1

I am trying to add facebook share functionality to my wordpress posts. in my wp loop i have a share button

<a class="action_button"  href="javascript:void(0)" id="share_button" target="_blank"> share this</a>

i am not getting post title ,post thumpnail etc. what is wrong with my code.

and before starting loop i have javascript code like

<script>
  window.fbAsyncInit = function() {
     FB.init({appId: 'myappid', status: false, cookie: false, xfbml: false});
  };

  (function() {
     var e = document.createElement('script'); e.async = true;
     e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
     document.getElementById('fb-root').appendChild(e);
  }());
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: '  <?php echo get_the_title(); ?>',
link: ' <?php echo get_permalink(); ?>',
picture: '<?php echo get_the_post_thumbnail();?>',
caption: 'This is the content of the "caption" field.',
description: 'This is the content of the "description" field, below the caption.',
message: ''
});
});
});
</script>
1

The Javascript is outside the loop, so php can never access get_the_title(), get_permalink() and get_the_post_thumbnail() from there.

What I'd do is include those somewhere in the loop, for instance:

<div class="entry-content">
    <h2 class="post-title"><?php the_title(); ?></h2>
    <a class="share-button" data-title="<?php the_title(); ?>"></a>
</div>

Then with jQuery, you can grab them from the HTML generated by the loop. For instance the following (and do the same for link and picture):

<script type="text/javascript">
$(document).ready(function(){
    $('#share_button').click(function(e){
        e.preventDefault();
        var postTitle = $(this).data( "title" ); // Here's where you grab the title
        FB.ui({
            method: 'feed',
            name: postTitle,
            link: ' <?php echo get_permalink(); ?>',
            picture: '<?php echo get_the_post_thumbnail();?>',
            caption: 'This is the content of the "caption" field.',
            description: 'This is the content of the "description" field, below the caption.',
            message: ''
        });
    });
});
</script>
-1

Try removing single quotes from your code like this:

name: '  <?php echo get_the_title(); ?>',
link: ' <?php echo get_permalink(); ?>',
picture: '<?php echo get_the_post_thumbnail();?>',

Replace With

name:    <?php echo get_the_title(); ?>,
link:    <?php echo get_permalink(); ?>,
picture: <?php echo get_the_post_thumbnail();?>,

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.