删除分类并删除与其相关的所有帖子

时间:2016-10-14 作者:sameer sheikh

我想删除所有与分类法相关的帖子。

例如,每当我从后端删除分类法时,应该删除该分类法的所有帖子。

我尝试了以下代码,钩名为delete_term_taxonomy

   <?php
    add_action(\'delete_term_taxonomy\',\'wp_custom_delete_taxonomy\');
    function wp_custom_delete_taxonomy($tt_id) {
           global $wpdb; // add action here


        $get_term_id = $wpdb->get_results("SELECT meta_value, user_id
                                        FROM `wp_usermeta`
                                        WHERE `meta_key`=\'term_id\'
                                        AND `meta_value` =".$tt_id."");

        $post_metattid = $get_term_id[0]->meta_value;
        $user_id = $get_term_id[0]->user_id;

        $get_post_id = get_user_meta($user_id,\'post_id\',true);

        $delete_all_model = $wpdb->query("DELETE p,pm,tr,d,e 
                                        FROM wp_posts as p 
                                        LEFT JOIN wp_postmeta as pm ON p.id=pm.post_id 
                                        LEFT JOIN wp_term_relationships as tr ON tr.object_id=pm.post_id 
                                        LEFT JOIN wp_term_taxonomy d ON  d.term_taxonomy_id = tr.term_taxonomy_id 
                                        LEFT JOIN wp_terms e ON  e.term_id = d.term_id 
                                        WHERE tr.term_taxonomy_id=".$tt_id."");
  }  
    ?>
这不是删除分类法的帖子,任何人都知道这一点。

1 个回复
最合适的回答,由SO网友:CodeMascot 整理而成

首先,我们需要找到与我们的分类术语相关的帖子。然后,我们将通过运行foreach 环尝试以下代码。我希望这对你有用-

add_action(\'pre_delete_term\', \'the_dramatist_delete_posts_on_taxonomy_delete\', 1, 1 );
function the_dramatist_delete_posts_on_taxonomy_delete( $term ) {
    $args = array(
        \'post_type\' => \'post\', // post_type
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'post_tag\', // taxonomy_name
                \'field\' => \'id\',
                \'terms\' => $term
            )
        )
    );

    $posts = get_posts($args);

    foreach ( $posts as $post ){
        wp_delete_post( $post->ID, true );
    }
}