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