Site logo

[Resolved] Post title with external link

Home Forums Support [Resolved] Post title with external link

Home Forums Support Post title with external link

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #2432532
    Lena

    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.

    #2433624
    David
    Staff
    Customer Support

    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.

    #2438552
    Lena

    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?

    #2438846
    David
    Staff
    Customer Support

    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 );
    #2440606
    Lena

    That works perfect, also! Thanks a bunch and happy holidays.

    #2440722
    David
    Staff
    Customer Support

    Glad to hear that!!

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