Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Search Result – Show Post Type

  • liquidonthedrums

    Hi Guys,

    Just wondering how I would go about showing the post type of each post in the search page. And to extend that, if it would be possible to show an icon for each post type.

    eg search result for ‘transport’ returns posts of type ‘page’, ‘post’, ‘project’ (CPT) etc. and i would like to show the post type next to the result, and/or an image/icon for that post type.

    Thanks

  • Hi there,

    Do you mean adding a label or some kind of indicator to the search results to identify whether each item is a post, page, or another post type? Is that correct?

  • liquidonthedrums

    Hi Alvind,

    Yes. Exactly.

    Thx

  • If you’re using a Block Element to build your search results template, one approach is to create a custom shortcode or custom dynamic tag to output the post type label for each post in the results.

    If that’s the method you’re using, I’d be happy to help you create the necessary code snippet. Let me know!

  • liquidonthedrums

    Hi Alvind,

    I’d be interested to see your approach to a custom dynamic tag. I’m trying to eliminate the use of shortcodes if i can.

    Thanks

  • Try this:

    add_action('init', function () {
        // Check if the GenerateBlocks dynamic tag class exists
        if (! class_exists('GenerateBlocks_Register_Dynamic_Tag')) {
            return;
        }
    
        // Register the dynamic tag for post type
        new GenerateBlocks_Register_Dynamic_Tag([
            'title'       => __('Post Type', 'generateblocks'),
            'tag'         => 'post_type',
            'type'        => 'post',
            'supports'    => [],
            'description' => __('Displays the post type of the current post.', 'generateblocks'),
            'return'      => function () {
                // Get the current post type
                $current_post_type = get_post_type();
    
                // Return the post type if it exists, otherwise return an empty string
                return $current_post_type ? esc_html($current_post_type) : '';
            }
        ]);
    });

    Then you should be able to find Post type ({{post_type}}) dynamic tag in the dropdown list.

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.