不乱于心,不困于情。
不畏将来,不念过往。如此,安好。

WordPress WP_Query 使用方法

自定义调用文章在网站搭建中很常见,WordPress 也很人性化,通过新建查询 `new WP_Query` 就能实现相关功能。`WP_Query` 怎么用呢?随 ytkah 一起来看看吧

我们知道 WordPress 的主循环

<?php if ( have_posts() ) : 
    while ( have_posts() ) : the_post(); 
        the_title(); 
    endwhile; 
endif; ?> 

但其实隐藏了一些参数,比如

<?php if ( $wp_query->have_posts() ) : 
    while ( $wp_query->have_posts() ) : $wp_query->the_post(); 
        the_title(); 
    endwhile; 
endif;?> 

两段代码是等效的,为了保持代码的简洁性,WordPress 隐藏了全局的主循环变量 `$wp_query`。

`WP_Query` 最基础用法

<?php 
// WP_Query 所使用的参数 
$args = array( 'posts_per_page' => 3 ); 
// 调用 WP_Query 新建文章查询. 
$the_query = new WP_Query( $args ); 
if ( $the_query->have_posts() ) : 
    // 开始循环 
    while ( $the_query->have_posts() ) : $the_query->the_post(); 
        the_title(); 
        the_excerpt(); 
    // 结束循环 
    endwhile; 
else: 
    _e( '抱歉,未找到您需要的文章。', 'textdomain' ); 
endif; 
wp_reset_postdata(); 
?> 

`WP_Query` 这个万能的文章查询类,有人把 `WP_Query` 所有的参数做了一个总结,然后注释了一下,供有需要的朋友查阅使用。

<?php 
/** 
* WordPress 查询综合参考 
* 
* 官方文档: http://codex.wordpress.org/Class_Reference/WP_Query 
* 源代码: http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/query.php 
*/ 
$args = array( 
/** 
* 作者参数 - 显示某些作者发表的文章 
*/ 
'author' => '1,2,3,' //(整数) - 作者ID [使用减号 (-) 排除某个作者 ID, 如: 'author' => '-1,-2,-3,'] 
'author_name' => 'luetkemj', //(字符串) - 使用 'user_nicename' 用户昵称,(不是名称) 
/** 
* 分类参数 - 显示某个分类里面的文章 
*/ 
'cat' => 5,//(整数) - 分类id 
'category_name' => 'staff', 'news', //(字符串) - 分类别名(不是名称) 
'category__and' => array( 2, 6 ), //(数组) - 分类id 
'category__in' => array( 2, 6 ), //(数组) - 分类id 
'category__not_in' => array( 2, 6 ), //(数组) - 分类id 
/** 
* 标签参数 - 显示含有某些标签的文章 
*/ 
'tag' => 'cooking', //(字符串) - 标签别名 
'tag_id' => 5, //(整数) -标签id 
'tag__and' => array( 2, 6), //(数组) - 标签id 
'tag__in' => array( 2, 6), //(数组) - 标签id 
'tag__not_in' => array( 2, 6), //(数组) - 标签id 
'tag_slug__and' => array( 'red', 'blue'), //(数组) - 标签别名 
'tag_slug__in' => array( 'red', 'blue'), //(数组) - 标签别名 
/** 
* 自定义分类法参数 - 显示某些自定义分类法里面的文章 
* 重要提示: tax_query 使用多维数组 
* 这种查询结构允许我们查询多个自定义分类法 
*/ 
'tax_query' => array( //(数组) - 使用自定义分类法查询参数 (3.1及以后版本可用). 
  'relation' =>

赞(0)
未经允许不得转载:seo优化_前端开发_渗透技术 » WordPress WP_Query 使用方法