Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.