Site logo

Archived topic

Create an external link dynamically using the page tag

5 replies · Started by Michael on September 21, 2022

Viewing posts 1–6 of 6

Hi there,

I am trying to dynamically create an external link based on the post tag of each post.

For example, if the tag is Coffee, I want to create a link that generates: google.com/coffee

I was planning on inserting on content-single.php

Does anyone know how this can be done?

Thanks

Hi Michael,

To clarify, if there's multiple tags, will there also be multiple links?

Have you considered creating a custom post meta field for "coffee" and whatever custom link you want for each post?

Actually on second thought, rather than using the tag, how about using a custom field?

One follow up question to that, is there an easy way to bulk upload a custom field to all my posts?

I have post ID and the desired text in a CSV.

How many tags/field values will you have?

We usually advice our users to use a plugin like ACF. It's capable of adding field, but I'm not sure if there's a way to add values to fields in bulk. Perhaps you could reach out to their support if it's possible or ask for recommendations in our Facebook community as well: https://www.facebook.com/groups/generatepress

Thanks! Last question... for now.

Let's say I do have custom fields. How can I get it to print for example: google.com/{custom_field}

You can create a GB Headline Block, then add class my-headline-link to its class list. Then set the url to placeholder.com

Then, add this snippet:

add_filter( 'render_block', function( $block_content, $block ) {
    if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'my-headline-link' ) !== false ) {
		
		$myreplace = 'placeholder.com';
		$my_meta = get_post_meta( get_the_ID(), 'my-meta-name', false);
		$my_link = 'google.com';
		$my_insert = $my_link . '/' . $my_meta;
        $block_content1 = str_replace( $myreplace, $myinsert , $block_content );
		
    }

    return $block_content;
}, 10, 2 );

Replace my-meta-name to the meta field slug and google.com with the domain url.

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

This archived topic is closed to new replies.