docs
基本のループ
<ul>
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php echo esc_url(get_the_permalink()); ?>"><?php the_title() ?></a>
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
</ul>
複数のカスタムフィールドの値で並び替え
<?php
$args = array(
'paged' => $paged,
'post_type' => 'post',
'post_status' => 'any',
'posts_per_page' => 20,
'meta_query' => array(
'relation' => 'AND',
'acf_1' => array(
'key' => 'acf_1',
),
'acf_2' => array(
'key' => 'acf_2',
),
),
'orderby' => array(
'acf_1' => 'ASC',
'acf_2' => 'DESC',
),
);
$the_query = new WP_Query( $args ); ?>
ループに現在のページを含めない
<?php
$args = array(
'paged' => $paged,
'post_type' => 'post',
'post__not_in' => array($post->ID), // 配列で指定する必要あり
);
$the_query = new WP_Query( $args ); ?>
パラメータの条件分岐
<?php
if( is_front_page() && is_home() ) {
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC',
);
} else {
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'category_name' => $cat_slug,
'orderby' => 'date',
'order' => 'DESC',
);
}
$the_query = new WP_Query( $args ); ?>
外部ファイルから配列の変数を渡す
呼び出し側のファイル
<?php
$args = [
'category_name' => 'wordpress',
];
get_template_part('tmp/block', 'newPost', $args); ?>
テンプレート側のファイル
<?php
$args = array(
'category_name' => $args['category_name'],
'orderby' => 'date',
'order' => 'DESC',
);
$the_query = new WP_Query( $args ); ?>
pre_get_posts を使ったメインクエリ書き換え
/* メインクエリ書き換え - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
function twpp_change_sort_order( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( $query->is_archive() || is_search() ) {
$query->set( 'order', 'ASC' );
$query->set( 'orderby', 'title' );
$query->set( 'posts_per_page', -1 );
}
}
add_action( 'pre_get_posts', 'twpp_change_sort_order' );
https://qiita.com/ruka/items/e14280d34eddf49efad1