设置Wordpress自定义帖子类型的默认标题?

时间:2013-11-27 23:05:17

标签: wordpress

我有一个Wordpress自定义帖子类型“精选书籍”,它使用副标题来指定书籍的标题。例如:“特色书:饥饿游戏”

是否可以自动将帖子标题设为“精选书”?

我通过谷歌搜索找到了这段代码,但它不起作用(Wordpress后端返回空白页面/白屏死机)

代码中是否存在语法错误,或者这是不可能的?

function add_custom_title( $data, $postarr ) {
  if($data['post_type'] == 'featured-book') {
    if(empty($data['post_title'])) {
      $data['post_title'] = 'Featured Book';
    }
  }
  return $data;
}
add_filters('wp_insert_post_data', 'add_custom_title', 10, 2 );

2 个答案:

答案 0 :(得分:3)

你有一个错字:

add_filter( 'wp_insert_post_data', 'add_custom_title', 10, 2 );

答案 1 :(得分:0)

add_filter('wp_insert_post_data','add_custom_title',10,2); 此功能挂钩是否在发布帖子或发布更新时触发 我有类似的脚本在发布帖子上插入帖子标题,但是我的问题是它也在更新帖子上执行此功能。如何挂钩功能仅在发布后才能运行,而不能在更新时运行

我的代码

add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );  
function modify_post_title( $data , $postarr ) {

// Check for the custom post type and it's status
// We only need to modify it when it's going to be published

$posts_status = ['publish'];
if( $data['post_type'] == 'matrimony' && in_array($data['post_status'], $posts_status)) {

    $count_posts = wp_count_posts('matrimony');
    $published_posts = $count_posts->publish;
    $pending_posts = $count_posts->pending;
    if ($published_posts == 0) {
        if ($pending_posts == 0) {
            $data['post_title'] = 'ACMB' . '-1';
            $data['post_name'] = sanitize_title($data['post_title']);
        }
        else{
            // Get the most recent post
            $newposts = array(
                'numberposts' => 1,
                'orderby' => 'post_date',
                'order' => 'DESC',
                'post_type' => 'matrimony',
                'post_status' => 'publish'
            );

            $last_post = wp_get_recent_posts($newposts);
            $last__post_title = $last_post['0']['post_title'];
            $number = preg_split('/[^[:alnum:]]+/', $last__post_title);
            $number = $number[1] + 1;

            // Save the title.
            $data['post_title'] = 'ACMB' . '-' . $number;
            $data['post_name'] = sanitize_title($data['post_title']);
        }
    } 
    else {

    // Get the most recent post
    $newposts = array(
                'numberposts' => 1,
                'orderby' => 'post_date',
                'order' => 'DESC',
                'post_type' => 'matrimony',
                'post_status' => 'publish'
            );

    $last_post = wp_get_recent_posts($newposts);
    $last__post_title = $last_post['0']['post_title'];
    $number = preg_split('/[^[:alnum:]]+/', $last__post_title);
    $number = $number[1] + 1;

    // Save the title.
    $data['post_title'] = 'ACMB' . '-' . $number;
    $data['post_name'] = sanitize_title($data['post_title']);


}
}
return $data;
}