Site logo

Archived topic

Adding conditions for page elements based on category

5 replies · Started by William on February 11, 2022

Viewing posts 1–6 of 6

Hi there,

I love the elements in GP - so modular. However, I hit a bit of a sticking point where I would like an element to appear for certain posts only.

Basically, I have two elements, Element 1 and Element 2.

I would like Element 1 to appear any time the post in question is in a child category.

I would like Element 2 to appear any time the post in question is in a parent category.

It is not part of the site structure to have a post in a child and parent category. But, if this happens, it defaults to the Element 2 version.

How would this be possible?

Many thanks,

Hi William,

This is possible through PHP. Here is a sample PHP snippet:

add_filter( 'generate_block_element_display', function( $display, $element_id ) {
  global $post;

  if ( $element_id===390130 && 
       ( is_single() && $post->post_parent===282 ) 
     ) {
     $display = true;
  }	
  return $display;
}, 10, 2 );

389130 is the value of the Block element’s id and 282 is the post id of the parent post.

Here is a thread you may refer to for more knowledge regarding this: https://generatepress.com/forums/topic/conditionally-display-hook-on-sub-page-of-parent/#:~:text=rules%20on%20my-,hook,-%2C%20but%20using%20layout

Hope this helps! Feel free to reach out if you’ll need assistance regarding this. :)

Thanks for that! I think this might work for me - the only issue comes with I don't want to define specific parent IDs (not parent post, but parent category).

So that it is if the post has only a parent category, use one element. If the post has a child category, use another element?

Hi there,

tricky one... do the posts have a single category ? or do they use multiple categories ?

They all only have single categories. For example:

- "George Orwell" is a primary parent category with "1984" beneath it as a child category.

There will be posts that only have "George Orwell", the parent, as a category, and other posts that only have "1984", the child category, as the category. No posts would have both the parent and child category.

Ok, we could try the following:

1. Create a helper function to check if the current post category has a parent:

function db_category_has_parent() {
    $categories = get_the_category();
    if ($categories[0]->category_parent > 0) {
        return true;
    }
    return false;
}

2. The we can use that in our display conditions eg.

add_filter( 'generate_element_display', function( $display, $element_id ) {
    // If category has a Parent show element ID 100
    if ( 100 === $element_id && db_category_has_parent() ) {
        $display = true;
    }
    // if category has NO Parent the show element ID 200
    if ( 200 === $element_id && !db_category_has_parent() ) {
        $display = true;
    }

    return $display;
}, 10, 2 );
This archived topic is closed to new replies.