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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.