Archived topic
Populate Block Element with Absolute URL
9 replies · Started by Ian on August 15, 2022
In trying to create a Facebook share button, we need this insert this snippet to display the FB button:
<div class="fb-share-button"
data-href="https://www.your-domain.com/your-page.html"
data-layout="button_count">
Is there a way to display the absolute URL into the data-href field using a Block Element?
Hi Ian,
You can use a hook element to insert the HTML code or a block element with the Custom HTML block.
Thanks Ying. Yes, I am trying to use the Block Element for easy future maintenance. How do we populate https://www.your-domain.com/your-page.html with the current URL that user is on?
`<div class="fb-share-button"
data-href="https://need-this-absolute-url"
data-layout="button_count">'
I'm not sure I fully understand your question, are you using a plugin for the share button? Or you are trying to code it yourself?
If you are using a plugin, can you show us the plugin instruction?
Let me know!
We are trying not to use a plugin. Facebook has instructions here to do this manually: https://developers.facebook.com/docs/plugins/share-button/#share-button
We have all variables working, we just need to populate data-href in the actual button placement now.
Add-On: Looks like Yoast may actually be providing us with og:url. FB instructions indicate that og:url and data-href should use the same URL. Now we need to populate this:
<!-- Your share button code -->
<div class="fb-share-button"
data-href="https://www.your-domain.com/your-page.html"
data-layout="button_count">
</div>
Any ideas?
Can't the plugin generate the current URL by itself?
Try adding this code to a hook element:
<?php
$absolute_url = get_permalink( get_the_ID() );
echo '<div class="fb-share-button" data-href="' .$absolute_url.'" data-layout="button_count"></div>';
?>
Tick the execute PHP box.
Let me know if it works.
Thank you Ying. Your code works perfectly. I did notice we may have to use execute php but this only works inside a hook. Is there any way to make this work inside a Block Element? We will need to add other buttons and it may be easier to manage a GB grid in the long run.
Yes, instead outputing the code directly in the hook element, we can create a shortcode [fb-share-button] using the below code:
add_shortcode( 'fb-share-button', function() {
ob_start();
$absolute_url = get_permalink( get_the_ID() );
echo '<div class="fb-share-button" data-href="' .$absolute_url.'" data-layout="button_count"></div>';
return ob_get_clean();
} );
Then you should be able to using a shortcode block in the block element.
ok Ying. Amazing stuff. I should have thought of adding a shortcode function, thank you!
You are welcome :)