0

I would like to create link of word(s) in post content (word(s) which is used as post tag of current post) to post tag URL. I created this, and it works, but only for one word (last tag) of post.

$post_content = get_the_content(); // Get post content
$search = array($tag->name);
$replace = array('<a href="'.get_tag_link($tag->term_id).'" title="'.$tag->name.'" itemprop="url">'.$tag->name.'</a>');
$replacePairs = array_combine($search, $replace);
echo strtr($post_content, $replacePairs);

How to make it search for all words of tags (of current post) in post content and link that words to it's tag URLs?

2 Answers 2

0

You can use power of PHP. Explode the Words and Implode them. After exploding it you will get an array, with which you can loop through using foreach and call your function conditionally.

2
  • Could yoy please write that php code, to se it? Thanks. Dec 28, 2016 at 8:39
  • @AdvancedSEO Please see the manual string replace and replace the matching tags with the warpped url you want to replace. Dec 28, 2016 at 9:16
0

Could you please provide complete function in working mode. I have also same requirement but not working. here is the code.

<?php

function save_post_content_with_hyperlinks( $post_id, $post_content ) {

    // Check if the user is an admin.
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    // Check if the post ID is null.
    if ( is_null( $post_id ) ) {
        return;
    }

    // Check if the post content is null.
    if ( is_null( $post_content ) ) {
        return;
    }

    // Get the post tags.
    $post_tags = get_the_tags( $post_id );

    // Check if the post tags are null.
    if ( is_null( $post_tags ) ) {
        return;
    }

    // Create an array of hyperlinked tag keywords.
    $hyperlinked_tags = array();
    foreach ( $post_tags as $tag ) {

        // Check if the tag is null.
        if ( is_null( $tag ) ) {
            continue;
        }
    
        $hyperlinked_tag = null;
        if ( ! is_null( $tag ) ) {
            $hyperlinked_tag = '<a href="' . get_tag_link( $tag->term_id ) . '">' . $tag->name . '</a>';
        }
        $hyperlinked_tags[] = $hyperlinked_tag;
    }

    // Replace the tag keywords with hyperlinked tag keywords in the post content.
    $post_content = str_replace( $post_tags, $hyperlinked_tags, $post_content );

    // Update the post content in the database.
    wp_update_post( array(
        'ID'           => $post_id,
        'post_content' => $post_content,
    ) );

    // Return the post content with hyperlinks.
    return $post_content;

}
add_filter( 'save_post', 'create_hyperlinks_for_tag_keywords', 10, 2 );```

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.