我正在制作一个插件中的函数,该函数将在帖子移动到垃圾箱时删除数据库行。但是,我不能使用get_posts()
获取post_id。
function delete_condition($post)
{
global $wpdb;
$allposts = get_posts(array(
'numberposts' => -1,
'category' => 0, 'orderby' => 'date',
'order' => 'DESC', 'include' => array(),
'exclude' => array(), 'meta_key' => '',
'meta_value' =>'', 'post_type' => 'job',
'suppress_filters' => true));
foreach( $allposts as $postinfo ) {
$wpdb->delete('rule', array('post_id' => $postinfo));
}
}
add_action('wp_trash_post', 'delete_condition', 10, 1);
谢谢
您在这里使用的动作钩子,wp_trash_post
,将$post_id作为参数传递给函数。参见:https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post
听起来你想从一个表中删除所有的行,这些行与被丢弃的行具有相同的post ID。
我想你可能会想这样写:
function delete_condition( $post_id ) {
global $wpdb;
// Delete rows in the rule table which have the same post_id as this one
if ( 'job' === get_post_type( $post_id ) ) {
$wpdb->delete('rule', array('post_id' => $post_id ) );
}
}
add_action('wp_trash_post', 'delete_condition', 10, 1);
$postinfo是对象。您只需要post的ID。所以你应该写$postinfo->ID。用下面的-
替换你的循环foreach( $allposts as $postinfo ) {
$postinfoID = $postinfo->ID;
$wpdb->delete('rule', array('post_id' => $postinfoID));
}
<?php
function delete_condition($post)
{
global $wpdb;
$allposts = get_posts(array(
'numberposts' => -1,
'post_status' => 'any',
'category' => 0, 'orderby' => 'date',
'order' => 'DESC', 'include' => array(),
'exclude' => array(), 'meta_key' => '',
'meta_value' =>'', 'post_type' => 'job',
'suppress_filters' => true));
foreach( $allposts as $postinfo ) {
$wpdb->delete('rule', array('post_id' => $postinfo));
}
}
add_action('wp_trash_post', 'delete_condition', 10, 1);
?>