• Hi all,
    I’ve been building this beautiful website with the fukasawa theme. The menu consists of 27 category items (an alphabet, you see) and I managed to create a simple query to have each of those pages sort the items alphabetically on title.
    The problem is, I want the homepage to show the most recent additions – preferably limited to 20 or 30 items, instead of “all items” which is on those category pages.

    Could you help refining this query? I am a total novice with php so I guess I need help.

    The current code, added to my functions.php, is:

    add_action( 'pre_get_posts', 'x_category_order' );
    function x_category_order($query){
    if(!$query->is_main_query()) return $query;
    if(is_category( array( 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ) )) $query->set( 'orderby', 'title' );$query->set( 'order', 'ASC' );
    return $query;
    
    }
    • This topic was modified 1 year, 4 months ago by bcworkz. Reason: code format fixed
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    A query for most recent posts cannot also order by title because the ordering is used to determine what is most recent.

    You could instead query for posts published within the last week (or any other time span). Then you could order by title, but depending on how frequently you publish, it could be 50 posts or no posts. Also, users would then not be able to page through to older posts.

    Alternately, query for recent posts in the usual manner. Posts will be ordered by date. You could then use usort() in your template code to re-order the current page’s worth of posts by title.

    Thread Starter mfgr

    (@mfgr)

    I’m afraid my question wasn’t clear enough.
    I don’t want the homepage to order by title – just all the category pages.
    As it is, I don’t know how to achieve this.

    It would be fine if the homepage shows the most recent additions, but by adding the code above it affects the homepage as well as the category pages and I don’t know how to fix that.

    • This reply was modified 1 year, 4 months ago by mfgr.
    Moderator bcworkz

    (@bcworkz)

    You can use is_front_page() or is_home() in your conditional to avoid altering front page or home queries.
    if(!$query->is_main_query() || $query->is_front_page()) return $query;

    Thread Starter mfgr

    (@mfgr)

    Thank you very much!!
    I would never have come up with this, myself.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to exclude homepage from query’ is closed to new replies.