Site example: http://www.ianstuart-bride.com
I currently have this bit of code in header.php, but it does not work as desired:
<?php if (is_archive() && ($paged > 1) && ($paged < $wp_query->max_num_pages)) { ?>
<link rel="prefetch" href="<?php echo get_next_posts_page_link(); ?>">
<link rel="prerender" href="<?php echo get_next_posts_page_link(); ?>">
<?php } elseif (is_singular()) { ?>
<link rel="prefetch" href="<?php bloginfo('home'); ?>">
<link rel="prerender" href="<?php bloginfo('home'); ?>">
<?php } ?>
The homepage prefetch points to a non-existent page. I would like to disable prefetching on the homepage.
I want to enable prefetching on these pages, for the ‘Next’ dress.
This is the code for the single dress pages.
I tried this, but it linked to the current page instead of the next one:
<link rel="prefetch" href="<?php echo get_permalink($next_dress) ?>">
<link rel="prerender" href="<?php echo get_permalink($next_dress) ?>">
If I understand correctly you are putting that code in
header.php
, that is required in the filesingle-dress.php
usingget_header()
, and in the same file, after about 2 dozen lines, you define the variables you used 2 dozen lines before.So, either your server has an embedded time machine, or your code can’t work.
What you have to do is just define variables before you use them.
Probably, instead of messing up your code, and fill your header with a series of
if
/elseif
, you can separate your logic from your templates.I’ll write a simple class that handles the prefetching. You can save it in a separate file and require it from your
functions.php
.Please read the inline comments for more explanation.
All the logic is in the class: when
setup()
method is called, the class looks at the current query, and if it is an archive, then setup next URL to next archive page. If the page is for a single dress view, then it runs a query to get all dresses in the same collection, and if found, save adjacent post URLs in instance variables.Now we need to launch the class, i.e. call the
setup()
method on a hook fired after the main query is set, but beforewp_head()
is called:'template_include'
will be perfect.I don’t use
template_redirect
here to allow faster redirect if needed (without triggering the additional query). However,'template_include'
is a filter, so we have to return the current template. Add to yourfunctions.php
:Now, you have only to be sure in your
header.php
there is thewp_head()
call and the prefetch links will be added by the class.There is another task to do. In template file (
single-dress.php
) we need to display adjacent posts links, but we don’t need to run another query, because adjacent posts URLs are already saved in theMy_Theme_Prefetcher
instantiated on'template_include'
.So we need to access that instance and the custom filter
'my_theme_prefetcher'
that was created for the scope.So in the template, you can: