Site logo

Archived topic

Sort by (title, date, DESC, ASC etc...) for dynamic content elements

10 replies · Started by Dan on September 29, 2021

Viewing posts 1–11 of 11

Hi Dan,

Unfortunately not.

The content template is strictly for appearance and does not modify the post loop which is handled by WordPress core.

Thanks Leo.
So it I would like to change the order of posts displayed in an archive page for the Custom post type 'Catalog' is there a GP filter for that?

I'll use this function:

add_action( 'pre_get_posts', 'cd_sort_catalog' );
function cd_sort_catalog( $query ) {
    if ( $query->is_main_query() && !is_admin() ) {
        if ( $query->is_tax() || $query->is_post_type_archive('catalog') ) {
        
            $query->set('order', 'DESC'); 
			
        }       
    }
} 

I think it would be useful to add sorting options when creating a dynamic content element for archives / category pages.

Dan

Yup the pre_get_posts filter is what you need.

This isn't something we would add to the theme :)

Thanks,
Not to the theme but to the dynamic element.

Thanks for the suggestion :)

following up on this, can I use the pre_get_posts function to group the posts in that archive page by their category?
So to create a condition, if the archive page is showing posts from category A, display the posts by their subcategory(child category of category A) together.
Right now they are showing in chronological order and not grouped together.

Thanks
Dan

Thanks Elvin.
I don't need them to be grouped, but rather displayed together, meaning that the sorting of the posts (the posts order) will not be by post date or title but by the post's child category. All posts which are in the same child category will be together, The child category order can be either alphabetical or by date created.
And since I don't change the actual loop because I'm using a dynamic element I will need to use the pre_get_posts.

So I'm looking for a sorting by child category, not date or title.
Using something similar to this:

add_action( 'pre_get_posts', 'sort_by_child_catefory' );
function sort_by_child_catefory( $query ) {
    if ( $query->is_main_query() && !is_admin() ) {
        if ( $query->is_category('tutorials') ) {
        //I would like all the posts in the child categories of 'tutorials' to be together and not by date or title
            $query->set('order', 'DESC'); 
			$query->set('orderby', 'title');
        }       
    }
} 

I hope this make sense,

Thanks
Dan

This archived topic is closed to new replies.