如何在JS文件中添加wordpress permalink(onclick,window.open)


How to add wordpress permalink in JS file (onclick, window.open)?

点击后,我想打开一个弹出窗口,允许我的访客通过FACEBOOk分享我的博客。一切都很好,但问题是我无法获得当前文章的永久链接。如何在javascript中添加php?

// Replace the images with the following div and pin button
    $button_div = '<div class="plugin">
      <div class="imgshare">
        <div class="postfb">
            <a onclick="popItUp()">
                <img src="http://www.example.com/wp-content/facebook.png" width="45px" />
            </a>
        </div>
      </div>
      <div class="demo"><img$1src="$2.$3" $4 width="$5" height="$6" /></div>
    </div>';
    // Replace the images with a containing div with a pin button on the image
    $content = preg_replace( $pattern, $button_div, $content );
    return $content;
    }
}
<script>
    function popItUp(url) {
        var newWindow = window.open('http://www.facebook.com/share.php?u=<?php the_permalink(); ?>&title=<?php the_title(); ?>', 'name', 'height=615,width=475,scrollbars=yes');
        if (newWindow.focus) {
            newWindow.focus();
        }
    }
</script>

the_permalink()仅在"循环"中工作。

我假设这段代码在主post循环之外,在这种情况下,您需要使用get_permalink()并传递正在查看的post的ID。

您可以通过从$wp_query中获取帖子对象来获取当前帖子的ID;

function getPostID(){
    $post = $wp_query->post;
    return $post->ID;
}

现在你可以使用:

<?php echo get_permalink(getPostID()) ?>