29 October 2020

Fetching and Parsing Codepen RSS Feed and Then Making it a Custom Shortcode

utopianfool's
LIVE PUBLIC RSS FEED


Codepen RSS Feeds

It all started with a facination of really simple syndication and codepen collections. The original idea was to automatically grab and show the collections in my codepen profile, so I could keep adding them in codepen and they would be updated on other sites. Surely they might have a feed to tap into?

Turns out that all users have:

Fetching and Parsing with Javascript

After furiously searching over several web pages and codepens, then testing other code with my own tweaks I came accross this post “How to Fetch and Parse RSS Feeds in JavaScript” by CSS-Tricks. This was the golden nugget I was looking for.

        const RSS_URL = `https://codepen.io/utopianfool/public/feed`;

        fetch(RSS_URL)
          .then(response => response.text())
          .then(str => new window.DOMParser().parseFromString(str, "text/xml"))
          .then(data => {
            console.log(data);
            const items = data.querySelectorAll("item");
            let html = ``;
            items.forEach(el => {
              html += `
                <article>
                  <img src="${el.querySelector("link").innerHTML}/image/large.png" alt="">
                  <h2>
                    <a href="${el.querySelector("link").innerHTML}" target="_blank" rel="noopener noreferrer">
                      ${el.querySelector("title").innerHTML}
                    </a>
                  </h2>
                </article>
              `;
            });
            document.querySelector('#out').insertAdjacentHTML("beforeend", html);
          });

You could just grab this and plonk it straight in the page if you wrap it in <script></script> tags and add a div with an id=”out” and it will render the feed. But this is going to get tedious if we are going to embed it on multiple pages, so a WordPress shortcode was the next step.

Making it a Custom Sortcode

Several parts to this. Create a file called something like custom-shortcodes.php, this will house our shortcode script:

<?php
function codepen_rss_feed() {
  if( is_single() ) {
    ?>
        <h1 class="codepen-feed-title"><i class="fa fa-codepen" aria-hidden="true"></i> utopianfool's<br /><span>LIVE PUBLIC RSS FEED</span></h1>
        <hr />
        <div id="out" class="codepen-feed"></div>
    <?php
        wp_enqueue_script( 'codepen-rss', get_stylesheet_directory_uri() . '/js/codepen-rss.js');
    }
}

You may notice that the javascript that’s fetching the RSS feed is in its own file called codepen-rss.js.

Create that file, copy the fetch script from above and save it into /js/codepen-rss.js

Note: get_stylesheet_directory_uri() is used here to enqueue the javascript file because it is in a child theme. If it were in a parent theme you would use get_template_directory_uri() instead.

Note:The function is wraped in an if statement so that the shortcode will only run on a post page ‘is_single(). This shortcode caused no end of trouble breaking the backend until conditional tags came to the rescue.

Now we can include our custom-shortcodes.php file in the main functions.php

/**
 * custom shortcodes
 */
include('partials/custom-shortcodes.php');

and then register our shortcode.

/**
 * Register shortcodes
 */
function register_shortcodes(){
   add_shortcode('codepenrss', 'codepen_rss_feed');
}
add_action( 'init', 'register_shortcodes');

Here we are calling the codepen_rss_feed() function from the custom-shortcodes.php file and assigning the shortcode name ‘codepenrss’. Now we can use the shortcode to display our feed on any post page.

[codepenrss]

You will probably want to put your own style spin on it. Below is the css used for this example feed and a good starting point:

/* Codepen RSS feed */
.codepen-feed-title {
    text-align: center;
}
.codepen-feed-title span {
    font-size: 0.8rem;
}
.codepen-feed {
  margin: 1rem;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  grid-gap: 2rem;
  background: transparent;
}

.codepen-feed img {
  max-width: 100%;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

.codepen-feed article {
  background: #e6e6e6;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.16);
  overflow: hidden;
}
.codepen-feed article a {
  text-decoration: none;
  color: #455A64;
}
.codepen-feed article a:hover, .codepen-feed article a:focus {
  color: #2196F3;
}
.codepen-feed article h2 {
  text-transform: uppercase;
  font-size: 1.8rem;
  font-weight: 600;
  line-height: 30px;
  padding: 1rem 1rem;
  margin: 0;
}

Further reading

utopianfool

Creative Web Developer

View all posts by utopianfool →