2016-09-07 117 views
1

我在插件中製作一個函數,當帖子移動到垃圾箱時,函數將刪除數據庫行。但是,我無法使用get_posts()獲得post_id。如何獲取所有post_id刪除帖子? Wordpress

這裏是我的代碼:

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); 

感謝

回答

1

行動掛鉤你使用這裏,wp_trash_post,傳遞$ POST_ID給函數作爲參數。請參閱:https://codex.wordpress.org/Plugin_API/Action_Reference/trash_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); 
0

$ postinfo是對象。您只需要發佈帖子的ID。所以你應該寫$ postinfo-> ID。用下面的替換你的循環 -

foreach($allposts as $postinfo) { 
      $postinfoID = $postinfo->ID; 
      $wpdb->delete('rule', array('post_id' => $postinfoID)); 
    } 
0
<?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); 
?> 
相關問題