Linking images in WordPress Paginated Post

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:

?php 
  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!

Thanks.

Topic wp-link-pages linking pagination Wordpress

Category Web


_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);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.