Site logo

Archived topic

Display the post type in the query loop

4 replies · Started by Dan on February 1, 2023

Viewing posts 1–5 of 5

Hi,
I have a query loop which displays posts from several post types: posts, and a few cpt's.
I would like to add a dynamic element which would display the name of the post type.
So next to the title of the post I would have: "Post" or "Tutorial" or "Catalog"

How can this be done with the GB tools?

Thanks!
Dan

Hi Dan,

You can add a headline block, enter the text "post type", give it a CSS class, eg. post-type:
https://www.screencast.com/t/RphqKswHwVb9

Then add this PHP snippet to replace the text "post type" with the real post type:

add_filter( 'render_block', function( $block_content, $block ) {
	
    if ( ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'post-type' ) !== false  ) {		
		$post_id = get_the_ID();
        $post_type = get_post_type($post_id);

		$block_content = str_replace('post type',$post_type, $block_content );
	}
   return $block_content  ;
}, 10, 2 );

ok, found the issue.
on this line: $block_content = str_replace('post type',$post_type, $block_content );
it should be post-type with a dash.

Thanks for your help
Dan

$block_content = str_replace('post type',$post_type, $block_content );

In my example, the text I entered in the headline was post type, so it works on my end, but if you entered post-type in the headline, then it needs to be switched to post-type in the code :)

This archived topic is closed to new replies.