Функция похожих записей Wordpress. Как добавить текст, заголовок
Есть функция для вывода в записи ссылок на другие записи из этой рубрики:
/**
* Предыдущие записи из рубрики (относительно текущей записи) +
* кольцевая перелинковка (можно указывать таксономию и тип записи).
*
* Кэширует результат в объектный кэш, если он включен.
*
* Вызываем функцию так:
*
* echo kama_previous_posts_from_tax_lis( [
* 'post_num' => 5,
* 'format' => '{date:j.M.Y} - {a}{title}{/a}',
* ] );
*
* @param array|string $args {
* Parameters passed as array or query string.
*
* @type int $post_num Количество ссылок.
* @type string $format {thumb} {date:j.M.Y} - {a}{title}{/a} ({comments})
* @type string $list_tag Тег-обертка каждой ссылки.
* @type string $tax Таксономия. пр. category.
* @type string $post_type Тип записи. пр. post.
* }
*
* @version 1.2
*/
function kama_previous_posts_from_tax_lis( $args = array() ){
global $post, $wpdb;
$rg = (object) wp_parse_args( $args, [
'post_num' => 5,
'format' => '',
'list_tag' => 'li',
'tax' => 'category',
'post_type' => 'post',
] );
if( wp_using_ext_object_cache() ){
$cache_key = md5( __FUNCTION__ . $post->ID );
$cache_flag = __FUNCTION__;
if( $cache_out = wp_cache_get( $cache_key, $cache_flag ) ){
return $cache_out;
}
}
$SELECT = "SELECT ID, post_title, post_date, comment_count, guid
FROM $wpdb->posts p
LEFT JOIN $wpdb->term_relationships rel ON (p.ID = rel.object_id)
LEFT JOIN $wpdb->term_taxonomy tax ON (rel.term_taxonomy_id = tax.term_taxonomy_id)";
$WHERE = $wpdb->prepare( 'WHERE p.post_date < %s', $post->post_date );
$sub_query_tax_id = $wpdb->prepare(
"SELECT term_id FROM $wpdb->term_relationships rl
LEFT JOIN $wpdb->term_taxonomy tx ON (rl.term_taxonomy_id = tx.term_taxonomy_id)
WHERE object_id = %d AND tx.taxonomy = %s
LIMIT 1",
$post->ID, $rg->tax
);
$AND = $wpdb->prepare("
AND tax.term_id = ($sub_query_tax_id) AND tax.taxonomy = %s
AND p.post_status = 'publish'
AND p.post_type = %s ORDER BY p.post_date DESC",
$rg->tax, $rg->post_type
);
$LIMIT = 'LIMIT ' . (int) $rg->post_num;
$sql = "$SELECT $WHERE $AND $LIMIT";
$res = $wpdb->get_results( $sql );
$count_res = count( $res );
// если количество меньше нужного, делаем 2-й запрос (кольцевая перелинковка)
if( ! $res || $count_res < $rg->post_num ){
$NOT_IN = $post->ID;
foreach( $res as $id ){
$NOT_IN .= ",$id->ID";
}
$sql = "$SELECT WHERE p.ID NOT IN ($NOT_IN) $AND LIMIT " . (int) ( $rg->post_num - $count_res );
$res2 = $wpdb->get_results( $sql );
$res = array_merge( $res, $res2 );
}
if( ! $res ){
return '';
}
// вывод
if( $rg->format ){
preg_match( '!{date:(.*?)}!', $rg->format, $date_m );
}
$add_thumb = false !== strpos( $rg->format, '{thumb}' );
$out = '';
foreach( $res as $pst ){
$x = ( @ $x === 'li1' ) ? 'li2' : 'li1';
$a = '<a href="' . get_permalink( $pst->ID ) . '" title="' . esc_attr( $pst->post_title ) . '">';
if( $rg->format ){
$formated = strtr( $rg->format, [
'{title}' => esc_html( $pst->post_title ),
'{a}' => $a,
'{/a}' => '</a>',
'{comments}' => $pst->comment_count ?: '',
'{thumb}' => $add_thumb ? str_replace( '{thumb}', get_the_post_thumbnail( $pst->ID, 'thumbnail' ), $formated ) : '',
] );
// есть дата
if( $date_m ){
$formated = str_replace( $date_m[0], apply_filters( 'the_time', mysql2date( $date_m[1], $pst->post_date ) ), $formated );
}
}
else{
$formated = $a . esc_html( $pst->post_title ) . '</a>';
}
$out .= "\t<li class=\"$x\">$formated</li>\n";
}
if( wp_using_ext_object_cache() ){
wp_cache_add( $cache_key, $out, $cache_flag );
}
return $out;
}
В шаблоне потом выводится так:
<?php echo kama_previous_posts_from_tax('post_num=10'); ?>
Подскажите, пожалуйста, как туда добавить заголовок. Типа "Похожие записи". То есть, чтобы он выводился, только если есть другие записи.
Источник: Stack Overflow на русском