Wordpress wp_update_post没有更新post_name

时间:2016-09-01 13:08:51

标签: php wordpress

我在WordPress中有一个要求,如果分类术语字符串等于帖子标题,则更新slug(因为固定链接规则在这种情况下失败)。

我的代码是:

add_action('save_post', 'change_default_slug', 10,2);
function change_default_slug($post_id, $post) {
  error_log($post_id);
  error_log($post->post_title);
  error_log($post->post_name);

  $taxonomies=get_taxonomies('','names');
  $terms = wp_get_post_terms($post->ID, $taxonomies,  array("fields" => "names"));
  $terms = array_map('strtolower', $terms);

  error_log('terms :' . json_encode($terms));

  $title = strtolower($post->post_title);
  error_log('title : ' . $title);

  if(in_array($title, $terms)) {

    error_log('yessss');

    $args =  array (
      'ID'        => $post->ID,
      'post_name' => $post->post_name . "-post"
    );
    $result = wp_update_post($update_args);
    error_log('result');
    error_log(json_encode($result));
  } else {
    error_log('noooooooo');

  }
}

在所需的帖子上我得到了日志:Yesss结果为0。 slu is没有更新。 请帮忙。我已经尝试了所有可用于此问题的解决方案。它必须通过functions.php

完成

1 个答案:

答案 0 :(得分:0)

我终于可以使用以下方法解决它: wp_insert_post()

   $taxonomies=get_taxonomies('','names'); 
   $terms = wp_get_post_terms($post->ID, $taxonomies,  array("fields" => "all"));

   foreach($terms as $term) {

      if($term->taxonomy == 'category'){
           $categories[] = $term->term_id;
      } else if($term->taxonomy == 'post_tag'){
           $tags[] = $term->term_id;
      }
   }
    .
    .
    .
   //detach the hook to avoid infinite looping of the hook on post insert
   remove_action('save_post', 'change_default_slug', 10,2);

   //insert post
   $result =   wp_insert_post($post, true);

  //attach post tags to the current post (since not by default attached)
  wp_set_post_terms($post_id,$tags,'post_tag');

  //attach post categories to the current post (since not by default attached)
  wp_set_post_terms($post_id,$categories,'category');

  //re-activate the hook
  add_action('save_post', 'change_default_slug', 10,2);
相关问题