2013-05-28 43 views
1

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

顺便说一句我没有回应标题,它只会被我看到。

回答

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文件的代码。

+0

对我来说,它总是将标题设置为#5,即使没有创建任何帖子。 –

2

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

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

相关问题