Archived topic
Display the post type in the query loop
4 replies · Started by Dan on February 1, 2023
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 );
Thanks Ying,
But I'm just seeing 'post-type' in the headline
https://www.dropbox.com/s/lm4v5s170ytbtj8/post-type.jpg?dl=0
Editor:
https://www.dropbox.com/s/tmyzl6wrklnaeuv/post-type-editor.jpg?dl=0
I've added the function you sent to the functions.php file, and gave the heading a class of post-type.
Any thoughts?
Dan
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 :)