Site logo

Archived topic

Make CPT Post meta data link (from query loop) open in a new tab

3 replies · Started by Anwar on October 18, 2022

Viewing posts 1–4 of 4

I created a custom post type and added custom fields to it using ACF.

Using de Query loop block I am retrieving the posts with the post meta.

Because one custom field contains a link, adding that to the loop works fine, but I have no way of choosing where the link should open. In this case I want it to open in a new tab, but I have no way of doing that.

Please see the attachment below to get a picture of what I mean.

What would be the best way of retrieving this data and displaying it as a link while making sure it opens in a new tab?

Query Loop with post meta from a CPT

Hi Anwar,

Add my-open-new-tab to the classlist of the Headline Block links which you wish to open in a new tab. Then add this snippet:

function db_rerender_url_new_tab( $block_content, $block ) {
	if(!is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'my-open-new-tab' ) !== false  ) {
			$my_search='href="';
			$my_replace='target="_blank" href="';
			$new_content = str_replace($my_search, $my_replace, $block_content);
			return $new_content;
	}
    return $block_content;
}
 
add_filter( 'render_block', 'db_rerender_url_new_tab', 10, 2 );

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

It's been a while, but I've just implemented it and it seems to work!

You're welcome, Anwar! Glad that worked!

This archived topic is closed to new replies.