我需要在滑块中发布以两种特定分类法显示的文章和页面。我试图合并$ args和$ args2,但这给了我一个错误。谁能告诉我如何正确编写代码?谢谢!
这是代码:
<?php
$slider_counter = 0;
$args = array(
'post_type' => 'post',
'category_name' => 'slider'
);
$args2 = array(
'post_type' => 'page',
'tax_query' => array(
array(
'taxonomy' => 'my_taxonomy',
'field' => 'slug',
'terms' => 'slider'
)
)
);
$merged_query_args = array_merge( $args, $args2 );
$query_slider = new WP_Query ( $merged_query_args );
while ( $query_slider->have_posts() ) :
$query_slider->the_post(); ?>
<?php $slider_counter++ ;?>
<?php $slider_image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $post ->ID ), 'slider_img' );?>
<div class="swiper-slide <?php if ($slider_counter ==1) { echo 'active'; } ?>">
<a href="<?php the_permalink(); ?>"><img src="<?php echo $slider_image_attributes[0]; ?>" class="d-block w-100" alt="..."></a>
<div class="carousel-caption d-none d-md-block">
<div class="dispaly-3"><a href="<?php the_permalink(); ?>" class="slider-a"><?php the_title(); ?></a></div>
</div>
</div>
<?php endwhile;
wp_reset_query();
wp_reset_postdata(); ?>
首先,当您合并具有相同键的两个数组时,第二个将覆盖第一个,因此合并的结果将为:
Array
(
[post_type] => page
[category_name] => slider
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => my_taxonomy
[field] => slug
[terms] => slider
)
)
)
这就是为什么查询可能不返回任何结果。
我找到了此代码:
// Set our defaults to keep our code DRY
$defaults = [
'fields' => 'ids',
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'cache_results' => false
];
// Set query args for query 1
$args = [
'post_type' => 'post',
'posts_per_page' => '1',
];
// Set query args for query 2
$args1 = [
'post_type' => 'page',
'posts_per_page' => '3',
];
$post_query = get_posts( array_merge( $defaults, $args ) );
$page_query = get_posts( array_merge( $defaults, $args1 ) );
// Merge the two results
$post_ids = array_merge ( $post_query, $page_query ); //. You can swop around here
// We can now run our final query, but first mke sure that we have a valid array
if ( $post_ids ) {
$final_args = [
'post_type' => ['post', 'page'],
'post__in' => $post_ids,
'orderby' => 'post__in', // If you need to keep the order from $post_ids
'order' => 'ASC' // If you need to keep the order from $post_ids
];
$loop = new WP_Query( $final_args );
// Run your loop as normal
}
如何使它适合我的情况?我尝试将其集成,但它给了我一个错误。