if (!function_exists('get_article_for_category')) {
function get_article_for_category(
$category,
$posts_per_page = 5,
$tag = '' ,// 新增参数:标签(tag)
$include_meta = true,
$include_acf = true,
$orderby = 'menu_order',
$order = 'DESC'
) {
// 限制只允许的排序字段
$allowed_orderby = array('date', 'menu_order');
if (!in_array($orderby, $allowed_orderby)) {
$orderby = 'date'; // 默认回退到按时间排序
}
// 设置基础查询参数
$args = array(
'posts_per_page' => $posts_per_page,
'orderby' => $orderby,
'order' => $order,
);
// 添加分类查询条件
if (is_numeric($category)) {
$args['tax_query'][] = array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $category,
);
} else {
$args['tax_query'][] = array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $category,
);
}
if (!empty($tag)) {
$args['tax_query']['relation'] = 'AND';
if (is_numeric($tag)) {
$args['tax_query'][] = array(
'taxonomy' => 'post_tag',
'field' => 'term_id',
'terms' => $tag,
);
} else {
$args['tax_query'][] = array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $tag,
);
}
}
if ($orderby === 'menu_order') {
$args['orderby'] = 'menu_order';
}
$query = new WP_Query($args);
if ($query->have_posts()) {
$posts = array();
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$post_data = array(
'id' => $post_id,
'title' => get_the_title(),
'permalink' => get_the_permalink(),
'excerpt' => get_the_excerpt(),
'content' => get_the_content(),
'thumbnail' => has_post_thumbnail() ? get_the_post_thumbnail_url() : '',
'date' => get_the_date(),
'author' => get_the_author(),
'modified_date' => get_the_modified_date(),
'type' => get_post_type(),
'status' => get_post_status(),
'comment_count' => get_comments_number(),
);
// 获取所有自定义字段(post meta)
if ($include_meta) {
$meta = get_post_meta($post_id);
$post_data['meta'] = $meta;
}
// 如果使用了 ACF,获取 ACF 字段
if ($include_acf && function_exists('get_fields')) {
$acf_fields = get_fields();
if ($acf_fields) {
$post_data['acf'] = $acf_fields;
}
}
$posts[] = $post_data;
}
wp_reset_postdata();
return $posts;
}
return false;
}
}
最新发布