Php Wordpress wp_update_post未更新post_name
我在WordPress中有一个要求,如果分类术语字符串等于post title,则更新slug(因为在这种情况下permalink规则失败) 我的代码是:Php Wordpress wp_update_post未更新post_name,php,wordpress,Php,Wordpress,我在WordPress中有一个要求,如果分类术语字符串等于post title,则更新slug(因为在这种情况下permalink规则失败) 我的代码是: 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(
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');
}
}
在要求的帖子中,我获得了日志:是,结果为0。
slug没有更新。
请帮我做同样的事情。我已经尝试了所有解决这个问题的方法。它必须通过函数来完成。php我终于能够使用:wp\u insert\u post()解决它了。
$result=wp\u update\u post($update\u args);应该是$result=wp\u update\u post(args);您应该在变量
$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);