I would like to display taxonomies within an RSS feed. I am able to display my custom fields as per Add Custom Fields to Custom Post Type RSS (Thank you to all the contributors of that post), but I am unable to display fields that contain taxonomy values. Here is the code I am using:
add_action('rss2_item', 'yoursite_rss2_item');
function yoursite_rss2_item() {
if (get_post_type()=='listings') {
$fields = array(
'listing_category',
'listing_type',
'listing_bedrooms',
'listing_city',
);
$post_id = get_the_ID();
foreach($fields as $field)
if ($value = get_post_meta($post_id,$field,true))
echo "<{$field}>{$value}</{$field}>n";
}
}
Here are the 2 taxonomy fields that are not showing:
- “listing_category” – either “For Sale”, “For Lease”, or Both
(multiple values). - “listing_type” – 1 value containing “Condo”,
“House”, “Land”, or “Building”.
Any help is greatly appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
get_post_meta is only for custom fields. If listing_category and listing_type are in fact taxonomies, you need to use get_the_terms instead. The resulting code would be something like this:
add_action('rss2_item', 'yoursite_rss2_item');
function yoursite_rss2_item() {
if (get_post_type()=='listings') {
$fields = array(
'listing_bedrooms',
'listing_city',
);
$post_id = get_the_ID();
foreach($fields as $field) {
if ($value = get_post_meta($post_id,$field,true)) {
echo "<{$field}>{$value}</{$field}>n";
}
}
$taxonomies = array(
'listing_category',
'listing_type'
);
// Loop through taxonomies
foreach($taxonomies as $taxonomy) {
$terms = get_the_terms($post_id,$taxonomy);
if (is_array($terms)) {
// Loop through terms
foreach ($terms as $term) {
echo "<{$taxonomy}>{$term->name}</{$taxonomy}>n";
}
}
}
}
}
See the documentation for get_the_terms here: http://codex.wordpress.org/Function_Reference/get_the_terms
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0