Wordpress:删除术语时删除术语

时间:2016-08-12 11:55:48

标签: php wordpress

我试图删除该术语被删除时与分类术语相关联的所有帖子(某种类型,在本例中为#34;图表")。

这就是我现在所拥有的:

add_action( 'delete_term', 'remove_site', 10, 3 );

function remove_site( $term_id, $tt_id, $taxonomy ){
  if ($taxonomy != 'sites')
    return false;

  $args = array(
    'posts_per_page' => -1,
    'post_type' => 'chart',
    'tax_query' => array(
      array(
        'taxonomy' => 'sites',
        'terms'    => $term_id,
      ),
    ),
  );

  $posts = get_posts( $args );
  foreach ($posts as $post) {
    wp_delete_post( $post->ID, true );
  }
}
正确调用

remove_site(),但$ posts为空。它似乎是' tax_query' (因为没有它,它可以工作并删除所有图表帖子),但我无法看到tax_query的错误?

1 个答案:

答案 0 :(得分:0)

所以......我看到的问题是'delete_term'在被删除后被触发。

因此,在删除后的状态中,该术语中没有帖子,因此尝试循环播放帖子将无效。

就我而言,需要删除的帖子只能从自定义分类法中附加一个术语,所以我这样做了:

//Remove Client Pages when Client is deleted
add_action( 'delete_term', 'remove_site', 10, 3 ); //run code when a term is deleted

function remove_site( $term_id, $tt_id, $taxonomy ){
  if ($taxonomy != 'client-name') //If term is not in your taxonomy.. don't run code
    return false;

// args to query posts that now have NO taxonomy term
  $args = array(
    'post_type' => 'client',
    'tax_query' => array(
        array(
            'taxonomy' => 'client-name',
            'operator' => 'NOT EXISTS', 
        ),
    ),
  );

  $client_pages = get_posts( $args );

  foreach ($client_pages as $client_page) {

        wp_trash_post( $client_page->ID);  // trash all posts that have no term in your taxonomy.
  }
}