2016-09-01 37 views
2

我在WordPress中有一個要求,如果分類術語字符串等於帖子標題,更新slug(因爲永久鏈接規則在這種情況下失敗)。WordPress的wp_update_post不更新post_name

我的代碼是:

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 嵌塞沒有更新。 請幫助一樣。我已經嘗試了所有可用於此問題的解決方案。它必須通過的functions.php做

+0

$結果= wp_update_post($ update_args);應該是$ result = wp_update_post(args); – Juergen

回答

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);