2021.05.21WEB - PHP WordPress
カスタムフィールドでソート、絞り込み等
//セットした引数を取得
$plice = $_GET['plice'];
//リンク(引数をセット)
<a href="./?plice=DESC">高い順</a>
<a href="./?plice=ASC">安い順</a>
<a href="./?plice=p99-201">99~201円のみ</a>
<a href="./?plice=p199-301">199~301円のみ</a>
//ループの内容を条件分岐で出しわける
<?php
/*** 高い順 ***/
if($plice == 'DESC') {
$customPostArg = array(
'posts_per_page' => -1, //出す数は任意
'post_type' => 'post', //カスタム投稿タイプ
'meta_query' => array(
array(
'key' => 'plice', //並び替えに使うカスタムフィールドの名前
)
),
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
}
/*** 安い順 ***/
else if($plice == 'ASC') {
$customPostArg = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'plice',
)
),
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
}
/*** 99~201円のみ ***/
else if($plice == 'p99-201') {
$customPostArg = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'plice',
'value' => array("99","201"), //valueを2つ設定し、
'compare' => 'BETWEEN', //BETWEENで上記valueの間のものを表示
'type'=>'NUMERIC'
)
),
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
}
/*** 199~301円のみ ***/
else if($plice == 'p199-301') {
$customPostArg = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'plice',
'value' => array("199","301"),
'compare' => 'BETWEEN',
'type'=>'NUMERIC'
)
),
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
}
//実際にループしていく
$customPosts = get_posts($customPostArg);
if ($customPosts) : foreach ($customPosts as $post) : setup_postdata($post);
?>
<a href="<?php the_permalink(); ?>">値段:<?php the_field('plice'); ?></a>
<?php endforeach; endif; ?>