Halloween Sale 15% off Ends in See the plans
PHP

Hashtags From Tags in Feed Items

Turns each post's tags into hashtags such as #HomeOffice at the end of the feed summary, so RSS-to-social tools like Buffer, Zapier or IFTTT post them automatically.

Don’t have WPIDE yet? Install it on your site

Code

// Where the hashtags go: 'description' (the summary most RSS-to-social tools post) or 'both' to add them to the full content too.
$wpide_feed_hashtags_in = 'description';
// Maximum number of hashtags per item.
$wpide_feed_hashtags_max = 4;

$wpide_feed_hashtags = function () use ( $wpide_feed_hashtags_max ) {
    $tags = get_the_tags();

    if ( ! $tags || is_wp_error( $tags ) ) {
        return '';
    }

    $out = array();

    foreach ( array_slice( $tags, 0, max( 1, (int) $wpide_feed_hashtags_max ) ) as $tag ) {
        // "Home office" becomes #HomeOffice; accents and other alphabets are kept.
        $words = preg_split( '/[^\p{L}\p{N}]+/u', $tag->name, -1, PREG_SPLIT_NO_EMPTY );
        $words = array_map( function ( $word ) {
            return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( mb_substr( $word, 0, 1 ) ) . mb_substr( $word, 1 ) : ucfirst( $word );
        }, (array) $words );

        if ( $words ) {
            $out[] = '#' . implode( '', $words );
        }
    }

    return implode( ' ', array_unique( $out ) );
};

add_filter( 'the_excerpt_rss', function ( $excerpt ) use ( $wpide_feed_hashtags ) {
    $tags = $wpide_feed_hashtags();

    return '' === $tags ? $excerpt : $excerpt . ' ' . esc_html( $tags );
} );

if ( 'both' === $wpide_feed_hashtags_in ) {
    add_filter( 'the_content_feed', function ( $content ) use ( $wpide_feed_hashtags ) {
        $tags = $wpide_feed_hashtags();

        return '' === $tags ? $content : $content . '<p>' . esc_html( $tags ) . '</p>';
    } );
}

Notes

Set the place to 'both' to add the hashtags to the full content as well; the number of hashtags is capped at four by default.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.