0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Wordpressで複数のQueryを取得し、1つにまとめる

Last updated at Posted at 2021-11-24

あまりやることはないし綺麗ではないけれどどうしてもやらないといけないとき用。

	<?php 
        //taxonomy.phpで処理した例
        $term_id = get_queried_object_id();

        //条件1
	$post_args = array(
		'post_type' => 'post01-topics',
        'tax_query' => array(
            array(
                'taxonomy' => 'country',
                'field' => 'slug',
                'terms' => $term
            )
		),
		'posts_per_page' => 0,
	);
        //条件2
	$post_args2 = array(
		'post_type' => 'post02-topics',
		'meta_query' => array(
			'relation' => 'AND',
			array(
				'key' => 'country',
				'value' => $term_id,
				'compare' => '=',
			),
			array(
				'key' => 'association',
				'value' => 'お知らせ',
				'compare' => '=',
			),
		),
		'posts_per_page' => 0,
	);

        //条件1と2をガッチャンコ
	$myposts = array_merge( get_posts($post_args), get_posts($post_args2));

        //post_date(日付)でソート
	usort($myposts, function ($a, $b) {
        return $a->post_date> $b->post_date? -1 : 1;
    }); 

        //後はいつもどおりループ
	if ($myposts) : ?>
	<section>
		<h1>お知らせ</h1>
		<ul>
		<?php foreach($myposts as $post){
			setup_postdata($post); ?>
			<li><span class="_date"><?php the_time('Y.m.d'); ?></span>
				<a href="<?php the_permalink(); ?>">?php the_permalink(); ?><?php the_title(); ?></a>
			</li>
		<?php }
		wp_reset_postdata(); ?>
		</ul>
	</section>
	<?php endif; ?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?