I'm trying to count the total number of paragraphs within each blog post but it is not getting executed and hence returning nothing.
How do you want to use this code?
Currently in my function.php
I have the following code that I use to show up ads inside my post:
add_filter( 'the_content', '_some_func' );
function _some_func( $content ) {
$ad_code = "the ad code";
if ( is_singular( 'post' ) ) {
return prefix_insert_after_paragraph( $ad_code, 12, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
Now I want to take it to next level by servicing code based on now many paragraphs are there, like this:
add_filter( 'the_content', '_some_func' );
function _some_func( $content ) {
if( __check_paragraph_count_blog() > 15 )
$ad_code = "the ad code";
if ( is_singular( 'post' ) ) {
return prefix_insert_after_paragraph( $ad_code, 12, $content );
}
return $content;
}
So, I tried to write the following __check_paragraph_count_blog()
function to get the total paragraph count so that I can use it in the above call.
function __check_paragraph_count_blog() {
global $post;
if ( is_singular( 'post' ) ) {
$count = substr_count( $post->post_content, '</p>' );
return $count;
} else {
return 0;
}
}
There are 2 problem with my __check_paragraph_count_blog()
function:
- It is always returning 0
- It considers the
</p>
tags inside<code>
and<pre>
tags too.
So, if anyone can help me fix my __check_paragraph_count_blog()
function so that it work properly it will be a really big help.
functions.php
it will be executed immediately when the theme is inititiated. This is long before WP determines which post to show. So there is no post, there are no paragraphs and the count is zero. – cjbj Aug 27 '16 at 16:42