Archived topic
Post title with external link
5 replies · Started by Lena on November 25, 2022
Hi. I have a bunch of blog posts with post format 'link'. The posts only include a title and an external link. I'm now trying to show a list of the latest posts on the frontpage and I want the titles to link directly to the external site, but instead the links go to the posts. I tried with all different blocks like 'Latest posts' and 'Loop query' but I get the same result.
Hi there,
if you use a GB Query Loop block, and use a Headline Block to display the Title with a dynamic link set to the Post.
So that link will go to the single post... we'll correct that with some code.
With that block selected go to: Advanced > Additional CSS Class(es) and give it a class of: dynamic-title
With that all saved add this PHP Snippet to your site:
add_filter( 'generateblocks_dynamic_url_output', function( $url, $attributes ) {
if ( ! empty( $attributes['className'] )
&& 'dynamic-title' === $attributes['className']
&& 'link' === get_post_format()
) {
$content = get_the_content();
$has_url = get_url_in_content( $content );
$url = ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}
return $url;
}, 10, 2 );
That code will check if the post is the link format, and if it is and there is a URL in the posts content it will swap the link for you. If no link is found it will carry on linking to the post.
Great. Thank you. Works perfect. Is there a way I can add target="_blank" somewhere in the code to open the links in another tab/window?
Good to hear that.
Add this snippet as well.
add_filter( 'render_block', function( $block_content, $block ) {
if (
!is_admin()
&& 'link' === get_post_format()
&& ! empty( $block['attrs']['className'] )
&& 'dynamic-title' === $block['attrs']['className']
) {
$block_content = str_replace( '<a ', '<a target="_blank" ', $block_content );
}
return $block_content;
}, 10, 2 );
That works perfect, also! Thanks a bunch and happy holidays.
Glad to hear that!!