Tuesday, April 22, 2025
HomeProgrammingCreating A "Starred" Feed | CSS-Tips

Creating A “Starred” Feed | CSS-Tips


In my submit Transient Notice on Determine and Figcaption Help I display how, when encountering a determine with a display screen reader, you gained’t hear all the pieces introduced directly:

No display screen reader combo treats the caption because the accessible identify nor accessible description, not even for an…

One of many working jokes and/or dialogue I’m sick and bored with is individuals belittling HTML. Sure, HTML shouldn’t be a programming language. No, HTML shouldn’t simply be a compilation goal. Studying HTML is a strong funding and never onerous to do.

I’m not…

We will use the :empty pseudo-class as a method to fashion components in your webpage which are empty.

You may marvel why you’d need to fashion one thing that’s empty. Let’s say you’re making a todo listing.

You need to put your todo gadgets in an inventory, however what about once you don’t…

Again in 2023, I belatedly jumped on the bandwagon of individuals posting their CSS want lists for the approaching yr.  This yr I’m doing all that once more, much less belatedly! (I didn’t do it final yr as a result of I couldn’t even.  Get it?)

I began this submit by taking a look at what I…

It does, really. In Firefox. Generally.

A significant danger of utilizing ARIA to outline textual content content material is it sometimes will get neglected in translation. Automated translation providers usually don’t seize it. Those that pay for localization providers steadily miss content material in ARIA attributes when sending textual content strings to localization distributors.

Content material buried…

6 years again I posted the Easiest Method to Load CSS Asynchronously to doc a hack we’d been utilizing for a minimum of 6 years previous to that. The use case for this hack is to load CSS information asynchronously, one thing that HTML itself nonetheless doesn’t assist, though…

This text is a sponsored by DebugBear

I used to be chatting with DebugBear’s Matt Zeunert and, within the course of, he casually talked about this factor referred to as Tight Mode when describing how browsers fetch and prioritize assets. I needed to nod alongside like I knew what he was speaking about…

I’ve been excited by the potential of text-box-trim, text-edge and text-box for some time. They’re in draft standing in the meanwhile, however when extra browser assist is offered, this functionality will open up some thrilling potentialities for enhancing typesetting within the browser, in addition to giving us extra…

It’s slightly totally different. For one, I’m solely fetching 10 gadgets at a time. We may push that to infinity however that comes with a efficiency tax, to not point out I’ve no manner of organizing the gadgets for them to be grouped and filtered. Perhaps that’ll be a future enhancement!

The Chris demo supplied the bones and it does many of the heavy lifting. The “robust” elements have been square-pegging the factor right into a WordPress block structure after which getting transients going. That is my first time working with transients, so I believed I’d share the related code and decide it aside.

operate fetch_and_store_data() {
  $transient_key = 'fetched_data';
  $cached_data = get_transient($transient_key);

  if ($cached_data) {
    return new WP_REST_Response($cached_data, 200);
  }

  $response = wp_remote_get('https://feedbin.com/starred/a22c4101980b055d688e90512b083e8d.xml');
  if (is_wp_error($response)) {
    return new WP_REST_Response('Error fetching knowledge', 500);
  }

  $physique = wp_remote_retrieve_body($response);
  $knowledge = simplexml_load_string($physique, 'SimpleXMLElement', LIBXML_NOCDATA);
  $json_data = json_encode($knowledge);
  $array_data = json_decode($json_data, true);

  $gadgets = [];
  foreach ($array_data['channel']['item'] as $merchandise) {
    $gadgets[] = [
      'title' => $item['title'],
      'hyperlink' => $merchandise['link'],
      'pubDate' => $merchandise['pubDate'],
      'description' => $merchandise['description'],
    ];
  }

  set_transient($transient_key, $gadgets, 12 * HOUR_IN_SECONDS);

  return new WP_REST_Response($gadgets, 200);
}

add_action('rest_api_init', operate () {
  register_rest_route('customized/v1', '/fetch-data', [
    'methods' => 'GET',
    'callback' => 'fetch_and_store_data',
  ]);
});

