WordPress循环中的Facebook共享功能

时间:2014-06-28 作者:Nisham Mahsin

我正在尝试添加facebook share my的功能wordpress 职位。在我的wp loop 我有一个共享按钮

<a class="action_button"  href="javascript:void(0)" id="share_button" target="_blank"> share this</a>
我不想post title ,post thumpnail 等等。我的代码有什么问题。

在开始循环之前,我有如下javascript代码

<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>

2 个回复
SO网友:Pim

Javascript在循环之外,因此php永远无法访问get_the_title(), get_permalink()get_the_post_thumbnail() 从那里开始。

我要做的是在循环中的某个地方包括这些内容,例如:

<div class="entry-content">
    <h2 class="post-title"><?php the_title(); ?></h2>
    <a class="share-button" data-title="<?php the_title(); ?>"></a>
</div>
然后使用jQuery,您可以从循环生成的HTML中获取它们。例如,以下内容(对链接和图片也一样):

<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>

SO网友:astrovish

尝试删除single quotes 从下面的代码中:

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

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

结束