I’ve got a lot of catching up to do with Tom Woodward on building sites that draw content from WordPress ones via the API but I’ve got reason and interest to start.

This has been a back of the mind idea for while for my sites that rely on random images drawn from the flickr API, e.g. pechaflickr and Five Card Flickr stories. They have been running quite fine for years, but a commons concern question is about the chance of one of the random images that come into play being inappropriate (like a photo of beets).

Many people might be interesting in running these kinds of sites from an image collection they control. The back brain engines have been mulling how it might work from using the WordPress API to get the featured images from photos in a site running my TRU Collector SPLOT theme.

I’ve only done a tiny bit of WordPress API tinkering, making a goofy site for the front end of arganee.world that repeatedly loaded some random text pulled via WordPress API from posts on the site.

Rather than pile on more verbiage, I am testing pulling stuff from the SPLOT Collector demo site, what I really need are, at a minimum, the featured images for each post.

What I was able to do, with a bit of code banging, was a custom API call to pull a given number of images (the last number on the URL is a parameter, returning an array of the title of the post, the link to the post, and the link to the thumbnail image, e.g. gimme 8

http://splot.ca/collector/wp-json/splotcollector/v1/randy/8, resulting ins returns like:

Here is the test bit of all the working pieces, running in codepen

See the Pen Pechasplot by Alan Levine (@cogdog) on CodePen.

Like I said, duct tape and crude.

So as it turns out, via the built in API there’s not a means to query for a random post, like one can do in WordPress via a WP_Query. So for what I wanted, it meant digging into adding my own custom endpoint to do the task.

Here is the code running on the site, added to functions.php that sets up the custom API call and handles what is sent back

It’s a start. But I can see with some connection to the existing scripts, to see a version of pechaflickr that would draw images from a SPLOT.


Featured Image: File:Duct-tape Moving Van.jpg Wikimedia Commons image shared into the public domain as the work of a US Government employee

If this kind of stuff has value, please support me by tossing a one time PayPal kibble or monthly on Patreon
Become a patron at Patreon!
Profile Picture for CogDog The Blog
An early 90s builder of web stuff and blogging Alan Levine barks at CogDogBlog.com on web storytelling (#ds106 #4life), photography, bending WordPress, and serendipity in the infinite internet river. He thinks it's weird to write about himself in the third person. And he is 100% into the Fediverse (or tells himself so) Tooting as @cogdog@cosocial.ca

Comments

  1. Cue the music… the truck is rolling through your neighborhood, blaring the music, here to deliver random images to all the kids– and the truck is fueled by json.

    THE SPLOT TRUCK IS HERE!

    This could be a way for the TRU Collector SPLOT to provide random images that might one day, be an alternative source than flickr for both pechaflickr and Five Card Photo Stories. This would take away concerns over the using flickr as a source (it comes up legit as a question for teachers), but more if you wanted a way to manage the pool of photos without a third party host.

    It started with a tweeted question from my pal @dogtrax.

    @cogdog Alan, what is that browser add-on you have mentioned and used that grabs random Creative Commons via Flickr? (Am I remembering this right?) I want to find something to use as random visual prompts for writing poetry … thx— KevinHodgson (@dogtrax) March 30, 2019

    I had a hard time this morning connecting the dots to what Kevin was referring to (maybe not yet enough coffee), but then realized maybe it was this nifty service Lorem Flickr which you can use in HTML anywhere it wants an image, and it serves up CC licensed ones from flickr.

    For example, using the URL in an img tag will give a different dog each time, 640×480 pixels in dimensions:

    The code for this is

    <img src=”https://loremflickr.com/640/480/dog” width=”640″ height=”480″ alt=”random dog from flickr”>

    1

    <img src=“https://loremflickr.com/640/480/dog” width=“640” height=“480” alt=“random dog from flickr”>

    That’s pretty nifty, right? Random dog photos. The options on Lorem Flickr let you do a few more tricks.

    I had used it for a #netarr activity that maybe did not even get used, something I toyed around with for a site that generated a random character with random information using like 4 different services, all done in the browser.

    #NetNarr Experience (Proceed if you dare)” class=”wp-image-67652″ srcset=”https://cogdogblog.com/wp-content/uploads/2019/03/characters-cubed-760×465.jpg 760w, https://cogdogblog.com/wp-content/uploads/2019/03/characters-cubed-1280×783.jpg 1280w, https://cogdogblog.com/wp-content/uploads/2019/03/characters-cubed.jpg 1892w” sizes=”(max-width: 760px) 100vw, 760px” />An experimental site to generate characters for Networked Narratives.

    Then I thought about a playful site I did to with a free domain I got from Reclaim Hosting (it was for coming up with an original domain)

    Made this site to hit flickr API for lesser known photographers. Could be modified to pull one a day. You want wide open random, Kevin or by any kind of search. https://t.co/0IffdainlI— Alan Levine (@cogdog) March 30, 2019

    That site uses server side scripting to rewrite the web site every hour; it does some flickr API calls to find photos at the bottom of the interesting list and key words of “dull” or “boring”, and retrieves info on the last 10 photos by the same person.

    That could work, with bit of fiddling to do one every day to change it up (via a server cron script), to be a random prompt kind of site that automatically updated itself.

    And then another memory- I had started work to add some custom endpoints to the WordPress API so any site running the TRU Collector theme to be the source of random images.

    You can see what the special endpoint does (the built on WordPress ones do not do random selection of content), by using a URL on the SPLOT TRU Collector demo site like:

    http://splot.ca/collector/wp-json/splotcollector/v1/randy/12

    The number at the end tells it how many images to send back data for. I’m able to return a number of useful bits of info for the entry at http://splot.ca/collector/45/

    [
    {
    “title”: “Happy as a Sheep”,
    “link”: “http://splot.ca/collector/45/”,
    “sharedby”: “@cogdog”,
    “license”: “CC BY Creative Commons By Attribution”,
    “images”: {
    “thumb”: “http://splot.ca/collector/files/2015/01/15116810596_13effa377f_b-150×150.jpg”,
    “large”: “http://splot.ca/collector/files/2015/01/15116810596_13effa377f_b.jpg”
    }
    }
    ]

    123456789101112

    [ { “title”: “Happy as a Sheep”, “link”: “http://splot.ca/collector/45/”, “sharedby”: “@cogdog”, “license”: “CC BY Creative Commons By Attribution”, “images”: { “thumb”: “http://splot.ca/collector/files/2015/01/15116810596_13effa377f_b-150×150.jpg”, “large”: “http://splot.ca/collector/files/2015/01/15116810596_13effa377f_b.jpg” } }]

    Including title, url for the page with the image, who contributed to the site (hey, that’s me), and URLs for a thumbnail and large size images.

    This is done in the SPLOT site by registering a new endpoint for the API.

    add_action( ‘rest_api_init’, function () {
    // redister a route for just random images, accept a paraemeter for the number of random images to fetch
    register_rest_route( ‘splotcollector/v1’, ‘/randy/(?P<n>d+)’, array(
    ‘methods’ => ‘GET’,
    ‘callback’ => ‘trucollector_randy’,
    ‘args’ => array(
    ‘n’ => array(
    ‘validate_callback’ => function($param, $request, $key) {
    return is_numeric( $param );
    }
    ),
    )
    ) );
    }

    1234567891011121314

    add_action( ‘rest_api_init’, function () { // redister a route for just random images, accept a paraemeter for the number of random images to fetch register_rest_route( ‘splotcollector/v1’, ‘/randy/(?P<n>d+)’, array( ‘methods’ => ‘GET’, ‘callback’ => ‘trucollector_randy’, ‘args’ => array( ‘n’ => array( ‘validate_callback’ => function($param, $request, $key) { return is_numeric( $param ); } ), ) ) );}

    which define the URL path and the last parameter as a variable for the number of images. The callback function retrieves the data to send back.

    function trucollector_randy( $data ) {
    // general function for getting random images, first test version

    // get specified random number of posts
    $posts = get_posts( array( ‘orderby’ => ‘rand’, ‘posts_per_page’ => $data[‘n’]) );

    // bad news here
    if ( empty( $posts ) ) {
    return null;
    }

    // walk the results, add to array
    foreach ($posts as $item) {

    // find code for license, if not present set to code for unknown
    $lic = ( get_post_meta( $item->ID, ‘license’, 1 ) ) ? get_post_meta( $item->ID, ‘license’, 1 ) : ‘u’;

    $found[] = array(
    ‘title’ => $item->post_title,
    ‘link’ => get_permalink( $item->ID ),
    ‘sharedby’ => get_post_meta( $item->ID, ‘shared_by’, 1 ),
    ‘license’ => trucollector_get_the_license( $lic ),
    ‘images’ => array(
    ‘thumb’ => wp_get_attachment_image_src( get_post_thumbnail_id( $item->ID ), ‘thumbnail’)[0],
    ‘large’ => wp_get_attachment_image_src( get_post_thumbnail_id( $item->ID ), ‘large’)[0]
    )
    );
    }
    // server up some API goodness
    return new WP_REST_Response( $found, 200 );
    }

    1234567891011121314151617181920212223242526272829303132

    function trucollector_randy( $data ) { // general function for getting random images, first test version // get specified random number of posts $posts = get_posts( array( ‘orderby’ => ‘rand’, ‘posts_per_page’ => $data[‘n’]) ); // bad news here if ( empty( $posts ) ) { return null; } // walk the results, add to array foreach ($posts as $item) { // find code for license, if not present set to code for unknown $lic = ( get_post_meta( $item>ID, ‘license’, 1 ) ) ? get_post_meta( $item>ID, ‘license’, 1 ) : ‘u’; $found[] = array( ‘title’ => $item>post_title, ‘link’ => get_permalink( $item>ID ), ‘sharedby’ => get_post_meta( $item>ID, ‘shared_by’, 1 ), ‘license’ => trucollector_get_the_license( $lic ), ‘images’ => array( ‘thumb’ => wp_get_attachment_image_src( get_post_thumbnail_id( $item>ID ), ‘thumbnail’)[0], ‘large’ => wp_get_attachment_image_src( get_post_thumbnail_id( $item>ID ), ‘large’)[0] ) ); } // server up some API goodness return new WP_REST_Response( $found, 200 );}

    I then started tinkering with a simple site to get one random image via JSON and display it (using the ever useful Backstretch.js to fill the screen).

    See it in action first at http://lab.cogdogblog.com/randysplot/ (you will of course get a different image than this one… just reload to swap in a new one).

    Random image pulled via browser script from http://splot.ca/collector

    The HTML is basic, just place holders for content loaded down below it.

    <div id=”stuff” class=”trans_box1″>
    <h1 id=”title”></h1>
    <p class=”small”>An experiment in random images drawn from the SPLOT at <span id=”splot”></span><br><span id=”license”></span> <span id=”sharedby”></span></p>
    <p id=”furl”></p>
    </div>

    12345

    <div id=“stuff” class=“trans_box1”> <h1 id=“title”></h1> <p class=“small”>An experiment in random images drawn from the SPLOT at <span id=“splot”></span><br><span id=“license”></span> <span id=“sharedby”></span></p> <p id=“furl”></p> </div>

    We lazily load in from remote libraries a jquery library and the backstretch.js code:

    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script>
    <script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.3/jquery.backstretch.min.js”></script>
    <script>

    123

    <script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”></script><script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.3/jquery.backstretch.min.js”></script> <script>

    The work is done in jQuery code. We define a source site for the SPLOT, set up a function to populate the in page content, and then use an Ajax call to get the remote data (likely needs some error checking in case it get nothing, hey this is a beta version).

    $(document).ready(function(){

    // this sets the image source, in the future it could be
    // a front page entry
    var splot_source = ‘http://splot.ca/collector’;

    function update_backdrop ( fromsplot ) {
    // populates the page with stuff from the remotely fetched json data
    randyimage = fromsplot[0];

    // load the background image
    $.backstretch(randyimage.images.large);

    // set the title and source of the SPLOT site
    $(‘#title’).text(randyimage.title);
    $(‘#splot’).text(splot_source);

    // load license data
    if (randyimage.license === null) randyimage.license = “Rights Status Unknown”;
    $(‘#license’).html(‘This image is licensed: <strong>’ + randyimage.license + ‘</strong>’);

    // load the credit data
    if (randyimage.sharedby != ”) $(‘#sharedby’).html( ‘and was shared by <strong>’ + randyimage.sharedby + ‘</strong>’);

    // add link to the source splot item page
    $(‘#furl’).html(‘<a href=”‘ + randyimage.link + ‘” target=”_blank” rel=”noopener noreferrer”>’ + randyimage.link + ‘</a>’);
    }

    // Let’s get some images!
    $.ajax({
    url: splot_source + ‘/wp-json/splotcollector/v1/randy/1′,
    jsonp:”cb”,
    dataType:’json’,
    success: function(data) {
    // save the results in array we can use later
    splotstuff = data;

    // use function to update display
    update_backdrop(splotstuff);

    } //success
    }); //ajax

    });//ready
    </script>

    12345678910111213141516171819202122232425262728293031323334353637383940414243444546

    $(document).ready(function(){ // this sets the image source, in the future it could be // a front page entry var splot_source = ‘http://splot.ca/collector’; function update_backdrop ( fromsplot ) { // populates the page with stuff from the remotely fetched json data randyimage = fromsplot[0]; // load the background image $.backstretch(randyimage.images.large); // set the title and source of the SPLOT site $(‘#title’).text(randyimage.title); $(‘#splot’).text(splot_source); // load license data if (randyimage.license === null) randyimage.license = “Rights Status Unknown”; $(‘#license’).html(‘This image is licensed: <strong>’ + randyimage.license + ‘</strong>’); // load the credit data if (randyimage.sharedby != ) $(‘#sharedby’).html( ‘and was shared by <strong>’ + randyimage.sharedby + ‘</strong>’); // add link to the source splot item page $(‘#furl’).html(‘<a href=”‘ + randyimage.link + ‘” target=”_blank” rel=”noopener noreferrer”>’ + randyimage.link + ‘</a>’); } // Let’s get some images! $.ajax({ url: splot_source + ‘/wp-json/splotcollector/v1/randy/1’, jsonp:“cb”, dataType:‘json’, success: function(data) { // save the results in array we can use later splotstuff = data; // use function to update display update_backdrop(splotstuff); } //success }); //ajax });//ready</script>

    This was a good practice to do some basic random image fetching. You can get the source code for this at https://github.com/cogdog/splotlab/tree/master/docs/randysplot

    The part I need to figure out next to make a pechasplot demo is figuring out in the WordPress code to create the custom API endpoint, how to have 2 variables in the URL (one for number of images to get and another to limit by tag).

    Do you hear the call of the SPLOT truck? It’s full of random images to deliver.

    Featured Image: Added SPLOT logo and some json code to The Super Green Lime Ice Cream Truck flickr photo by Señor Codo shared under a Creative Commons (BY-SA) license


    If this kind of stuff has value, please support me by tossing a one time PayPal kibble or monthly on Patreon


Leave a Reply

Your email address will not be published. Required fields are marked *