Files
wordpress-theme-aksrt/inc/helpers/search/aksrt-search-posts.php
T

101 lines
3.1 KiB
PHP

<?php
/**
* Search panel hot posts (zibll zib_get_search_posts parity).
*
* @package AKSRT
*/
defined('ABSPATH') || exit;
if (!function_exists('aksrt_get_search_posts')) :
/**
* Build hot-post slides for the search dropdown.
*
* @param int $count Number of posts.
* @param string $orderby views|date|modified|…
* @param bool $show_img Use graphic cards (true) or text list (false).
*/
function aksrt_get_search_posts(int $count = 6, string $orderby = 'views', bool $show_img = true): string {
$count = max(1, min(20, $count));
$args = [
'posts_per_page' => $count,
'ignore_sticky_posts' => true,
'post_status' => 'publish',
'post_type' => 'post',
'no_found_rows' => true,
'update_post_meta_cache' => true,
'update_post_term_cache' => false,
];
if ($orderby === 'views') {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'aksrt_post_views';
$args['order'] = 'DESC';
} else {
$allowed = ['date', 'modified', 'comment_count', 'rand', 'title'];
$args['orderby'] = in_array($orderby, $allowed, true) ? $orderby : 'date';
$args['order'] = 'DESC';
}
$query = new WP_Query($args);
// Fallback when no posts have views meta yet.
if (!$query->have_posts() && $orderby === 'views') {
wp_reset_postdata();
$args['orderby'] = 'date';
unset($args['meta_key']);
$query = new WP_Query($args);
}
$lists = '';
while ($query->have_posts()) {
$query->the_post();
$post_id = (int) get_the_ID();
$title = get_the_title($post_id);
if ($title === '') {
continue;
}
if ($show_img && function_exists('aksrt_graphic_card')) {
$thumb = get_the_post_thumbnail_url($post_id, 'medium');
if (!$thumb) {
$thumb = get_template_directory_uri() . '/assets/img/placeholder.svg';
}
$views = function_exists('aksrt_get_post_views') ? (int) aksrt_get_post_views($post_id) : 0;
$views_txt = function_exists('aksrt_format_number')
? aksrt_format_number($views)
: (string) $views;
$time_ago = human_time_diff(get_the_time('U', $post_id), current_time('timestamp'));
$info = '<item>' . esc_html(sprintf(/* translators: %s: relative time */ __('%s前', 'aksrt'), $time_ago))
. '</item><item class="pull-right"><i class="fa fas fa-eye" aria-hidden="true"></i> '
. esc_html((string) $views_txt) . '</item>';
$lists .= '<div class="swiper-slide em09 mr10" style="width:160px;">';
$lists .= aksrt_graphic_card([
'type' => 'style-3',
'class' => '',
'img' => $thumb,
'alt' => $title,
'link' => [
'url' => get_permalink($post_id),
'target' => '',
],
'text1' => $title,
'text2' => mb_strlen($title) > 29 ? mb_substr($title, 0, 29) . '…' : $title,
'text3' => $info,
'lazy' => true,
'height_scale' => 70,
], false);
$lists .= '</div>';
} else {
$lists .= '<li><a class="icon-circle text-ellipsis" href="'
. esc_url(get_permalink($post_id)) . '">'
. esc_html($title) . '</a></li>';
}
}
wp_reset_postdata();
return $lists;
}
endif;