首页 > wordpress > WordPress常用函数WP_Query详解二

WordPress常用函数WP_Query详解二

WordPress常用函数 W P _Query 是在制作WordPress CMS主题时必用函数,简单而且好用。W P _Query 是WordPress的精华,在下面我们将实例说明 W P _Query 的用法。

更多用法(英文)

Time Parameters

Show posts associated with a certain time period.

year (int) – 4 digit year (e.g. 2011).
monthnum (int) – Month number (from 1 to 12).
w (int) – Week of the year (from 0 to 53). Uses the MySQL WEEK command. The mode is dependent on the “start _of _week” option.
day (int) – Day of the month (from 1 to 31).
hour (int) – Hour (from 0 to 23).
minute (int) – Minute (from 0 to 60).
second (int) – Second (0 to 60).
Returns posts for just the current date:

$ today = getdate();
$ query = new W P _Query( ’year=’ . $ today["year"] . ’ & monthnum=’ . $ today["mon"] . ’ & day=’ . $ today["mday"] );
Returns posts for just the current week:

$ week = date(’W’);
$ year = date(’Y’);
$ query = new W P _Query( ’year=’ . $ year . ’ & w=’ . $ week );
Returns posts dated December 20:

$ query = new W P _Query( ’monthnum=12 & day=20’ );
Note: The queries above return posts for a specific date period in history, i.e. “Posts from X year, X month, X day”. They are unable to fetch posts from a timespan relative to the present, so queries like “Posts from the last 30 days” or “Posts from the last year” are not possible with a basic query, and require use of the posts _where filter to be completed. The examples below use the posts _where filter, and should be modifyable for most time-relative queries.

Return posts for March 1 to March 15, 2010:

// Create a new filtering function that will add our where clause to the query
function filter _where( $ where = ’’ ) {
    // posts for March 1 to March 15, 2010
    $ where .= " AND post _date >= ’2010-03-01’ AND post _date <  ’2010-03-16’";
    return $ where;
}

add _filter( ’posts _where’, ’filter _where’ );
$ query = new W P _Query( $ query _string );
remove _filter( ’posts _where’, ’filter _where’ );
Return posts from the last 30 days:

// Create a new filtering function that will add our where clause to the query
function filter _where( $ where = ’’ ) {
    // posts in the last 30 days
    $ where .= " AND post _date > ’" . date(’Y-m-d’, strtotime(’-30 days’)) . "’";
    return $ where;
}

add _filter( ’posts _where’, ’filter _where’ );
$ query = new W P _Query( $ query _string );
remove _filter( ’posts _where’, ’filter _where’ );
Return posts 30 to 60 days old

// Create a new filtering function that will add our where clause to the query
function filter _where( $ where = ’’ ) {
    // posts  30 to 60 days old
    $ where .= " AND post _date >= ’" . date(’Y-m-d’, strtotime(’-60 days’)) . "’" . " AND post _date < = ’" . date(’Y-m-d’, strtotime(’-30 days’)) . "’";
    return $ where;
}

add _filter( ’posts _where’, ’filter _where’ );
$ query = new W P _Query( $ query _string );
remove _filter( ’posts _where’, ’filter _where’ );

Custom Field Parameters

Show posts associated with a certain custom field.

meta _key (string) – Custom field key.
meta _value (string) – Custom field value.
meta _value _num (number) – Custom field value.
meta _compare (string) – Operator to test the ‘meta _value‘. Possible values are ‘!=’, ‘>’, ‘>=’, ‘<  ’, o r ‘< =’. Default value is ‘=’.
meta _query (array) – Custom field parameters (available with Version 3.1).
key (string) – Custom field key.
value (string|array) – Custom field value (Note: Array support is limited to a compare value of ‘IN’, ‘NOT IN’, ‘BETWEEN’, or ‘NOT BETWEEN’)
compare (string) – Operator to test. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘< ’, ‘< =’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘NOT EXISTS’ (in W P 3.5). Default value is ‘=’.
type (string) – Custom field type. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’. Default value is ‘CHAR’.
Simple Custom Field Query:

Display posts where the custom field key is ‘color’, regardless of the custom field value:

$ query = new W P _Query( ’meta _key=color’ );
Display posts where the custom field value is ‘blue’, regardless of the custom field key:

$ query = new W P _Query( ’meta _value=blue’ );
Display Page where the custom field value is ‘blue’, regardless of the custom field key:

$ query = new W P _Query( ’meta _value=blue & post _type=page’ );
Display posts where the custom field key is ‘color’ and the custom field value is ‘blue’:

