Order Wordpress Posts Based on Parent Category

UPDATE: I tried using the following code:

<?php if (is_category(events)) { 
$posts = query_posts($query_string . '&orderby=event_date&order=desc'); 
} else {
    $posts = query_posts($query_string . '&orderby=title&order=asc'); 
    }
?>

Is there a reason why this will not work? It seems that it works great in organizational posts in alphabetical order, but is still out of luck with the date order in “events”.

-

After searching for various existing questions, I cannot find a solution to what I am trying to do.

Currently, all posts on my site are sorted alphabetically, which is great, except for one new category that I added. For this category, I want to order all messages by the value that I enter in a custom field. The field is called "event_date" - so I want to sort the posts by date in essence, but not the date the message was created, the date when the user manually enters this field.

, :

<?php if (is_category($events)) { $posts = query_posts($query_string . '&orderby=$event_date&order=asc'); } ?>

.

:

<?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc' ); } ?>

, , , , , "", .

, , , , , , .

+5
4

, - . orderby=meta_value meta_key=metafieldid .

pre_get_posts hook , get_query_var( "cat" ) ( var) .

add_action( "pre_get_posts", "custom_event_post_order" );

function custom_event_post_order( $query )
{
    $queried_category = $query -> get_query_var( "cat" );

    /*
     * If the query in question is the template main query and
     * the category ID matches. You can remove the "is_main_query()"
     * check if you need to have every single query overridden on
     * a page (e.g. secondary queries, internal queries, etc.).
     */
    if ( $query -> is_main_query() && $queried_category == 123 )
    {
        $query -> set( "meta_key", "event_date" ); // Your custom field ID.
        $query -> set( "orderby", "meta_value" ); // Or "meta_value_num".
        $query -> set( "order", "ASC" ); // Or "DESC".
    }
} 

, , . WP_Query, .

. UNIX-timestamp, . , , , .

: , .

EDIT: , functions.php .

+1

, , WP_Query orderby :

$args = array(
    'posts_per_page' => 100,
    'orderby' => 'title',
    'order' => 'ASC',
);

if(is_category($events)){
    $args['orderby'] .= " meta_value_num";
    $args['meta_key'] = 'event_date';
}

$posts = (array) new WP_Query( $args );
0

What about:

<?php $posts = query_posts($query_string . (is_category($events)?'&orderby='.$event_date:'&orderby=title') . '&order=asc');  ?>
0
source
<?php
$recent = new WP_Query("cat=ID&showposts=x");
while($recent->have_posts()) : $recent->the_post();
?>
0
source

All Articles