WordPress RSS feed – filter RSS content by custom field value

You can try to add geo_country as an extra query variable with:

/**
 * Add the 'geo_country' as a public query variable
 *
 * @param array $query_vars
 * @return array $query_vars
 */ 
function my_query_vars( $query_vars ) 
{
    $query_vars[] = 'geo_country';
    return $query_vars;
}

add_filter( 'query_vars', 'my_query_vars' );

and then setup a pre_get_posts hook to filter your feed according to the geo_country value:

/**
 * Filter the feed by the 'geo_country' meta key 
 *
 * @param WP_Query object $query
 * @return void 
 */ 
function my_pre_get_posts( $query ) 
{
    // only for feeds
    if( $query->is_feed && $query->is_main_query() ) 
    {
        // check if the geo_country variable is set 
        if( isset( $query->query_vars['geo_country'] ) 
                && ! empty( $query->query_vars['geo_country'] ) )
        {

            // if you only want to allow 'alpha-numerics':
            $geo_country =  preg_replace( "/[^a-zA-Z0-9]/", "", $query->query_vars['geo_country'] ); 

            // set up the meta query for geo_country
            $query->set( 'meta_key', 'geo_country' );
            $query->set( 'meta_value', $geo_country );
        }

    } 
}

add_action( 'pre_get_posts', 'my_pre_get_posts' );

I assume geo_country takes only alpha-numeric values (a-z,A-Z,0-9), just let me know if that’s not the case.

This works on my install with the Twenty Twelve theme.

Leave a Comment