Custom Field Values in Feed Items
Adds the custom fields you choose, such as an event date or location, to each RSS item as its own element, for newsletter tools, aggregators and partner sites that read your feed.
Opens WPIDE on
Code
// Custom field key => element name in the feed (lowercase letters, digits and dashes). Empty = off. Examples:
// 'event_date' => 'event-date',
// 'location' => 'location',
$wpide_feed_fields = array();
// Prefix of the elements, for example <site:event-date>.
$wpide_feed_fields_prefix = 'site';
if ( $wpide_feed_fields ) {
add_action( 'rss2_ns', function () use ( $wpide_feed_fields_prefix ) {
echo 'xmlns:' . esc_attr( sanitize_key( $wpide_feed_fields_prefix ) ) . '="' . esc_url( home_url( '/' ) ) . '"' . "\n\t";
} );
add_action( 'rss2_item', function () use ( $wpide_feed_fields, $wpide_feed_fields_prefix ) {
$post_id = get_the_ID();
if ( ! $post_id || post_password_required( $post_id ) ) {
return;
}
$prefix = sanitize_key( $wpide_feed_fields_prefix );
foreach ( $wpide_feed_fields as $key => $element ) {
$element = preg_replace( '/[^a-z0-9-]/', '', strtolower( (string) $element ) );
$value = get_post_meta( $post_id, $key, true );
if ( '' === $element || ! is_scalar( $value ) || '' === trim( (string) $value ) ) {
continue;
}
printf( "\t\t<%1\$s:%2\$s>%3\$s</%1\$s:%2\$s>\n", $prefix, $element, esc_xml( wp_strip_all_tags( (string) $value ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput -- names are sanitized above.
}
} );
}
Notes
The field list is empty by default; add field keys and the element names to use. Password-protected posts are skipped.
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.