如何在WordPress中更新帖子后更新类别?

时间:2018-02-28 14:45:13

标签: php wordpress custom-post-type custom-fields taxonomy-terms

我有一个名为海滩的自定义帖子类型。每次创建帖子时都会创建一个类别,这是有效的。

我的类别与帖子类型具有相同的标题和相同的slug。

问题是当帖子更新时,如果标题和段塞发生变化,我就不能再将帖子链接到该类别。

此代码可用于创建类别:

function rci_custom_dynamic_beach_category ($post_id) {
  $post = get_post($post_id);

  if($post->post_status === 'auto-draft') return;
  if($post->post_type !== 'beaches') return;

  // Verify if the category exists already
  $exist = term_exists($post->post_name, 'beaches');

  if($exist !== 0 && $exist !== null) {

    // THE PROBLEM IS HERE

    // Get the category by the slug field
    $term = get_term_by('slug', $post->post_name, 'beaches');
    wp_update_term($term->term_id, 'beaches', array(
      'name' => $post->post_title,
      'slug' => $post->post_name
    ));
  }
  else {
    wp_insert_term($post->post_title, 'beaches', $args = array(
      'slug' => $post->post_name,
      'parent' => 'houses'
    ));
  }
} 

add_action('save_post', 'rci_custom_dynamic_beach_category');

有没有办法获得旧的slug值,以便在更新后使用新值找到该术语?

0 个答案:

没有答案