WordPress 实现通过自定义字段查询和排序

WordPress 实现通过自定义字段查询和排序

WordPress 建网站时,可以根据指定自定义字段进行排序,也可以按照指定字段查询需要的类型。这些功能都是通过 WP_Query()方法来实现的,下面分享一下二种代码。

WordPress 通过自定义字段进行排序

<?php
$args = array(
'post_type' => 'product',//文章类型,可删除
'orderby' => array(
'meta_value_num'=>'ASC'
),
'meta_key' => 'sortnum',//sortnum是字段名
);
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post(); ?>
<li> <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_query();?>

还可以这样写:

<?php
$args=array(
'meta_key' => 'views',//字段名
'orderby' => 'meta_value_num',//按字段值排序
'post__not_in' => get_option( 'sticky_posts' ),//排除置顶文章
'category__not_in' => array(1,2),//排序指定分类数组
'posts_per_page'=>8,//显示文章数量
'order' => 'DESC'
);
query_posts($args); while (have_posts()) : the_post();?>
<li> <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php endwhile;wp_reset_query();?>

WordPress 通过自定义字段进行查询

<?php
$args = array(
'meta_query'=>array(
array(
'key'=>'disabled',
'value'=>1,
'compare'=>'='
)
),
'showposts' =>6,
);
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post(); ?>
<li> <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_query();?>

也可以二者结合在一起实现查询和排序。

<?php
$args = array(
'post_type' => 'product',//文章类型
'orderby' => array(
'meta_value_num'=>'ASC'
),
'meta_key' => 'sort',//排序字段
'meta_query'=>array(
array(
'key'=>'disabled',//查询字段
'value'=>1,
'compare'=>'='
)
),
'showposts' =>6,
);
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post(); ?>
<li> <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_query();?>

如果想多个条件筛选,可以在代码里多加 array,如下:

<?php
$args = array(
 
'orderby' => array(
'meta_value_num'=>'ASC'
),
'meta_key' => 'paixu',//排序字段
 
'meta_query'=>array(
array(
'key'=>'paixu',//筛选字段1
'value'=>'',
'compare'=>'!='//不为空
),
array(
'key'=>'演示网站',//筛选字段2
'value'=>'dedeym',
'compare'=>'LIKE'
)
),
'showposts' =>300,//显示数量
);
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post(); ?>
 
<li> <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li>
 
<?php endwhile; ?>
<?php wp_reset_query();?>
温馨提示:本文最后更新于2022-05-12 20:32:05,某些文章具有时效性,若有错误或已失效,请在下方留言或联系乡野博文
您阅读这篇文章共花了: 0小时00分00秒
-----本页内容已结束,喜欢请分享!-----
© 版权声明
THE END
喜欢本站内容,请点【点赞】【分享】和【收藏】~
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容