1

我创建了一个自定义帖子类型“推荐”并删除了对标题的支持。我想自动增加标题,例如证词#1、证词#2、证词#3 等。现在它保存为“自动草稿”。任何帮助,将不胜感激。

顺便说一句,我没有重复标题,它只会对我可见。

4

2 回答 2

2

对@the-alpha 提供的代码进行了一些改进。

// Use a filter to make the change
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr ) {

// Check for the custom post type and if it's in trash
// We only need to modify if it when it's going to be published
$posts_status = ['publish', 'future', 'draft', 'pending', 'private', 'trash'];
if( $data['post_type'] == 'oferta' && !in_array($data['post_status'], $posts_status)) {

    // Count the number of posts to check if the current post is the first one
    $count_posts = wp_count_posts('you custom post type');
    $published_posts = $count_posts->publish;

    // Check if it's the first one
    if ($published_posts == 0) {

        $data['post_title'] = date('Y-m') . '-1';

    } else {

        // Get the most recent post
        $args = array(
            'numberposts' => 1,
            'orderby' => 'post_date',
            'order' => 'DESC',
            'post_type' => 'you custom post type',
            'post_status' => 'publish'
        );
        $last_post = wp_get_recent_posts($args);
        // Get the title
        $last_post_title = $last_post['0']['post_title'];
        // Get the title and get the number from it.
        // We increment from that number
        $number = explode('-', $last_post_title);
        $number = $number[2] + 1;

        // Save the title.
        $data['post_title'] = date('Y-m') . '-' . $number;

    }        
}
return $data;
}

在这种情况下,用户无法修改自定义帖子类型标题,并且整个内容会根据标题递增。

于 2015-02-27T10:41:00.367 回答
0

在从前端自定义帖子标题设置为#1的帖子提交时,但在第二次帖子提交时不会增加到#2..

这是functions.php中使用的确切代码

add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
function modify_post_title( $data , $postarr )
   {
if( $data['post_type'] == 'your custom post type' ) {
    $last_post = wp_get_recent_posts( '1');
    $last__post_id = (int)$last_post['0']['ID'];
    $data['post_title'] = 'Testimony #' . ($last__post_id+1);
}
return $data;
}
于 2018-10-07T12:16:34.477 回答