学做网站培训课程介绍

当前位置:

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();?>

还可以这样写:(可以指定分类)


<?php
$args=array(
'meta_key' => 'views',//字段名
'orderby' => 'meta_value_num',//按字段值排序
'post__not_in' => get_option( 'sticky_posts' ),//排除置顶文章
'cat' => '1',//指定分类数组
//'category__in'=>array(1,2,3),
'posts_per_page'=>4,//显示文章数量
'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',//查询字段
'type'=>'NUMERIC',//类型:数值:NUMERIC 字符:CHAR 二进制数:BINARY
'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(
'relation' => 'AND', // AND:必须同时匹配 OR:任意一个匹配
array(
'key'=>'paixu',//筛选字段1
'value'=>'',
'compare'=>'!='//不为空
),
array(
'key'=>'演示网站',//筛选字段2
'value'=>'dedeym',
'compare'=>'LIKE'
)
),
'showposts' =>10,//显示数量
);
$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();?>

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关教程