Auto tag link creation while saving the wordpress post

36 Views Asked by At

Hello I am using wordpress 6.3.2 version and generatepress theme.

I have searched for plugins which can create a tag links automatically while saveing /publishing/updating the posts. But they are creating dynamic links while user access the post for reading. But I want link to be created and saved in db (hard coded links for tag keywords). I have asked chatgpt for code that is given below code but its creating hard links for tags but Post is not getting saved.

here is the code. can anybody suggest whats the issue with this php function?

    // Check if the post is being saved or updated.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    // Get the post object
    $post = get_post($post_id);
    if ($post) {
        // Retrieve all tags
        $tags = get_tags();
        $content = $post->post_content;

        foreach ($tags as $tag) {
            $tag_name = $tag->name;
            $tag_link = get_tag_link($tag->term_id);
            $tag_link_html = '<a href="' . $tag_link . '">' . $tag_name . '</a>';
            $content = str_replace($tag_name, $tag_link_html, $content);
        }

        // Update the post content with tag links
        wp_update_post(array(
            'ID' => $post_id,
            'post_content' => $content,
        ));
    }
}

add_action('save_post', 'auto_link_tags_on_publish');```
0

There are 0 best solutions below