I'm trying to get data from a custom field and then passing that into a variable which is then used to perform a function which is - adding the tweet in the body of the_content(); This code was initially meant for inserting ads into the_content(); thats why the function is named that, didn't bother changing name yet.

I can't get the actual custom field data to echo and finish the tweet intent with what user entered because I can't use echo inside a variable.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {
  $tweet = get_field('tweet_msg');
  $tweet_intent = '<div style="margin-bottom:15px;"><a href="https://twitter.com/intent/tweet?text="'.$tweet.'">TEST</a> </div>';

  if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $tweet_intent, 2, $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 );


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.