Site logo

Archived topic

How to have 3 selected post to be at the top of a category archive page?

15 replies · Started by nomadiceman on December 30, 2022

Viewing posts 1–15 of 16

I'm trying to figure out how I can select 3 posts for each category and have them display at the top of the archives for that category. A sort of featured posts for each category.

Is there a way to do that with a hook and element?

Are any of the current templates doing that? If so let me know and I will check it out

Thanks for your help as always

Hi Nomadice Man,

You can use a Query Loop Block. Reference: https://docs.generateblocks.com/article/query-loop-overview/

Add it through a Block Element - Hook. Hook it to after_header.

Then, in the Query Loop Parameters, include only posts with Taxonomy - Tag - Featured. (So, you need to tag 3 featured posts as Featured)

Then, add a PHP snippet to exclude posts with Tag - Featured on your archive pages so it doesn't repeat.

Example code:

add_filter( 'pre_get_posts', function( $query ) {
    if ( $query->is_archive() && $query->is_main_query() ) {
		$query->set( 'tag', '-19' );
    }

    return $query;
} );

Replace 19 with the ID of the Tag.

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

Getting the Tag ID: https://share.getcloudapp.com/Z4umjoAo

thank you 🙏

You're welcome! Happy New Year! :)

Happy new year to you too

Hi, I've just tried adding the PHP snippet and I got this error:

Don't Panic
The code snippet you are trying to save produced a fatal error on line 6:

syntax error, unexpected 'return' (T_RETURN), expecting ')'
The previous version of the snippet is unchanged, and the rest of this site should be functioning normally as before.

I updated the code above.

Can you try adding it again?

I've added it and now the archive disappears

Below is the code I used. The featured category tag id is 113

add_filter( 'pre_get_posts', function( $query ) {
    if ( $query->is_archive() && $query->is_main_query() ) {
		$query->set( 'tag', '-113' );
    }

    return $query;
} );

here you go, thank you

I see.

You need to add "Featured" as a tag, not a category.

Then, add the tag ID in the code.

Doing so should make it work.

ive changed it to a tag and changed the id. problem is still there

I see.

Can you try changing the code to this?:

function excludeTagId($query) {
  $tag_Ids = array(
    114
  );

  if ($query->is_main_query() && ! is_admin() && $query->is_category() ) {
    $query->set( 'tag__not_in', $tag_Ids );
  }
}
add_action('pre_get_posts', 'excludeTagId');

Let me know how it goes.

thank you. that seems to have worked now

This archived topic is closed to new replies.