1

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

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

问题是当帖子更新时,如果标题和 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 值以便在使用新值更新帖子之前找到术语?

4

0 回答 0