wordpress—wp_query的使用方法

2020年01月4日22:27:49 发表评论 热度420 ℃

wp_query是一个wordpress用于复杂请求的的一个类,看到query懂开发的人就会反应这个是数据库查询的一个类,这个类可谓是非常有用的,可以帮助我们做很多复杂的查询。

wordpress---wp_query的使用方法

wp_query的使用方法也很简单:

  1. $query = new WP_Query( 'author=123' ); // 查询单个作者的文章
  2. $query = new WP_Query( 'author_name=rami' ); // 根据用户名查找
  3. $query = new WP_Query( 'author=2,6,17,38' ); // 查询多个人的文章
  4. $query = new WP_Query( 'author=-12' ); // 查询不属于某个人的文章 可以通过减号“-”来排除某位作者。
  5. $query = new WP_Query( 'cat=4' ); // 按分类ID
  6. $query = new WP_Query( 'category_name=staff' ); //查询某个分类下的文章(包含它的子分类)
  7. $query = new WP_Query( 'category__in=4' ); //查询某个分类下的文章(不包含它的子分类)
  8. $query = new WP_Query( 'cat=2,6,17,38' ); // ID 类似的,查询多个分类下的文章
  9. $query = new WP_Query( 'category_name=staff,news' ); // slug 类似的,查询多个分类下的文章
  10. $query = new WP_Query( 'cat=-12,-34,-56' ); //不包含某个分类
  11. // 查询同时属于多个分类的文章
  12. $query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) ); // 2 and 6
  13. $query = new WP_Query( array( 'category__in' => array( 2, 6 ) ) ); // 2 or 6

通过标签查询

可通过标签查询的条件包括:tag, tag_id, tag__and, tag__in, tag__not_in, tag_slug__and, tag_slug__in。

对应到上面分类的查询方法,不难理解每个条件如何使用,我不一一举例了。(注意:名字中没有slug的,用tag的id查询)。

简单使用示例:

  1. <?php
  2. // 调用的分类4,可以修改分类id  显示的前两篇文章,可以修改显示篇数
  3. $where = array('cat' =>'4','posts_per_page' =>'2',);
  4. $the_query = new WP_Query($where);
  5. // 开始循环
  6. if ( $the_query->have_posts() ) {//如果找到了结果,便输出以下内容
  7.         echo '<ul>';
  8.     while ( $the_query->have_posts() ) {//再次判断是否有结果
  9.         $the_query->the_post();//不用问为什么,每次都要写这个;
  10. ?>
  11. <li><a href="<?php the_permalink();?>"><?php the_title();?></a></li>
  12. <?php
  13.     }
  14.     echo '</ul>';
  15.     } else {
  16.         // 如果没有找到任何结果,就输出这个
  17.     }
  18.     wp_reset_postdata();//不用问为什么,每次都记得写就好
  19. ?>

简单示例:

  1. <?php
  2. $args = array(
  3.     // 用于查询的参数或者参数集合
  4. );
  5. // 自定义查询
  6. $the_query = new WP_Query( $args );
  7. // 判断查询的结果,检查是否有文章
  8. if ( $the_query->have_posts() ) :
  9.     // 通过查询的结果,开始主循环
  10.     while ( $the_query->have_posts() ) :
  11.         $the_query->the_post(); //获取到特定的文章
  12.         // 要输出的内容,如标题、日期等 
  13.     endwhile;
  14. endif;
  15. // 重置请求数据
  16. wp_reset_postdata();
  17. ?>

