我找到了另一种方法。或多或少基于Konstantin-Kovshenin方法。不确定是否将其标记为正确。它可能会导致性能问题,但仍然存在。首先,制作一个过滤器,使默认的“标题”模板标记按内容的第一个字母填充空标题字段。
add_filter( \'the_title\', \'empty_title_fix\' );
add_filter( \'single_post_title\', \'empty_title_fix\');
function empty_title_fix( $titles ) {
if ( strlen( trim( $titles ) ) < 1 ) {
$daa = get_post($idd);
$conten = $daa->post_content;
$contents = trim(strip_tags($conten));
if (strlen($contents) > 40) {
$titles = substr($contents, 0, 40) . \'...\';
//this is if the content has no words (like with a single image or video). It can be different.
} elseif (strlen($contents) == 0) {
$format = get_post_format();
if ( false === $format ) {
$format = \'post\';
}
$titles = ucfirst($format);
} else {
$titles = substr($contents, 0, 40);
}
}
return $titles;
}
这是为了使用与上述类似的方法自动生成后期段塞,以替换“数字”段塞。
add_action(\'publish_post\', \'insert_automatic_post_slug\', 10, 2);
function insert_automatic_post_slug($postID, $post) {
if($post->post_name == $postID) {
$content = trim(strip_tags($post->post_content));
if (strlen($content) > 40) {
$title = substr($content, 0, 40) . \'...\';
} elseif (strlen($content) == 0) {
$format = get_post_format();
if ( false === $format ) {
$format = \'post\';
}
$title = ucfirst($format);
} else {
$title = substr($content, 0, 40);
}
$post->post_name = sanitize_title($title);
$result = wp_update_post($post);
}
}
然后,所有的标题标记anywere都被内容的第一个字符或其他回退字符替换。如果标题标记为空,则可以在主题中手动选择是否显示标题标记。
//Simplified version to get the point across.
<?php $my_id = get_the_ID();
$post_id = get_post($my_id);
$post_title = $post_id->post_title;
if (!empty($post_title)) { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>