根据不同的帖子属性更改自动帖子标题生成

时间:2016-01-19 作者:Pete

我有以下代码片段,可以自动生成帖子标题。我想换一下$post_type\'post_title\' => $post_type . \' Job #\' . $post_id 行到其他post属性,如post_datepost_author.

function save_post_func_2134( $post_id ) {     
    $post_type = \'post\'; //Change your post_type here     
    if ( $post_type == get_post_type ( $post_id ) ) {  //Check and update for the specific $post_type         
        $my_post = array(
            \'ID\'           => $post_id,
            \'post_title\' => $post_type . \' Job #\' . $post_id //Construct post_title 
        );
         remove_action(\'save_post\', \'save_post_func_2134\'); //Avoid the infinite loop 
        // Update the post into the database
        wp_update_post( $my_post );              
    }
}
add_action( \'save_post\', \'save_post_func_2134\' );

2 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

post对象作为save_post action (do_action ( \'save_post\', int $post_ID, WP_Post $post, bool $update )。您可以使用此post对象从中获取发布日期和作者。

您可以尝试以下操作:(注意:代码未经测试)

add_action( \'save_post\', \'wpse_214927_alter_title\', 10, 2 );
function wpse_214927_alter_title ( $post_id, $post_object )
{
    // Target only specific post type
    if (    \'my_specific_post_type\'       !== $post_object->post_type
         && \'my_other_specific_post_type\' !== $post_object->post_type
    )
        return;

    // Remove the current action
    remove_action( current_filter(), __FUNCTION__ );

    $post_date      = $post_object->post_date;
    $format_date    = DateTime::createFromFormat( \'Y-m-d H:i:s\', $post_date );
    $date_formatted = $format_date->format( \'Y-m-d\' ); // Set correct to display here
    $post_author    = $post_object->post_author;
    $author_name    = get_the_author_meta( \'display_name\', $post_author ); // Adjust as needed

    $my_post = [
        \'ID\' => $post_id,
        \'post_title\' => $author_name . \' Job \' . $date_formatted // Change as needed
    ];
    wp_update_post( $my_post );
}
重要的是,您应该在需要的地方添加验证和卫生

SO网友:Linnea Huxford

使用该功能get_post_meta($post_id) 获取post元数据。

希望这有帮助。