我想每当我发布帖子时运行 sql 查询。我只是不确定如何将其包装在函数中,以及在单击发布时将该函数粘贴到何处才能生效。以下命令是我需要的,在 phpMyAdmin-SQL 中成功运行,并且它也在我的 WordPress 后端中正确反映。
INSERT INTO `databasename`.`wp_xxxxxx` (
`id` ,
`name` ,
`item_number` ,
`price` ,
`options_2`) VALUES (
'9', 'xxxx1', 'xxxx2', 'xxxxx3', 'xxxx4'
);
Run Code Online (Sandbox Code Playgroud)
但是,当我每次保存帖子时,如何让它在 PHP 中的 Functions.php 文件中运行?我尝试了以下操作,但我确信它是正确的,因为我之后进行了刷新并且未创建表:
function do_my_stuff($post_ID) {
mysql_query("INSERT INTO `databasename`.`wp_xxxxx` (
`id` ,
`name` ,
`item_number` ,
`price` ,
`options_2`) VALUES (
'9', 'xxxx1', 'xxxx2', 'xxxx3', 'xxxxx4'");
return $post_ID;
}
Run Code Online (Sandbox Code Playgroud)
add_action('save_post', 'do_my_stuff');
发布帖子时。它实际上是一个需要一些细节的产品。
以下是我想要填充 sql 查询的值。
item_number = 它应该是一个自定义字段后元值,来自名为“scode”的字段,目前我通过以下方式在我的单页模板上回显它:
ID, 'scode', true) ) echo do_shortcode(get_post_meta($post->ID, 'scode', $single = true)); ?>价格 = 价格,我还通过一个名为“价格”的自定义字段手动输入该价格,我目前通过以下方式回显:
options_2,我还通过名为“variations”的自定义字段值手动输入。
这一切都可以这样完成吗?
也许是这样的:
INSERT INTO `databasename`.`wp_cart66_products` (
`id` ,
`name` ,
`item_number` ,
`price` ,
`options_2`) VALUES (
'9', '<?php the_title(); ?>', '<?php if ( get_post_meta($post->ID, 'scode', true) ) echo do_shortcode(get_post_meta($post->ID, 'scode', $single = true)); ?>', '<?php $values = get_post_custom_values("price"); echo $values[0]; ?> ', '<?php $values = get_post_custom_values("variations"); echo $values[0]; ?> '
);
Run Code Online (Sandbox Code Playgroud)
请注意,我对 php 或 SQL 不太了解。我花了几个小时试图找到尽可能多的信息来提供可靠的请求。
您非常接近,当您将帖子保存到参考时,您定义的函数正在运行add_action,但内容do_my_stuff()不太正确。
建议使用$wpdb全局变量来访问数据库,甚至引用表。例如,如果您正在使用wp_您希望用于$wpdb->users表的默认前缀wp_users。如果它不是标准表但仍使用前缀,例如插件,则可以使用{$wpdb->prefix}tablename. 您还应该使用它$wpdb->prepare来帮助确保生成有效的 SQL(以及防止 SQL 注入)。
尝试这个:
function do_my_stuff($post_ID) {
global $wpdb; // the wordpress database object
// check if this is a revision, if so use the parent post_id
if ($parent_id = wp_is_post_revision( $post_id )) $post_ID = $parent_id;
// load the post
$post = get_post($post_ID);
// load postmeta values
$scode = get_post_meta($post_ID, 'scode', true);
$price = get_post_meta($post_ID, 'price', true);
$variations = get_post_meta($post_ID, 'variations', true);
// create sql, use %d for digits, %s for strings
$sql = $wpdb->prepare("INSERT INTO {$wpdb->prefix}xxxxx (id, name, item_number, price, options_2) VALUES (%d, %s, %s, %s)", $post_ID, $post->post_name, $scode, $price, $variations);
// run the query
$wpdb->query($sql);
}
// add custom function to run on post save
add_action('save_post', 'do_my_stuff');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1656 次 |
| 最近记录: |