开发者

Sort WordPress Meta Field By Date Using WP_Query

开发者 https://www.devze.com 2023-03-29 07:05 出处:网络
I have posts with meta data that I want to sort by \'LiveStreamDate\'. Format of meta field is: yyyy/mm/dd.

I have posts with meta data that I want to sort by 'LiveStreamDate'. Format of meta field is: yyyy/mm/dd.

My current code below:

$recent = new WP_Query('cat='.$spcatid.'&paged=' . $paged); while($recent->have_posts()) : $recent->the_post();
$tmpLiveTime = get_post_custom_values("LiveStreamTime");
$tmpLiveDate = get_post_custom_values("LiveStreamDate");
$tmpLiveCompetition = get_post_custom_values("LiveStreamCompetition");
$tmpLiveMatch = get_p开发者_StackOverflow中文版ost_custom_values("LiveStreamMatch");

NORMAL LOOP STUFF HERE

Any ideas? I have looked through the WP_QUERY examples using meta fields and values - but how to construct the query (or add another query) to end up with data sorted by meta field by value of it's date?

Cheers BK


You can use the follow example:

add_filter('posts_orderby', 'my_filter_posts_orderby' );
$query = new WP_Query( array(
    'meta_key' => 'LiveStreamDate',
    'cat' => $spcatid,
    'paged' => $paged,
) );
remove_filter( 'posts_orderby', 'my_filter_posts_orderby' );

function my_filter_posts_orderby( $orderby )
{
    global $wpdb;
    $orderby = $wpdb->postmeta . '.meta_value DESC, ' . $orderby;
    return $orderby;
}

while($query->have_posts()) { 
$query->the_post();
echo get_post_custom_values("LiveStreamDate");
}

The list of possible parameters are in WordPress file

/wp-includes/query.php

inside this function:

/**
     * Fills in the query variables, which do not exist within the parameter.
     *
     * @since 2.1.0
     * @access public
     *
     * @param array $array Defined query variables.
     * @return array Complete query variables with undefined ones filled in empty.
     */
    function fill_query_vars($array) {
        $keys = array(
            'error'
            , 'm'
            , 'p'
            , 'post_parent'
            , 'subpost'
            , 'subpost_id'
            , 'attachment'
            , 'attachment_id'
            , 'name'
            , 'static'

(...)

0

精彩评论

暂无评论...
验证码 换一张
取 消