How to get information about the current page of a paginated post in Wordpress?
Any suggestions on how I might get the word count of the current page of a paginated post in Wordpress? And in general, how to get information about only the current page of a paginated post (paginated using "").
I've made a wordcount function based on this helpful blog post: http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/how-to-display-word-count-of-wordpress-posts-without-a-plugin/ but开发者_如何学编程 that gets me the total word count for the entire post, not the count for the current page only.
Thanks much for your help!
Use $wp_query
to access the post's content and the current page number, then split the post's content into the pages using PHP's explode()
, strip all HTML-tags from the content using strip_tags()
, because they don't count as words and finally count the words of just the current page with str_word_count()
.
function paginated_post_word_count() {
global $wp_query;
// $wp_query->post->post_content is only available during the loop
if( empty( $wp_query->post ) )
return;
// Split the current post's content into an array with the content of each page as an item
$post_pages = explode( "<!--nextpage-->", $wp_query->post->post_content );
// Determine the current page; because the array $post_pages starts with index 0, but pages
// start with 1, we need to subtract 1
$current_page = ( isset( $wp_query->query_vars['page'] ) ? $wp_query->query_vars['page'] : 1 ) - 1;
// Count the words of the current post
$word_count = str_word_count( strip_tags( $post_pages[$current_page] ) );
return $word_count;
}
You will have to count words of all the posts on the page. Assuming this is inside the loop, you can define a global variable initialized to zero and then count the words displayed in each post using the method suggested in the link you have posted.
Something on this lines -
$word_count = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post();
global $word_count;
$word_count += str_word_count(strip_tags($post->post_excerpt), 0, ' ');
endwhile;
endif;
精彩评论