$ query = new W P _Query( array( ’meta _key’ => ’color’, ’meta _value’ => ’blue’ ) );
Display posts where the custom field key is ‘color’ and the custom field value IS NOT ‘blue’:

$ query = new W P _Query( array( ’meta _key’ => ’color’, ’meta _value’ => ’blue’, ’meta _compare’ => ’!=’ ) );
Display ‘product’(s) where the custom field key is ‘price’ and the custom field value that is LESS THAN OR EQUAL TO 22.
By using the ‘meta _value’ parameter the value 99 will be considered greater than 100 as the data are stored as ‘strings’, not ‘numbers’. For number comparison use ‘meta _value _num’.

$ query = new W P _Query( array( ’meta _key’ => ’price’, ’meta _value’ => ’22’, ’meta _compare’ => ’< =’, ’post _type’ => ’product’ ) );
Display posts with a custom field value of zero (0), regardless of the custom field key:

$ query = new W P _Query( array ( ’meta _value’ => ’ _W P _zero _value’ ) );
Single Custom Field Handling:

Display posts from a single custom field:

$ args = array(
    ’post _type’ => ’product’,
    ’meta _query’ => array(
        array(
            ’key’ => ’color’,
            ’value’ => ’blue’,
            ’compare’ => ’NOT LIKE’
        )
    )
 );
$ query = new W P _Query( $ args );
(Note that meta _query expects nested arrays, even if you only have one query.)

Multiple Custom Field Handling:

Display posts from several custom field:

$ args = array(
    ’post _type’ => ’product’,
    ’meta _query’ => array(
        array(
            ’key’ => ’color’,
            ’value’ => ’blue’,
            ’compare’ => ’NOT LIKE’
        ),
        array(
            ’key’ => ’price’,
            ’value’ => array( 20, 100 ),
            ’type’ => ’numeric’,
            ’compare’ => ’BETWEEN’
        )
    )
 );
$ query = new W P _Query( $ args );
Display posts that have meta key ‘color’ NOT LIKE value ‘blue’ OR meta key ‘price’ with values BETWEEN 20 and 100:

 $ args = array(
    ’post _type’ => ’product’,
    ’meta _query’ => array(
        ’relation’ => ’OR’,
        array(
            ’key’ => ’color’,
            ’value’ => ’blue’,
            ’compare’ => ’NOT LIKE’
        ),
        array(
            ’key’ => ’price’,
            ’value’ => array( 20, 100 ),
            ’type’ => ’numeric’,
            ’compare’ => ’BETWEEN’
        )
    )
  );
 $ query = new W P _Query( $ args );

Permission Parameters

Display published posts, as well as private posts, if the user has the appropriate capability:

$ query = new W P _Query( array( ’post _status’ => array( ’publish’, ’private’ ), ’perm’ => ’readable’ ) );

Parameters relating to caching

In addition to the parameters mentioned above, you can also pass three different cache control flags: cache _results, update _post _term _cache, and update _post _meta _cache.

If you need to stop the data retrieved from being added to the cache you can pass cache _results as false (this is a master flag that will also turn off the other two), or you can be specific and pass update _post _term _cache and/or update _post _meta _cache depending on your requirements.

// Retrieve 50 posts, but don’t add post meta to the cache
$ query = new W P _Query( array( ’posts _per _page’ => 50, ’update _post _meta _cache’ => false ) );
// Retrieve 50 posts, but don’t add post information to the cache
$ query = new W P _Query( array( ’posts _per _page’ => 50, ’cache _results’ => false ) );
In general usage you should not need to use these – adding to the cache is the right thing to do – however they may be useful in specific circumstances.

An example of such circumstances might be when using a W P _Query to retrieve a list of post titles and URLs to be displayed, but in which no other information about the post will be used and the taxonomy and meta data won’t be needed. By not loading this information, you can save time from the extra unnecessary SQL queries.

Note: If a persistent object cache backend (such as memcached) is used, these flags are set to false by default since there is no need to update the cache every page load when a persistent cache exists.


Post Field Parameters

fields
’ids’: return an array of post IDs
’id=>parent’: return an associative array [ parent => ID, … ]
any other value or empty (default): return an array of post objects

Search Parameter

Show posts based on a keyword search

s (string) – Search keyword
Return posts that match the search term “keyword”:

$ query = new W P _Query( ’s=keyword’ );

上一篇: Varnish

下一篇: 使用Dnspod+加速乐(全球CDN+缓存)提高网站访问速度