WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to use pre_get_posts to order Recent Posts Widget? (2 posts)

  1. Uwhoosh
    Member
    Posted 1 year ago #

    Hello,
    I'd like to use the pre_get_posts filter to order the Recent Post Widget.
    Currently I'm using query_posts to order my blog posts in ascending order, oldest to earliest. You can see it here.
    Common wisdom is to use the alternative pre_get_posts filter to do this. But here's the problem. When I use the pre_get_posts filter to order the blog excerpts in ascending order, the Recent Post widget also orders the post is ascending order! For obvious reason I'd like the to order the recent post widget in descending order (newest to oldest).
    Here is the code I've tried to use.

    // Runs before the posts are fetched
    add_filter( 'pre_get_posts' , 'my_kongo_order' );
    // Function accepting current query
    function my_kongo_order( $query ) {
    	// Check if the query is for home
    	if($query->is_home)
    		// Query was for home, then set order
    		$query->set( 'order' , 'asc' );
    	// Return the query (else there's no more query, oops!)
    	return $query;}

    As you can see, I even tried to exclude the widget by using the if... is_home, but that didn't work either.
    Is there anyway I can achieve this using pre_get_posts?
    Any help is appreciated.
    Thanks.

  2. Uwhoosh
    Member
    Posted 1 year ago #

    Resolved this by only modifying the main query using is_main_query (), you can get the code snippet here.

Topic Closed

This topic has been closed to new replies.

About this Topic