Site logo

Archived topic

Order of posts appearing on a category/archive page

6 replies · Started by Paul on June 15, 2022

Viewing posts 1–7 of 7

Hi there, I'm just wondering if there is way to make a custom order of blog posts appearing on a category/archive page in Generate Press? (FYI I'm using the marketr theme).

Basically I want to be able to choose 4 posts of a category appearing at the top of the category/archive page (independent of date). The rest of the posts can just appear in date order. For sites like mine with evergreen content it's obviously important to be able to put at the top of the list the most important posts.

I know making a custom page and using WP Show Posts is an option. Or the new query loop solution. But I don't want to do that because I pay for the marketr theme to use that theme. And I like the design of the category/archive pages.

I know that I could just change the publishing dates to keep the posts at the top of the list (after new posts are published) But I'm wondering if there is an actual solution to this, even if it's some code, so that they stick to the top of the list.

Thanks!

Hi Paul,

We can try to alter the query of your specific Category. For instance, here’s a PHP snippet you may try adding:

add_action( 'pre_get_posts', function($query){
if ( ! is_admin() && is_category('affiliate-marketing') && $query->is_main_query() ) {
		$args = array('posts_per_page' => -1,
			'fields' => 'ids');
		$posts = get_posts($args);
		
	
	if ( $posts ) {
    $move_to_front   = array( 282, 287, 391276, 123 );
    $post_ids_merged = array_merge( $move_to_front, $posts );
    $reordered_ids   = array_unique( $post_ids_merged );
		
	
        $query->set( 'post__in', $reordered_ids );
        $query->set( 'orderby', 'post__in');
		$query->set( 'order', 'ASC' );

	}
        
   }
});

Kindly replace affiliate-marketing with the slug/name of the category, and ( 282, 387, 391276, 123 ) with the Id of the posts you wish to place on top.

Adding PHP reference: https://docs.generatepress.com/article/adding-php/#code-snippets

Getting the post id: https://share.getcloudapp.com/o0uG8nYD

Hope this helps!

Thanks for that. I tried what you said and it worked in terms of the order. BUT above the header of the website I got like 100 lines of random code just appearing. Any more help much appreciated! :)

FYI on my site posts are configured to simply be sitename/postname

In the public URL of the post it is not eg sitename/category/postname

Not sure if that makes a difference to the code you shared. But just thought to tell you that. Cheers.

I see. I modified the code above. Can you try it again?

Kindly let us know how it goes.

Worked! Thanks so much for the help.

You’re welcome Paul! Glad that worked!

This archived topic is closed to new replies.