【发布时间】:2018-08-13 12:06:40
【问题描述】:
我继承了一个 WordPress Twig 站点,并正在尝试修改一个现有的短代码,该短代码在页面中用于为博客页面和单一类别的帖子页面输出博客文章。
这些简码很明显:
[blog_list category_exclude="in-the-news"] 用于“博客”页面,不包括带有category_exclude 的“新闻”类别。
[blog_list category="in-the-news"] 用于带有category 的类别的“新闻帖子”页面。
我添加了另一个类别,即视频,这适用于视频帖子类别页面:
[blog_list category="videos"]
但我需要做的是在博客页面上使用category_exclude 排除多个类别,如下所示:
[blog_list category_exclude="in-the-news videos"]
这不起作用,所以我知道我需要为下面的 if 循环修改 query_posts 来确定要排除的类别。如何让category_exclude 参数使用多个参数?
这是完整的简码功能:
add_shortcode('blog_list', 'blog_get_list');
function blog_get_list($params) {
global $paged;
$blog_posts = [];
if (!isset($paged) || !$paged){
$paged = 1;
}
$page_size = 20;
$context = Timber::get_context();
if (!empty($params['page_size'])) {
$page_size = $params['page_size'];
}
$args = array(
'post_type' => 'post',
'posts_per_page' => $page_size,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish'
);
if (!empty($params['category'])) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'terms' => explode(',', $params['category']),
'field' => 'slug',
'operator' => 'IN',
),
);
}
if (!empty($params['category_exclude'])) { // Exclude categories
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'terms' => explode(',', $params['category_exclude']),
'field' => 'slug',
'operator' => 'NOT IN',
),
);
}
query_posts($args);
$posts = Timber::get_posts();
foreach ($posts as $p) {
$blog_posts[] = acco_blog_get_single($p);
}
$context['blog_posts'] = $blog_posts;
$context['pagination'] = Timber::get_pagination();
return Timber::compile('blog/index.twig', $context);
}
function acco_blog_get_single($post) {
$blog_post = [
'id' => $post->ID,
'link' => $post->link,
'title' => $post->title(),
'author_name' => $post->author_name,
'date' => $post->post_date,
'summary' => $post->get_field('summary'),
'body' => $post->get_field('body')
];
$feature_image = $post->get_image('feature_image');
if ($feature_image->ID){
$blog_post['feature_image'] = $feature_image;
}
return $blog_post;
}
【问题讨论】: