1

So I am trying to add a button at the end of my blog posts, here is the code I have in the plugin so far:

<?php
/*
Plugin Name: etc....
*/

function shares_content() { ?>
  <div class='social-shares-container'>
    <a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>
  </div> <?php
}

function shares_add_buttons($content) {
  global $post;

  if (!is_page() && is_object($post)) {
    return $content . shares_content();
  }

  return $content;
}

add_filter('the_content', 'shares_add_buttons');
?>

This adds the link just before my content, but if I do something like this, it adds the new content in the desired place (after the_content):

function shares_add_buttons($content) {
  global $post;

  if (!is_page() && is_object($post)) {
    return $content . 'some random content';
  }

  return $content;
}

Could anyone tell me why this is please?

1

Your shares_content function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a return statement within another function.

You can change it to return the string:

function shares_content() {
    $content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>";
    return sprintf( $content, get_permalink() );
}

It's also worth pointing out here the use of get_permalink(). If you look at the source code, that function also returns its value. There is another API function, the_permalink(), which contains an echo instead of a return. That would also break your filter output. Most WordPress functions have two versions like this.

0

In this line:

return $content . shares_content();

You concatenate original content with result of shares_content function. So it looks correct, but then...

In that function:

function shares_content() { ?>
  <div class='social-shares-container'>
    <a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>
  </div> <?php
}

you don’t return anything, so this function has no result, so nothing is appended to the content in your filter.

But also... This function echoes div with link, so that content is printed, when the function is ran, so it gets printed before the content...

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.