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

On click I want to open a popup window which will allow my visitors to share my blog via FACEBOOk. Everything works great, but the problem is I cant get the permalink of the current article. How to add php in javascript?

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

Related posts

Leave a Reply

1 comment

  1. the_permalink() only works within “the loop”.

    I assume this code is outside of the main post loop in which case you need to use get_permalink() and pass the ID of the post that is being viewed.

    You can get the ID of the current post by getting the post object from the $wp_query;

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

    Now you can use:

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