I have a paginated post on WordPress with about 5 pages. I want to set it up so that the images in the content from the previous page automatically link to the following page.

I've used the following code in functions.php file:

  add_action('the_content',function($content) {
    global $page, $numpages, $multipage;
    if ( $multipage ) {
      $nextPage = $page + 1;
      if ( $nextPage <= $numpages ) {
        $link = _wp_link_page( $nextPage );
        $content = preg_replace('/(<img(.+?)\/>)/i','<a href="'.$link.'">$1</a>', $content);
    // send back our content, modified or not
    return $content;

The code above ALMOST works. When I substitute the $link variable for an actual URL e.g. http://google.com, all the images in a paginated post end up linking to google.com. However, when I place the variable $link there, none of the images link anywhere. Not sure if there's an issue with me using the _wp_link_page variable.

I'm totally lost as to why it won't work when the $link variable is placed, but it works with any other value.

Hopefully someone can assist. Let me know!


  • 1
    did you try to use add_filter()? – Michael Feb 26 '18 at 4:51

_wp_link_page() returns a HTML string and not just the URL address of the link. So, if the link's URL address is http://example.com/blah/2/, then _wp_link_page() would return:

<a href="http://example.com/blah/2/">

..i.e. it returns the opening a tag for that link.

So replace the following:

$content = preg_replace('/(<img(.+?)\/>)/i','<a href="'.$link.'">$1</a>', $content);

..with this:

$content = preg_replace('/(<img(.+?)\/>)/i', $link . '$1</a>', $content);
  • PS: Tried and tested with WordPress version 4.9.4. – Sally CJ Feb 26 '18 at 6:49
  • 1
    Thanks @Sally. Your solution worked. Just have to modify the syntax a little to the following. $content = preg_replace('/(<img(.+?)\/>)/i',' '.$link.'$1</a>', $content); – johndoe Feb 26 '18 at 16:42
  • You're welcome! And I'd appreciate if you could accept or vote up my answer. =) – Sally CJ Feb 27 '18 at 3:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.