深入查看wp_query类

  1. <?php
  2. $args = array(
  3.     //作者参数 - Show posts associated with certain author.
  4.     //http://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters
  5.     'author' => '1,2,3,',                     //(int) - use author id [use minus (-) to exclude authors by ID ex. 'author' => '-1,-2,-3,']
  6.     'author_name' => 'luetkemj',              //(string) - use 'user_nicename' (NOT name)
  7.     'author__in' => array( 2, 6 ),            //(array) - use author id (available with Version 3.7).
  8.     'author__not_in' => array( 2, 6 ),        //(array)' - use author id (available with Version 3.7).
  9.     //类别参数 - Show posts associated with certain categories.
  10.     //http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
  11.     'cat' => 5,//(int) - use category id.
  12.     'category_name' => 'staff, news',          //(string) - Display posts that have these categories, using category slug.
  13.     'category_name' => 'staff+news',           //(string) - Display posts that have "all" of these categories, using category slug.
  14.     'category__and' => array( 2, 6 ),         //(array) - use category id.
  15.     'category__in' => array( 2, 6 ),          //(array) - use category id.
  16.     'category__not_in' => array( 2, 6 ),      //(array) - use category id.
  17.     //标签参数 - Show posts associated with certain tags.
  18.     //http://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters
  19.     'tag' => 'cooking',                       //(string) - use tag slug.
  20.     'tag_id' => 5,                            //(int) - use tag id.
  21.     'tag__and' => array( 2, 6),               //(array) - use tag ids.
  22.     'tag__in' => array( 2, 6),                //(array) - use tag ids.
  23.     'tag__not_in' => array( 2, 6),            //(array) - use tag ids.
  24.     'tag_slug__and' => array( 'red', 'blue'), //(array) - use tag slugs.
  25.     'tag_slug__in' => array( 'red', 'blue'),  //(array) - use tag slugs.
  26.     //分类参数(自定义分类法) - Show posts associated with certain taxonomy.
  27.     //http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
  28.     //Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays)
  29.     //This construct allows you to query multiple taxonomies by using the relation parameter in the first (outer) array to describe the boolean relationship between the taxonomy queries.
  30.     'tax_query' => array(                     //(array) - use taxonomy parameters (available with Version 3.1).
  31.     'relation' => 'AND',                      //(string) - Possible values are 'AND' or 'OR' and is the equivalent of running a JOIN for each taxonomy
  32.       array(
  33.         'taxonomy' => 'color',                //(string) - Taxonomy.
  34.         'field' => 'slug',                    //(string) - Select taxonomy term by ('id' or 'slug')
  35.         'terms' => array( 'red', 'blue' ),    //(int/string/array) - Taxonomy term(s).
  36.         'include_children' => true,           //(bool) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
  37.         'operator' => 'IN'                    //(string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.
  38.       ),
  39.       array(
  40.         'taxonomy' => 'actor',
  41.         'field' => 'id',
  42.         'terms' => array( 103, 115, 206 ),
  43.         'include_children' => false,
  44.         'operator' => 'NOT IN'
  45.       )
  46.     ),
  47.     //文章和页面参数 - Display content based on post and page parameters.
  48.     //http://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
  49.     'p' => 1,                               //(int) - use post id.
  50.     'name' => 'hello-world',                //(string) - use post slug.
  51.     'page_id' => 1,                         //(int) - use page id.
  52.     'pagename' => 'sample-page',            //(string) - use page slug.
  53.     'pagename' => 'contact_us/canada',      //(string) - Display child page using the slug of the parent and the child page, separated ba slash
  54.     'post_parent' => 1,                     //(int) - use page id. Return just the child Pages. (Only works with heirachical post types.)
  55.     'post_parent__in' => array(1,2,3)       //(array) - use post ids. Specify posts whose parent is in an array. NOTE: Introduced in 3.6 
  56.     'post_parent__not_in' => array(1,2,3),  //(array) - use post ids. Specify posts whose parent is not in an array.
  57.     'post__in' => array(1,2,3),             //(array) - use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use ignore_sticky_posts
  58.     'post__not_in' => array(1,2,3),         //(array) - use post ids. Specify post NOT to retrieve.
  59.     //NOTE: you cannot combine 'post__in' and 'post__not_in' in the same query
  60. //////Password Parameters - Show content based on post and page parameters. Remember that default post_type is only set to display posts but not pages.
  61.     //http://codex.wordpress.org/Class_Reference/WP_Query#Password_Parameters
  62.     'has_password' => true,                 //(bool) - available with Version 3.9
  63.                                               //true for posts with passwords; 
  64.                                               //false for posts without passwords; 
  65.                                               //null for all posts with and without passwords 
  66.     'post_password' => 'multi-pass',          //(string) - show posts with a particular password (available with Version 3.9)
  67. //////类型状态参数 - Show posts associated with certain type or status.
  68.     //http://codex.wordpress.org/Class_Reference/WP_Query#Type_Parameters
  69.     'post_type' => array(                   //(string / array) - use post types. Retrieves posts by Post Types, default value is 'post';
  70.             'post',                         // - a post.
  71.             'page',                         // - a page.
  72.             'revision',                     // - a revision.
  73.             'attachment',                   // - an attachment. The default WP_Query sets 'post_status'=>'published', but atchments default to 'post_status'=>'inherit' so you'll need to set the status to 'inherit' or 'any'.
  74.             'my-post-type',                 // - Custom Post Types (e.g. movies)
  75.             ),
  76.     //NOTE: The 'any' keyword available to both post_type and post_status queries cannot be used within an array. 
  77.     'post_type' => 'any',                   // - retrieves any type except revisions and types with 'exclude_from_search' set to true.  
  78. //////Type & Status Parameters - Show posts associated with certain type or status.
  79.     //http://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters
  80.     'post_status' => array(                 //(string / array) - use post status. Retrieves posts by Post Status, default value i'publish'.         
  81.             'publish',                      // - a published post or page.
  82.             'pending',                      // - post is pending review.
  83.             'draft',                        // - a post in draft status.
  84.             'auto-draft',                   // - a newly created post, with no content.
  85.             'future',                       // - a post to publish in the future.
  86.             'private',                      // - not visible to users who are not logged in.
  87.             'inherit',                      // - a revision. see get_children.
  88.             'trash'                         // - post is in trashbin (available with Version 2.9).
  89.             ),
  90.     //NOTE: The 'any' keyword available to both post_type and post_status queries cannot be used within an array. 
  91.     'post_status' => 'any',                 // - retrieves any status except those from post types with 'exclude_from_search' set to true.
  92. //////分页参数
  93.     //http://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
  94.     'posts_per_page' => 10,                 //(int) - number of post to show per page (available with Version 2.1). Use 'posts_per_page' => -1 to show all posts. 
  95.                                             //Note: if the query is in a feed, wordpress overwrites this parameter with the stored 'posts_per_rss' option. Treimpose the limit, try using the 'post_limits' filter, or filter 'pre_option_posts_per_rss' and return -1
  96.     'posts_per_archive_page' => 10,         //(int) - number of posts to show per page - on archive pages only. Over-rides showposts anposts_per_page on pages where is_archive() or is_search() would be true
  97.     'nopaging' => false,                    //(bool) - show all posts or use pagination. Default value is 'false', use paging.
  98.     'paged' => get_query_var('paged'),      //(int) - number of page. Show the posts that would normally show up just on page X when usinthe "Older Entries" link.
  99.                                             //NOTE: Use get_query_var('page'); if you want your query to work in a Page template that you've set as your static front page. The query variable 'page' holds the pagenumber for a single paginated Post or Page that includes the lt;!--nextpage--gt; Quicktag in the post content.
  100.     'nopaging' => false,                    // (boolean) - show all posts or use pagination. Default value is 'false', use paging.
  101.     'posts_per_archive_page' => 10,         // (int) - number of posts to show per page - on archive pages only. Over-rides posts_per_page and showposts on pages where is_archive() or is_search() would be true.
  102.     'offset' => 3,                          // (int) - number of post to displace or pass over. 
  103.                                             // Warning: Setting the offset parameter overrides/ignores the paged parameter and breaks pagination. for a workaround see: http://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination
  104.                                             // The 'offset' parameter is ignored when 'posts_per_page'=>-1 (show all posts) is used.
  105.     'paged' => get_query_var('paged'),      //(int) - number of page. Show the posts that would normally show up just on page X when usinthe "Older Entries" link.
  106.                                             //NOTE: This whole paging thing gets tricky. Some links to help you out:
  107.                                               // http://codex.wordpress.org/Function_Reference/next_posts_link#Usage_when_querying_the_loop_with_WP_Query
  108.                                               // http://codex.wordpress.org/Pagination#Troubleshooting_Broken_Pagination
  109.     'page' => get_query_var('page'),        // (int) - number of page for a static front page. Show the posts that would normally show up just on page X of a Static Front Page.
  110.                                             //NOTE: The query variable page holds the pagenumber for a single paginated Post or Page that includes the < !--nextpage--> Quicktag in the post content.
  111.     'ignore_sticky_posts' => false,         // (boolean) - ignore sticky posts or not (available with Version 3.1, replaced caller_get_posts parameter). Default value is 0 - don't ignore sticky posts. Note: ignore/exclude sticky posts being included at the beginning of posts returned, but the sticky post will still be returned in the natural order of that list of posts returned.
  112. //////排序参数 - Sort retrieved posts.
  113.     //http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
  114.     'order' => 'DESC',                      //(string) - Designates the ascending or descending order of the 'orderby' parameter. Default to 'DESC'.
  115.                                               //Possible Values:
  116.                                               //'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
  117.                                               //'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).
  118.     'orderby' => 'date',                    //(string) - Sort retrieved posts by parameter. Defaults to 'date'. One or more options can be passed. EX: 'orderby' => 'menu_order title'
  119.                                               //Possible Values:
  120.                                               //'none' - No order (available with Version 2.8).
  121.                                               //'ID' - Order by post id. Note the captialization.
  122.                                               //'author' - Order by author.
  123.                                               //'title' - Order by title.
  124.                                               //'name' - Order by post name (post slug).
  125.                                               //'date' - Order by date.
  126.                                               //'modified' - Order by last modified date.
  127.                                               //'parent' - Order by post/page parent id.
  128.                                               //'rand' - Random order.
  129.                                               //'comment_count' - Order by number of comments (available with Version 2.9).
  130.                                               //'menu_order' - Order by Page Order. Used most often for Pages (Order field in the EdiPage Attributes box) and for Attachments (the integer fields in the Insert / Upload MediGallery dialog), but could be used for any post type with distinct 'menu_order' values (theall default to 0).
  131.                                               //'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note alsthat the sorting will be alphabetical which is fine for strings (i.e. words), but can bunexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as yomight naturally expect).
  132.                                               //'meta_value_num' - Order by numeric meta value (available with Version 2.8). Also notthat a 'meta_key=keyname' must also be present in the query. This value allows for numericasorting as noted above in 'meta_value'.
  133.                                               //'title menu_order' - Order by both menu_order AND title at the same time. For more info see: http://wordpress.stackexchange.com/questions/2969/order-by-menu-order-and-title
  134.                                               //'post__in' - Preserve post ID order given in the post__in array (available with Version 3.5).
  135. //////日期参数 - Show posts associated with a certain time and date period.
  136.     //http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
  137.     'year' => 2014,                         //(int) - 4 digit year (e.g. 2011).
  138.     'monthnum' => 4,                        //(int) - Month number (from 1 to 12).
  139.     'w' =>  25,                             //(int) - Week of the year (from 0 to 53). Uses the MySQL WEEK command. The mode is dependenon the "start_of_week" option.
  140.     'day' => 17,                            //(int) - Day of the month (from 1 to 31).
  141.     'hour' => 13,                           //(int) - Hour (from 0 to 23).
  142.     'minute' => 19,                         //(int) - Minute (from 0 to 60).
  143.     'second' => 30,                         //(int) - Second (0 to 60).
  144.     'm' => 201404,                          //(int) - YearMonth (For e.g.: 201307).
  145.     'date_query' => array(                  //(array) - Date parameters (available with Version 3.7).
  146.                                               //these are super powerful. check out the codex for more comprehensive code examples http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
  147.       array(
  148.         'year' => 2014,                     //(int) - 4 digit year (e.g. 2011).
  149.         'month' => 4                        //(int) - Month number (from 1 to 12).
  150.         'week' => 31                        //(int) - Week of the year (from 0 to 53).
  151.         'day' => 5                          //(int) - Day of the month (from 1 to 31).
  152.         'hour' => 2                         //(int) - Hour (from 0 to 23).
  153.         'minute' => 3                       //(int) - Minute (from 0 to 59).
  154.         'second' => 36                      //(int) - Second (0 to 59).
  155.         'after'     => 'January 1st, 2013', //(string/array) - Date to retrieve posts after. Accepts strtotime()-compatible string, or array of 'year', 'month', 'day'
  156.         'before'    => array(               //(string/array) - Date to retrieve posts after. Accepts strtotime()-compatible string, or array of 'year', 'month', 'day'
  157.           'year'  => 2013,                  //(string) Accepts any four-digit year. Default is empty.
  158.           'month' => 2,                     //(string) The month of the year. Accepts numbers 1-12. Default: 12.
  159.           'day'   => 28,                    //(string) The day of the month. Accepts numbers 1-31. Default: last day of month.
  160.         ),
  161.         'inclusive' => true,                //(boolean) - For after/before, whether exact value should be matched or not'.
  162.         'compare' =>  '=',                  //(string) - Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '='
  163.         'column' => 'post_date',            //(string) - Column to query against. Default: 'post_date'.
  164.         'relation' => 'AND',                //(string) - OR or AND, how the sub-arrays should be compared. Default: AND.
  165.       ),
  166.     ),
  167. //////自定义字段参数 - Show posts associated with a certain custom field.
  168.     //http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
  169.     'meta_key' => 'key',                    //(string) - Custom field key.
  170.     'meta_value' => 'value',                //(string) - Custom field value.
  171.     'meta_value_num' => 10,                 //(number) - Custom field value.
  172.     'meta_compare' => '=',                  //(string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or ='. Default value is '='.
  173.     'meta_query' => array(                  //(array) - Custom field parameters (available with Version 3.1).
  174.        'relation' => 'AND',                 //(string) - Possible values are 'AND', 'OR'. The logical relationship between each inner meta_query array when there is more than one. Do not use with a single inner meta_query array.
  175.        array(
  176.          'key' => 'color',                  //(string) - Custom field key.
  177.          'value' => 'blue'                  //(string/array) - Custom field value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN') Using WP < 3.9? Check out this page for details: http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
  178.          'type' => 'CHAR',                  //(string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'. The 'type' DATE works with the 'compare' value BETWEEN only if the date is stored at the format YYYYMMDD and tested with this format.
  179.                                             //NOTE: The 'type' DATE works with the 'compare' value BETWEEN only if the date is stored at the format YYYYMMDD and tested with this format.
  180.          'compare' => '='                   //(string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '='.
  181.        ),
  182.        array(
  183.          'key' => 'price',
  184.          'value' => array( 1,200 ),
  185.          'compare' => 'NOT LIKE'
  186.        )
  187.     ),
  188. //////Permission Parameters - Display published posts, as well as private posts, if the user has the appropriate capability:
  189.     //http://codex.wordpress.org/Class_Reference/WP_Query#Permission_Parameters
  190.     'perm' => 'readable'                    //(string) Possible values are 'readable', 'editable'
  191. //////Caching Parameters
  192.     //http://codex.wordpress.org/Class_Reference/WP_Query#Caching_Parameters
  193.     //NOTE Caching is a good thing. Setting these to false is generally not advised.
  194.     'cache_results' => true,                //(bool) Default is true - Post information cache.
  195.     'update_post_term_cache' => true,       //(bool) Default is true - Post meta information cache.
  196.     'update_post_meta_cache' => true,       //(bool) Default is true - Post term information cache.
  197.     'no_found_rows' => false,               //(bool) Default is false. WordPress uses SQL_CALC_FOUND_ROWS in most queries in order to implement pagination. Even when you don’t need pagination at all. By Setting this parameter to true you are telling wordPress not to count the total rows and reducing load on the DB. Pagination will NOT WORK when this parameter is set to true. For more information see: http://flavio.tordini.org/speed-up-wordpress-get_posts-and-query_posts-functions
  198. //////Search Parameter
  199.     //http://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter
  200.     's' => $s,                              //(string) - Passes along the query string variable from a search. For example usage see: http://www.wprecipes.com/how-to-display-the-number-of-results-in-wordpress-search 
  201.     'exact' => true,                        //(bool) - flag to make it only match whole titles/posts - Default value is false. For more information see: https://gist.github.com/2023628#gistcomment-285118
  202.     'sentence' => true,                     //(bool) - flag to make it do a phrase search - Default value is false. For more information see: https://gist.github.com/2023628#gistcomment-285118
  203. //////Post Field Parameters
  204.     //For more info see: http://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter
  205.     //also https://gist.github.com/luetkemj/2023628/#comment-1003542
  206.     'fields' => 'ids'                       //(string) - Which fields to return. All fields are returned by default. 
  207.                                               //Possible values: 
  208.                                               //'ids'        - Return an array of post IDs. 
  209.                                               //'id=>parent' - Return an associative array [ parent => ID, … ].
  210.                                               //Passing anything else will return all fields (default) - an array of post objects.            
  211. //////Filters
  212.     //For more information on available Filters see: http://codex.wordpress.org/Class_Reference/WP_Query#Filters
  213. );
  214. ?>

