• WORDPRESS: Custom query to RSS feed.


    Had a need to create RSS feeds for several lists. Seemed a simple enough task at the time. All that was left to do was structure some kind of request thingy and move on to the next task.

    Initially I thought I could get away with some variation of the following example:

    https://domain.com/?s=&post__in=["12345","123"]&feed=rss2 // does not work

    As it turns out, extended search parameters, such as post__in, tag__in, etc. do not behave as expected in a query string.

    "Well duh." I thought, then turned to the internet for ideas. "Yo homie, you got some sauce for me?"

    The internet responded immediately, and after sifting through all the "use this" and "use that" plugin suggestions, I found something I could work with and probed deeper.

    "A custom rss feed will need to be registered," said a number of the candidates probed. "This new feed will reference a method that handles business, which includes overriding the WP_Query object then passing the results to a template."

    A custom template was also suggested. But, I did not want to do that, and settled on the recipe that extended existing assets. A variation of the solution was finally embedded into the plugin. Should work in a custom theme as well.

    Below a crude feed registration and handler example:

    public function create_feed()
    {
            global $wp_rewrite;
            $name = 'custom-rss';
            if ( ! in_array( $name, $wp_rewrite->feeds ) ) {
                $wp_rewrite->feeds[] = $name;
                flush_rewrite_rules( FALSE );
            }
            add_feed( $name, function(){$this->render_feed();} );
    }
    add_action( 'init', array( $this, 'create_feed'));

    public function render_feed()
    {
            global $wp_query;
            $id = $_REQUEST["id"];
            $args = array_merge(
                    $wp_query->query,
                    array('post__in' => $id)
            );
            query_posts($args);
            include('wp-includes/feed-rss2.php');
    }

    Link example:

    https://domain.com/feed/playlist/?id%5B%5D=3296&id%5B%5D=3096&id%5B%5D=2853&id%5B%5D=747

    Create and append to content with a bit of jQuery (What? I like jQuery):

    let param = { id: ["3296","3096","2853","747"]};

    jQuery("<div />",{ class: "text-center" })
    .append(
    jQuery("<a />", {
    "href": glob_obj.site_url + "/feed/playlist/?" + jQuery.param(param) ,
    "title": elem.title + " rss feed",
    "target": "_blank"
    })
    .append(
    jQuery("<img />", {
    "src": glob_obj.site_url + "/wp-includes/images/rss-2x.png",
    "vspace":"12"
    })           
    )
    )
    .appendTo( jQuery('#' + elem.id) );

    Feed solution adopted from here:
    https://raphaelhertzog.com/2011/01/07/howto-create-custom-rss-feeds-with-wordpress/

  • You might also like