How To Programmically Add <!–nextpage–> To WordPress Template

The short answer is that you can’t programmically add <!–nextpage–> to your single.php template or custom file.

But there is a fairly easy workaround using jQuery.

When you are splitting up a WordPress page or a post into multiple pages, you define where you want the page breaks to occur by inserting <!–nextpage–> in the WordPress text editor.

You can’t manually add a page break from within your template file because only the results of WordPress’s content the_content() will adhere to the <!–nextpage–> tag.  If it is inserted elsewhere, the tag will only be returned as an html comment.

Of course you could create a filter within your functions.php file and add shortcode to your post, but it can also be accomplished using jQuery.

In this example, we have a regular post that we want to break up into 2 pages but we also want a third page that will display some custom php code that we’ve added to single.php

To do this, we would add a div with an id of “custom-code-results” in the WordPress text editor as a placeholder for the results of our custom code that we added to single.php.  Then we’ll target the “custom-code-results” div in our post, using jQuery code that we added to single.php.

Content of WordPress Post Editor

Some content for page 1 of our WordPress post

<!--nextpage-->

Some more content in our WordPress post for page two

<!--nextpage-->

Our div that is a placeholder to be used for jQuery targeting for page 3

<div id="custom-code-results"></div>

jQuery Added To Single.php

<script>
jQuery(document).ready(function () {
  jQuery('#custom-code-results').html('custom content added to #custom-code-results div');
});
</script>

You can do just about anything within the jQuery.  Use .html to add content.  Use .append to add another div inside it.

Example

In our example, we added custom php code to single.php that we want display on the third page of our post.  In single.php we created a div with a unique id to output our php, then added it to our “custom-code-results” div using jQuery.

single.php Custom PHP

<?php

echo '<div id="custom-php">';
  $date = date('Y/m/d H:i:s');
  echo 'It is currently ' . $date;
echo '</div>';

?>

And to added this to our our “custom-code-results” div using jQuery

single.php jQuery

<script> 
jQuery(document).ready(function () { 
  jQuery('#custom-code-results').append('#custom-php'); 
}); 
</script>

 

 

Available for Amazon Prime