具体使用示例:

  1. <?php
  2. $args = array('post_type'=>'post','showposts'=>'10','posts_per_page'=>'10','paged'=>get_query_var('paged'));
  3. $recendposts = new WP_Query( $args );
  4. if($recendposts->have_posts()) :
  5.     while($recendposts->have_posts()) :
  6.         $recendposts->the_post();
  7. ?>
  8.     <li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
  9. <?php
  10.     endwhile;
  11. endif;
  12. wp_reset_postdata();
  13. ?>

一个非常有用的查询,看得懂的拿去:

  1. <?php
  2.     // $where = array('cat'=>1,'posts_per_page'=2);
  3.     // $where = array('author'=>1);
  4.     $where = array('s'=>'工具','post_type'=>'post');
  5.     $the_query = new WP_Query( $where );
  6.     var_dump($the_query);
  7.     // 开始循环
  8.     if($the_query->have_posts()){//如果找到了结果,便输出以下内容
  9.         echo '<ul>';
  10.         while ( $the_query->have_posts() ) { //再次判断是否有结果
  11.             $the_query->the_post(); //不用问为什么,每次都要写这个;
  12. ?>
  13.             <li><a href="<?php the_permalink();?>"><?php the_title();?></a></li>
  14. <?php
  15.     }
  16.         echo '</ul>';
  17.     } else {
  18.         echo "没有找到相关的文章";
  19.     }
  20.     wp_reset_postdata();
  21. ?>

结合PHP的流程控制对上面的代码进行改造:

  1. <?php $where = array('s'=>'工具','post_type'=>'post'); ?>
  2. <?php $the_query = new WP_Query( $where ); ?>
  3. <?php if($the_query->have_posts()):?>
  4. <?php while ($the_query->have_posts()) : $the_query->the_post();?>
  5. <a href="<?php the_permalink();?>"><?php the_title();?></a><br>
  6. <?php endwhile; ?>
  7. <?php else : ?>
  8. //此处显示未找到文章时的信息,比如404相关
  9. <?php endif; ?>

查询5条浏览量最多的:

  1. <?php $where = array('s'=>'工具','post_type'=>'post','order'=>'DESC','meta_key'=>'views','orderby'=>'meta_value_num','posts_per_page'=>1); ?>
  2. <?php $the_query = new WP_Query( $where ); ?>
  3. <?php if($the_query->have_posts()):?>
  4. <?php while ($the_query->have_posts()) : $the_query->the_post();?>
  5. <a href="<?php the_permalink();?>"><?php the_title();?></a><br>
  6. <?php endwhile; ?>
  7. <?php else : ?>
  8. //此处显示未找到文章时的信息,比如404相关
  9. <?php endif; ?>

瓜皮猪

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: