Created
March 27, 2013 23:37
-
-
Save GaryJones/5259147 to your computer and use it in GitHub Desktop.
Insert ads or other content after specific paragraph in single post content. The second function here would be easily re-usable for inserting additional bits and pieces do whatever content under whatever conditions (e.g. Cinema tickets competition link after 3rd paragraph of Movie CPT).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'the_content', 'prefix_insert_post_ads' ); | |
/** | |
* Insert code for ads after second paragraph of single post content. | |
* | |
* @param string $content Post content | |
* | |
* @return string Amended content | |
*/ | |
function prefix_insert_post_ads( $content ) { | |
$ad_code = '<div>Ads code goes here</div>'; | |
if ( is_single() && ! is_admin() ) { | |
return prefix_insert_after_paragraph( $ad_code, 2, $content ); | |
} | |
return $content; | |
} | |
/** | |
* Insert something after a specific paragraph in some content. | |
* | |
* @param string $insertion Likely HTML markup, ad script code etc. | |
* @param int $paragraph_id After which paragraph should the insertion be added. Starts at 1. | |
* @param string $content Likely HTML markup. | |
* | |
* @return string Likely HTML markup. | |
*/ | |
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { | |
$closing_p = '</p>'; | |
$paragraphs = explode( $closing_p, $content ); | |
foreach ($paragraphs as $index => $paragraph) { | |
// Only add closing tag to non-empty paragraphs | |
if ( trim( $paragraph ) ) { | |
// Adding closing markup now, rather than at implode, means insertion | |
// is outside of the paragraph markup, and not just inside of it. | |
$paragraphs[$index] .= $closing_p; | |
} | |
// + 1 allows for considering the first paragraph as #1, not #0. | |
if ( $paragraph_id == $index + 1 ) { | |
$paragraphs[$index] .= $insertion; | |
} | |
} | |
return implode( '', $paragraphs ); | |
} |
$ad_code = file_get_contents('./ban.php');
For more about file_get_contents
It doesn't seems to work properly because it shows ban.php code too
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ı want to add following code between < div >here < /div > tags
include 'ban.php';
for example:
$ad_code = '
but it doesn't work how can I do this