After some research I’ve managed to create a json file which I use as input for Twitter’s typeahead (prefetch). On my website I have several hundreds of events and several thousands of artists (both custom post types).
The json files are created using the function below (only posted one function since the function for artists is the same except it’s a different post type). Since we keep updating the events and artists, and since we have so much of both, I was wondering how I should go about running the functions. My idea was to schedule this function, so it will run once every day or so. After some more research I should be able to fix this (using this post).
Now my question is if this is good practice. I thought it would be great to schedule the functions to run every night (we have over 8000 artists so I don’t want the functions to slow down the website for visitors), but maybe there’s another efficient way of building such large datasets.
The function:
function json_events() {
$args = array(
'post_type' => 'events',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$query = new WP_Query($args);
$json = array();
while ($query->have_posts()): $query->the_post();
$json[] = get_the_title();
endwhile;
wp_reset_query();
$fp = fopen('events.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
}
Note that
WP_Cron
setted to daily is impossible to controlexactly
at what time the creation happen. If no one visit your site on night the first user on morning will experience a very long page loading time.There are some workaround, sometimes I’ve used one: create a function that hook into
shutdown
action and then, from that function call the url that run the heavy work viacurl
.However, if you have access to the cron table is better use this feature.
Also because search engines will trigger the
WP_Cron
too, so there are chances that the slow work start on search engine visit, resulting in slow page loading that will affect SEO.If you need to refresh all the file content every day there are little chances. But if all your artists/events CPT post titles don’t change every day, you can
save_post
,post_updated
anddelete_post
and when a new artist or event is added, increment the prefetch file (i.e. just append the new title instead of build entire file) with the new title. When a title is updated or a post is deleted (or restored from trash) recreate the file againIn this way you don’t need to run any heavy scheduled task, and no website slow down will occur.
I’ve written a simple plugin that do the incremental saving stuff. The plugin saves json files in the WP
uploads
directory under a/json
subfolder.To retrieve the json file url, e.g. to pass it to js you can use
Json_Posts_Incremental::get_json_url($type)
where$type
is the post type e.g.events
.Others utility functions are:
Json_Posts_Incremental::get_json_file($type)
to retrieve the file path.Json_Posts_Incremental::get_json($type)
to retrieve the json content as string.