簡體   English   中英

設置Wordpress自定義帖子類型的默認標題?

[英]Set default title for Wordpress Custom Post Types?

我有一個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 );

您有錯別字:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM