首页 > 解决方案 > 如何可靠地增加 CPT 标题和 slug?

问题描述

我有一个名为“任务”的自定义帖子类型,带有 ACF 前端来发布每个新帖子。

我想对最终用户隐藏标题,并让标题和 slug 自动设置和增加。

任务 1、任务 2、任务 3 等。

我在这里尝试了所有可以找到的代码示例,似乎没有什么是可靠的。

有没有人得到他们过去使用过的可靠工作的东西?

试过这个;

add_filter('title_save_pre','auto_generate_post_title');
function auto_generate_post_title($title) {
   global $post;
   if (isset($post->ID)) {
      if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){
         // get the current post ID number
         $id = get_the_ID();
         // add ID number with order strong
         $title = 'produktionsauftrag-'.$id;} }
   return $title; 
}

只给我一个标题为“无标题”的帖子,下一个帖子 ID 为 slug

试过这个

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', 'future', 'pending', 'private', 'trash'];
    if( $data['post_type'] == 'task' && !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('task');
        $published_posts = $count_posts->publish;

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

            // Save the title and the slug
            $data['post_title'] = date('Y-m') . '-1';
            $data['post_name'] = sanitize_title($data['post_title']);

        } else {

            // Get the most recent post
            $args = array(
                'numberposts' => 1,
                'orderby' => 'post_date',
                'order' => 'DESC',
                'post_type' => 'task',
                '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 = intval($number[2]) + 1;

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

        }        
    }
    return $data;
}

什么都不做,acf 表单页面只是刷新自己

标签: phpwordpress

解决方案


推荐阅读