php - 如何可靠地增加 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 表单页面只是刷新自己
解决方案
推荐阅读
- python - 如何正确编写 if 语句 - Python
- windows - 如何在 VB.Net 应用程序中嵌入图标,以便它们可以用作快捷方式图标?
- javascript - 如何根据用户当前所在的页面部分对链接进行颜色更改?
- angularjs - 使用 Tailwind 的交互式汉堡菜单
- nuget - Nuget 还原提示“此应用无法在您的 PC 上运行”
- npm - 使用 npm 在 ubuntu 20 上安装无服务器会出现错误
- flutter - Flutter 远程日志记录
- sass - Node-sass 未编译
- python - RuntimeWarning 的 Pandas 错误问题
- javascript - 在不滚动 iFrame 父级的情况下将滚动反应到 Element 底部