简体   繁体   中英

Wordpress - get_permalink post id outside loop

I've been struggling with this question for a while and although there's some topics regarding this subject I'm not sure how to implement it. It's regarding social buttons on homepage sharing the 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!

see image for what I mean:

You'll need to get the ID of the page at the top of the template:

<?php $postid = get_the_ID(); ?>

Then in your javascript, presumably after the loop:

var bShareOpt = {url: "<?php echo get_permalink($postid); ?>"}

Not sure how your code is laid out, but hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM