Append a to every post to force additional page link (and static content)

I’m trying to affect either the content or the $post->post_content directly, before the post get read by the wp_link_pages() function, to inject a little bit of static text or javascript after the content of every post on my site.

I’ve tried appending it with an add_filter in the functions.php of my theme, but that doesn’t work as desired. with a filter on the theme function, I get the static content on each page, as opposed to a “mulligan” Nth+1 page.

For example, if my post has 8 “natural” pages, I would like a 9th page that’s a static panel with share buttons or similar.

How can I “trick” the wp_link_pages() to think there’s more to the post than what I entered as an author in the dashboard?

1 Answer
1

The multipage setting is not something that happen via a query, it is handled only via global variables, inside the setup_postdata() function.

The only thing you need is to increment a global variable and add your static content using the 'the_post' hook that is fired at the end of that function.

Something like:

add_action('the_post', function(WP_Post $post) {
    global $multipage, $numpages, $pages;
    $multipage = 1; // ensure post is considered multipage: needed for single page posts
    $numpages++; // increment number of pages
    $pages[] = my_last_page_content($post); // set the static content for last page
});

There is no need for anything else, because wp_link_pages() will understand that there is the mocked number of pages for current post and will act accordingly.

As you can see I used a custom my_last_page_content function to create content for the last page. I passed to that function the post object, because maybe you need to build your “fake” page content, e.g. to get post title or permalink.

Below a rough example:

function my_last_page_content(WP_Post $post)
{
  $format="<div><a href="https://wordpress.stackexchange.com/questions/172466/%s"><i class="fa fa-twitter"></i> %s</a></div>";
  $url="https://twitter.com/home?status="
            . urlencode(__('New blog post: ', 'txtdomain'))
            . '%22' . urlencode(apply_filters('the_title', $post->post_title)) . '%22'
            . '%20' . urlencode(get_permalink($post));

  return sprintf($format, $url, esc_html__('Share on Twitter', 'txtdomain') );
}

Leave a Comment