如何根据自定义元字段自动设置文章标题



我想根据自定义元字段自动设置我的帖子标题,例如,我的自定义元字段有一个用户名。我希望帖子的标题是用户名。希望你能帮助我使用这个

您可以使用WordPress‘"save_post";钩子可以在保存帖子时根据帖子元来更改帖子标题。假设你喜欢一个名为";name_of_user";并且您想要相应地更改文章标题

add_action('save_post', 'wpse_update_post_title');
function wpse_update_post_title($post_id) {
// If this is just a revision, don't update the title yet.
if ( wp_is_post_revision( $post_id ) ) {
return;
}
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'wpse_update_post_title');
$user_name = get_post_meta( $post_id, 'name_of_user', true );
// Check if the meta for given key exists and then update the title 
if($user_name) {
$slug = str_replace(' ', '-', strtolower($user_name))
$post_update = array(
'ID'         => $post_id,
'post_title' => $user_name,
'post_name' => $slug // This swill update the url slug of the post too`enter code here`
);
wp_update_post( $post_update );
}
// re-hook this function
add_action('save_post', 'wpse_update_post_title');
}

上面的代码应该进入主题的functions.php文件

最新更新