0

I'm looking for a code snippet or plugin to solve one of my problems.

There are 4 different post types. Each has at least 5,000 posts. I want: if i enter a post title (plain text) in the content, it will automatically receive the post link.

So, if i have post with "CCC" title, and i will put in this one another post content, wordpress it would automatically detect this and linking automaticly the "CCC".

Is this possible? Is there such a plugin, code snippet or anything else?

Thanks

2
  • is this possible ? yes. is there a plugin for that ? no idea, here is a place for helping about development then you will not find advices about which existing plugin using. but we can help you to write you own plugin to do that. do you know development with php ?
    – mmm
    Commented Sep 21 at 7:26
  • Plugin recommendations are off topic here. While it would be possible to write one, that's way too large a scope for a Stack Exchange question.
    – Chris Cox
    Commented Sep 21 at 11:24

1 Answer 1

0

You can achieve your desired result with the help of given code which needs to be added to functions.php file of your theme.

The given code will automatically convert plain text titles in your post content into links pointing to the corresponding posts.

<?php
function auto_link_post_titles( $content ) {
    // This is to get all published posts from all post types.
    $args = array(
        'post_type'      => 'any', // this is to get posts from all post types.
        'post_status'    => 'publish',
        'posts_per_page' => -1, // this is to retrieve all posts
    );

    $posts = get_posts( $args );

    // Here are looping through each post and replace the title in the content with a link.
    foreach ( $posts as $post ) {
        $post_title = esc_html( $post->post_title ); // Here we are getting the post title.
        $post_link  = esc_url( get_permalink( $post->ID ) ); // Here we are getting the post link.
        
        // Create a link element
        $link = '<a href="' . $post_link . '">' . $post_title . '</a>';
        
        // Here we are replacing the plain text title with the link.
        $content = str_replace( $post_title, $link, $content );
    }

    return $content;
}

// We have apply the function to the content of posts.
add_filter( 'the_content', 'auto_link_post_titles' );
1
  • Thanks! Works perfect! Are you amazing! 😊
    – Mapa
    Commented Sep 22 at 4:29

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.