Wordpress-自动在特定类别的帖子标题中添加作者姓名

时间:2018-07-10 10:08:34

标签: wordpress

当我单击“发布”时,我想在帖子标题中自动添加帖子的作者姓名。

我尝试了此代码,但没有用:

add_action( 'wp_insert_post_data', 'obm_set_category_title', 99 );

function obm_set_category_title( $data, $postarr ) {

    if ( 'mycategoryname' == $postarr['post_category'] ) {

        $title = $data['post_author'] . ' : ' . $data['post_title'];
        $data['post_title'] = $title;
    }

    return $data;

}

?>

有什么建议吗?预先感谢:)!

2 个答案:

答案 0 :(得分:0)

乔纳森,
改用过滤器,操作可以使您执行某些操作,但确实希望返回数据-它们不对该数据执行任何操作。

FILTERS允许您影响正在处理的数据,因此是更好的选择。也许这个过滤器:https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data

我个人建议,与其在目录的标题中嵌入作者姓名,不如在显示时添加它。例如再次使用过滤器,但是这次也许是这个? https://codex.wordpress.org/Plugin_API/Filter_Reference/the_title

答案 1 :(得分:0)

尝试一下。

        function fun_update_post_title( $post_id, $post, $update  ) {
     //Get category by post id and put condition

        // If this is just a revision
        if ( wp_is_post_revision( $post_id ) )
            return;

        $post_author_name = get_the_author_meta( "display_name",$post->post_author );
        $post_title = $post_author_name."::".$post->post_title;

        $my_post = array(
          'ID'           => $post_id,
          'post_title'   => $post_title
      );




        // unhook this function so it doesn't loop infinitely
        remove_action('save_post', 'fun_update_post_title');
        // update the post, which calls save_post again
        wp_update_post( $my_post );
        // re-hook this function
        add_action('save_post', 'fun_update_post_title');
    }

   //call function whene post in save 
   add_action( 'save_post', 'fun_update_post_title', 10, 3 );
相关问题