自定义调用文章在网站建设中很常用,wordpress也很人性化,用新建查询new WP_Query就能实现相关功能。WP_Query怎么用呢?随ytkah一起来看看吧
我们知道wordpress的主循环
但其实是隐藏了一些参数,比如
两段代码是等效的,为了保持代码的简洁性,WordPress 隐藏了全局的主循环变量 $wp_query。
WP_Query最基础用法
WP_Query 这个万能的文章查询类,有人把 WP_Query 所有的参数做了一个总结,然后注释了一下,供有需要的朋友查阅使用。
<?php
$args = array(
'author' => '1,2,3,'
'author_name' => 'luetkemj',
'cat' => 5,
'category_name' => 'staff', 'news',
'category__and' => array( 2, 6 ),
'category__in' => array( 2, 6 ),
'category__not_in' => array( 2, 6 ),
'tag' => 'cooking',
'tag_id' => 5,
'tag__and' => array( 2, 6),
'tag__in' => array( 2, 6),
'tag__not_in' => array( 2, 6),
'tag_slug__and' => array( 'red', 'blue'),
'tag_slug__in' => array( 'red', 'blue'),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'color',
'field' => 'slug',
'terms' => array( 'red', 'blue' ),
'include_children' => true,
'operator' => 'IN'
),
array(
'taxonomy' => 'actor',
'field' => 'id',
'terms' => array( 103, 115, 206 ),
'include_children' => false,
'operator' => 'NOT IN'
)
),
'p' => 1,
'name' => 'hello-world',
'page_id' => 1,
'pagename' => 'sample-page',
'pagename' => 'contact_us/canada',
'post_parent' => 1,
'post__in' => array(1,2,3),
'post__not_in' => array(1,2,3),
'post_type' => array(
'post',
'page',
'revision',
'attachment',
'my-post-type',
),
'post_status' => array(
'publish',
'pending',
'draft',
'auto-draft',
'future',
'private',
'inherit',
'trash'
),
'post_type' => 'any',
'post_status' => 'any',
'posts_per_page' => 10,
'posts_per_archive_page' => 10,
'nopaging' => false,
'paged' => get_query_var('paged'),
'offset' => 3,
'order' => 'DESC',
'orderby' => 'date',
'ignore_sticky_posts' => false,
'year' => 2012,
'monthnum' => 3,
'w' => 25,
'day' => 17,
'hour' => 13,
'minute' => 19,
'second' => 30,
'meta_key' => 'key',
'meta_value' => 'value',
'meta_value_num' => 10,
'meta_compare' => '=',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'type' => 'CHAR',
'compare' => '='
),
array(
'key' => 'price',
'value' => array( 1,200 ),
'compare' => 'NOT LIKE'
)
'perm' => 'readable'
'no_found_rows' => false,
'cache_results' => true,
'update_post_term_cache' => true,
'update_post_meta_cache' => true,
's' => $s,
'exact' => true
'sentence' => true
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
endwhile;
endif;
wp_reset_postdata();
?>
参考资料https:
还有一些例子
<?php
$args = array(
'post_type'=>'post'
);
$query=new WP_Query($args);
if($query->have_posts()):while($query->have_posts()):$query->the_post();
?>
<?php the_title();?>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
调用单篇文章
调用id为36的单篇文章的新建查询如下
等同于
调用指定page页面或category分类页可以用类似的写法
调用多篇文章
调用id为34、32、30的文章
post__in默认调用的是文章信息,如果要调用页面,则需要指定类型
调用除了id为3以外的文章
调用全部文章
调用全部页面
本文标签:
声明:本文由代码号注册/游客用户【以蕊】供稿发布,本站不对用户发布的WordPress自定义查询WP_Query使用方法介绍信息内容原创度和真实性等负责。如内容侵犯您的版权或其他权益,请留言并加以说明。站长审查之后若情况属实会及时为您删除。同时遵循 CC 4.0 BY-SA 版权协议,尊重和保护作者的劳动成果,转载请标明出处链接和本声明内容。本文作者:以蕊» https://www.ebingou.cn/dmh/14231.html
很赞哦! (0)