Files
wordpress-theme-aksrt/templates/parts/home-modules/module-category.php
T

73 lines
2.2 KiB
PHP

<?php
/**
* Home Module · Category
*
* config: { cat_id, count, layout, columns, title? }
*/
defined('ABSPATH') || exit;
$cfg = get_query_var('aksrt_module_config', []);
if (!is_array($cfg)) $cfg = [];
$cat_id = isset($cfg['cat_id']) ? (int) $cfg['cat_id'] : 0;
$count = max(1, min(20, (int) ($cfg['count'] ?? 8)));
$layout = (string) ($cfg['layout'] ?? 'card');
$columns = max(1, min(6, (int) ($cfg['columns'] ?? 4)));
$title = (string) ($cfg['title'] ?? '');
if (!in_array($layout, ['card', 'list', 'masonry', 'grid-cms'], true)) {
$layout = 'card';
}
$args = [
'posts_per_page' => $count,
'post_status' => 'publish',
'no_found_rows' => true,
];
if ($cat_id > 0) {
$args['cat'] = $cat_id;
// 分类页通常希望同时展示资源 post,post 已天然包含资源;旧 CPT 兼容时合并
$args['post_type'] = function_exists('aksrt_resource_post_types')
? array_unique(array_merge(['post'], aksrt_resource_post_types()))
: ['post'];
} else {
$args['post_type'] = 'post';
}
$query = new WP_Query($args);
if (!$query->have_posts()) {
wp_reset_postdata();
return;
}
$display_title = $title;
if ($display_title === '' && $cat_id > 0) {
$term = get_term($cat_id, 'category');
if ($term && !is_wp_error($term)) $display_title = $term->name;
}
$more_link = $cat_id > 0 ? get_category_link($cat_id) : '';
?>
<section class="home-module home-module--category container" aria-label="<?php echo esc_attr($display_title ?: __('分类', 'aksrt')); ?>">
<header class="home-module__header">
<h2 class="home-module__title"><?php echo esc_html($display_title ?: __('精选内容', 'aksrt')); ?></h2>
<?php if ($more_link) : ?>
<a class="home-module__more" href="<?php echo esc_url($more_link); ?>">
<?php esc_html_e('查看更多', 'aksrt'); ?> <i class="fas fa-arrow-right" aria-hidden="true"></i>
</a>
<?php endif; ?>
</header>
<div class="post-grid post-grid--<?php echo esc_attr($layout); ?>" style="--cols:<?php echo (int) $columns; ?>;">
<?php
set_query_var('aksrt_post_card_layout', $layout);
while ($query->have_posts()) {
$query->the_post();
get_template_part('templates/parts/content', 'post-card');
}
set_query_var('aksrt_post_card_layout', '');
wp_reset_postdata();
?>
</div>
</section>