php – WordPress create custom XML RSS feed template

Question

I am trying to create a custom XML RSS feed. However, my code is not quite working as expected. Here is what I have done:

In functions.php I have created the feed called “top”:

add_action('init', 'customRSS');
function customRSS(){
        add_feed('feedname', 'top');
        get_template_part('rss', 'top');
}

In my child theme I have created file rss-top.php which contains my template file.

I am looking for a quite simple template structure like below:

<?xml version="1.0" encoding="UTF-8"?>
<articles>
    <article>
        <title>Overskrift</title>
        <teaser>Short excerpt</teaser>d
        <link>http://link-to-post.com/</link>
        <image>http://placehold.it/100x100</image>
        <date>19-06-2017 11:21:00</date>
    </article>
    <article>
        <title>Overskrift</title>
        <teaser>Short excerpt</teaser>
        <link>http://link-to-post.com/</link>
        <image>http://placehold.it/100x100</image>
        <date>19-06-2017 11:21:00</date>
    </article>
</articles>

I have tried creating the structure like so:

<?php
/**
 * Template Name: Custom RSS Template - top
 */
$postCount = 6; // The number of posts to show in the feed
$posts = query_posts('showposts=" . $postCount);
header("Content-Type: '.feed_content_type('rss-http').'; charset=".get_option("blog_charset'), true);
echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>';
?>

<articles>
        <?php while(have_posts()) : the_post(); ?>
                <article>
                        <title><?php the_title_rss(); ?></title>
                        <teaser><![CDATA[<?php the_excerpt_rss() ?>]]></teaser>
                        <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
                        <link><?php the_permalink_rss(); ?></link>
                        <image><?php get_the_post_thumbnail( $post->ID ); ?></image>
                        <date><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></date>
                        <?php rss_enclosure(); ?>
                        <?php do_action('rss2_item'); ?>
                </article>
        <?php endwhile; ?>
</articles>

Afterwards I have updated the permalink and then trying to view site.com/rss/top.xml

However, for some reason, it just shows the latest couple of posts like it was an archive page on my site and not as an XML file as expected. Any pointers on what I might be missing ??

0
TurboTobias 2 weeks 2021-09-02T09:04:46-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse