How to Convert WordPress Tags to Hashtags

This snippet allows you to convert a WordPress tag into a hashtag that links to a tag.

Programmazione WordPress
Programmazione WordPress

To convert WordPress tags into hashtags, you can utilize a custom function within your WordPress theme. Here’s a PHP example of how it could be implemented:

function convert_tags_to_hashtags() {
    // Get the current tags for the post
    $tags = get_the_tags();

    // Check if there are any tags
    if ($tags) {
        // Initialize an empty string for the new hashtagged tags
        $new_tags = '';

        // Iterate through the tags and prepend hashtags
        foreach ($tags as $tag) {
            $new_tags .= '#' . $tag->name . ' ';
        }

        // Return the new hashtagged tags
        return $new_tags;
    }

    // If no tags, return an empty string
    return '';
}

You can then use the `convert_tags_to_hashtags()` function in your WordPress theme files to display tags as hashtags as desired. For instance, you might insert this function within `single.php` or `content.php` to show tags as hashtags within a post.

Alternative:

function wptag_to_hashtag($mywp_post)
{
    $content = $mywp_post->post_content;
    $ID = $mywp_post->ID;
    preg_match_all('/B(#[a-zA-Z]+b)/', $content, $matches, PREG_PATTERN_ORDER);
    if (isset($matches[1])) {
        foreach ($matches[1] as $matchKey) {
            wp_set_post_tags($ID, $matchKey, true);
        }
    }
}
add_action('post_save', 'wptag_to_hashtag', 10, 2);
function hashtagger($content)
{
    $siteurl = get_site_url(); // get wordpress siteurl to create url for tags
    $content = preg_replace('/([^a-zA-Z-_&])#([a-zA-Z_]+)/', "$1#$2", $content);
    return $content;
}
add_filter('the_content', 'hashtagger');

Add this snippet to the functions.php file of your active theme.


Pubblicato in

Se vuoi rimanere aggiornato su How to Convert WordPress Tags to Hashtags iscriviti alla nostra newsletter settimanale

Be the first to comment

Leave a Reply

Your email address will not be published.


*