Skip to content

Instantly share code, notes, and snippets.

@GaryJones
Created March 27, 2013 23:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GaryJones/5259147 to your computer and use it in GitHub Desktop.
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).
<?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 );
}
@blurain82
Copy link

blurain82 commented Jan 18, 2017

ı want to add following code between < div >here < /div > tags

include 'ban.php';

for example:

$ad_code = '

include 'ban.php';
';
but it doesn't work how can I do this

@xqsit94
Copy link

xqsit94 commented Jan 18, 2017

$ad_code = file_get_contents('./ban.php');

For more about file_get_contents

@blurain82
Copy link

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