Some fun hacks Walter (WPAllied) did for an investing site I built.
I was building a stock investing site…that was auto-picked up by Zapier’s RSS tool, which pushed to Buffer’s auto-posting schedule, which then pushed to Twitter.
My goal was to show the following on Twitter in exactly this manner:
- Post title
- Post url
- And stock symbols (e.g. $ABC, $DEF, $GHI) which I set as “tags”.
Title of my stock post https://mysite.com/posturl $ABC $DEF $GHI
But the problem was the default WordPress RSS output showed all categories and tags, and also in a format I didn’t want.
- It showed the categories. (Again, I didn’t want to show this.)
- It put commas between each category/tag. (Wasting space.)
- There was no space before the tags, making them unclickable in Twitter.
Title of my stock post https://mysite.com/posturl CAT1,CAT2,TAG1,TAG2
Walter’s code fix below:
- Declare a namespace to avoid code conflict.
- Output RSS category element to show categories without commas and with a space between each one.
- Disable categories from showing in feed output. (Now shows only tags.)
- Put this snippet in your theme functions.php file.
/**
* Add <yoursite> namespace to RSS2.
*/
add_action( 'rss2_ns', function() {
echo 'xmlns:yoursite="http://yoursite.com/ns/yoursite#"';
});
/**
* Show post categories/tags in feeds with a single string space separated, and no comma.
*
* Disable Categories from showing in feed output.
*/
add_action('rss2_item', function() {
// $categories = get_the_category();
$tags = get_the_tags();
$the_list = '';
$cat_names = array();
// if ( ! empty( $categories ) ) {
// foreach ( (array) $categories as $category ) {
// $cat_names[] = sanitize_term_field( 'name', $category->name, $category->term_id, 'category', 'rss' );
// }
// }
if ( ! empty( $tags ) ) {
foreach ( (array) $tags as $tag ) {
$cat_names[] = sanitize_term_field( 'name', $tag->name, $tag->term_id, 'post_tag', 'rss' );
}
}
$cat_names = array_unique( $cat_names );
$cat_name = implode( ' ', $cat_names );
$the_list .= "\t\t<yoursite:categories><![CDATA[" . html_entity_decode( $cat_name, ENT_COMPAT, get_option( 'blog_charset' ) ) . "]]></yoursite:categories>\n";
echo $the_list;
I hope you enjoyed! It was a fun little hack and did the job perfectly for what we wanted!
rockin