May this be refactored and written extra effectively? All indicators level to sure. However right here’s how I grokked it:

operate fetch_and_store_data() {

}

The operate’s identify may be something. Naming is tough. The primary two variables:

$transient_key = 'fetched_data';
$cached_data = get_transient($transient_key);

The $transient_key is solely a reputation that identifies the transient after we set it and get it. In truth, the $cached_data is the getter in order that half’s completed. Test!

I solely need the $cached_data if it exists, so there’s a test for that:

if ($cached_data) {
  return new WP_REST_Response($cached_data, 200);
}

This additionally establishes a brand new response from the WordPress REST API, which is the place the information is cached. Relatively than pull the information immediately from Feedbin, I’m pulling it and caching it within the REST API. This fashion, CORS is now not a difficulty being that the starred gadgets at the moment are regionally saved by myself area. That’s the place the wp_remote_get() operate is available in to kind that response from Feedbin because the origin:

$response = wp_remote_get('https://feedbin.com/starred/a22c4101980b055d688e90512b083e8d.xml');

Equally, I made a decision to throw an error if there’s no $response. Meaning there’s no freshly $cached_data and that’s one thing I need to know immediately.

if (is_wp_error($response)) {
  return new WP_REST_Response('Error fetching knowledge', 500);
}

The majority of the work is merely parsing the XML knowledge I get again from Feedbin to JSON. This scours the XML and loops by way of every merchandise to get its title, hyperlink, publish date, and outline:

$physique = wp_remote_retrieve_body($response);
$knowledge = simplexml_load_string($physique, 'SimpleXMLElement', LIBXML_NOCDATA);
$json_data = json_encode($knowledge);
$array_data = json_decode($json_data, true);

$gadgets = [];
foreach ($array_data['channel']['item'] as $merchandise) {
  $gadgets[] = [
    'title' => $item['title'],
    'hyperlink' => $merchandise['link'],
    'pubDate' => $merchandise['pubDate'],
    'description' => $merchandise['description'],
  ];
}

“Description” is a loaded time period. It could possibly be the complete physique of a submit or an excerpt — we don’t know till we get it! So, I’m splicing and trimming it within the block’s Edit part to stub it at not more than 50 phrases. There’s slightly danger there as a result of I’m rendering the HTML I get again from the API. Safety, sure. However there’s additionally the prospect I render an open tag with out its closing counterpart, muffing up my structure. I do know there are libraries to deal with that however I’m holding issues easy for now.

Now it’s time to set the transient as soon as issues have been fetched and parsed:

set_transient($transient_key, $gadgets, 12 * HOUR_IN_SECONDS);

The WordPress docs are nice at explaining the set_transient() operate. It takes three arguments, the primary being the $transient_key that was named earlier to determine which transient is getting set. The opposite two:

  • $worth: That is the thing we’re storing within the named transient. That’s the $gadgets object dealing with all of the parsing.
  • $expiration: How lengthy ought to this transient final? It wouldn’t be transient if it lingered round perpetually, so we set an period of time expressed in seconds. Mine lingers for 12 hours earlier than it expires after which updates the following time a customer hits the web page.

OK, time to return the gadgets from the REST API as a brand new response:

return new WP_REST_Response($gadgets, 200);

That’s it! Effectively, a minimum of for setting and getting the transient. The following factor I noticed I wanted was a customized REST API endpoint to name the information. I actually needed to lean on the WordPress docs to get this going:

add_action('rest_api_init', operate () {
  register_rest_route('customized/v1', '/fetch-data', [
    'methods' => 'GET',
    'callback' => 'fetch_and_store_data',
  ]);
});

That’s the place I struggled most and felt like this all took wayyyyy an excessive amount of time. Effectively, that and sparring with the block itself. I discover it tremendous onerous to get the back and front finish elements to sync up and, actually, a whole lot of that code appears to be like tremendous redundant should you have been to scope it out. That’s one other story altogether.

Take pleasure in studying what we’re studying! I put a web page collectively that pulls within the 10 most up-to-date gadgets with a hyperlink to subscribe to the complete feed.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments