您可以使用save_post 钩例如,如果您有自定义的帖子类型stack, 挂钩可以更改为save_post_stack.
要将post slug设置为内容的前几个字,请执行以下操作:
add_action( \'save_post_stack\', \'wpse251743_set_title\', 10, 3 );
function wpse251743_set_title ( $post_id ){
//This temporarily removes action to prevent infinite loops
remove_action( \'save_post_stack\', \'wpse251743_set_title\' );
$post = get_post( $post_id );
$post_content = $post->post_content;
//GET THE FIRST THREE WORDS
$words = array_slice(str_word_count( $post_content, 2), 0, 5);
$post_name = implode(\' \', $words );
//update title
wp_update_post( array(
\'ID\' => $post_id,
\'post_name\' => $post_name, //Wordpress would generate the slug based on the post name
));
//redo action
add_action( \'save_post_stack\', \'wpse251743_set_title\', 10, 3 );
}
Avoiding infinite loops: 如果要调用函数,如wp_update_post
其中包括save_post
钩子,钩子函数将创建一个无限循环。为了避免这种情况,请在调用所需函数之前先取消钩住函数,然后再重新钩住它。