自动增量自定义帖子类型标题

时间:2013-05-28 22:39:51

标签: php mysql wordpress

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

BTW我没有回应标题,它只会被我看到。

3 个答案:

答案 0 :(得分: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;
}

在这种情况下,用户无法根据标题修改自定义帖子类型标题和整个事物增量。

答案 1 :(得分:0)

你可以试试这个

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;
}

只需将此代码粘贴到functions.php文件中即可。

答案 2 :(得分: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;
}