• Rob

    (@seomandarin)


    Hi,

    I’ve been struggling with this question for a while and altho there’s some topics regarding this subject I’m not sure how to implement it. It’s regarding social buttons on homepage sharingthe articles clicked on.

    I have to use <script type="text/javascript" charset="utf-8" >var bShareOpt = {url: "<?php echo get_permalink(); ?>"};</script> which shows the permalink of the last ID instead of the link clicked on. If I add the post_id number <?php echo get_permalink(2926); ?> it shows the correct post.

    Now this is because it happens outside the loop.

    Other topics regarding getting post id outside the loop:
    get-a-posts-id
    wordpress-get-the-page-id-outside-the-loop
    accessing-post-id-outside-of-the-loop-for-listing-child-pages

    Using get_queried_object_id or get_queried_object is apparently another option to do so.

    But unfortunately my PHP knowledge is very limited in order to glue the pieces together. I appreciate any help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi,

    Using the get_queried_object_id()-function is indeed an option here. Beer in mind that this will fetch the ID even if its a term/archive/other.

    You could do it like this:

    <?php if( isset( get_queried_object()->ID ) ) : ?>
    <script type="text/javascript" charset="utf-8" >var bShareOpt = {url: "<?php echo get_permalink( get_queried_object()->ID ); ?>"};</script>
    <?php endif; ?>

    You should also check out the wp_localize_script()-function, which can be used to pass parameters from PHP to your Javascript.

    Thread Starter Rob

    (@seomandarin)

    Hi Tormorton,

    It returns url=http%3A%2F%2Fwww.website.com%2F%3F So basically just the URL it is in without fetching the ID.

    Thanks, I’ll look into it. Tho my Javascript and PHP skills are not good enough to pass the $post_id parameters into Javascript

    Any thoughts why it doesn’t return the ID?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘get_permalink post id outside loop’ is closed to new replies.