Sometimes, you may want to display social media sharing buttons for a specific post rather than all posts on your WordPress site. This guide will show you how to implement sharing buttons for a specific post using PHP.
The Code
Here’s the PHP code snippet you can use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!--php // Specify the post ID $specific_post_id = 123; // Replace 123 with your specific post ID // Check if the current post matches the specific post ID if ( get_the_ID() == $specific_post_id ) { // Get the current post URL $post_url = get_permalink(); ?--> <div class = "social-share" > <!-- Facebook Share Link --> <a href= "https://www.facebook.com/sharer.php?u=<?php echo urlencode( $post_url ); ?>" target= "_blank" > </a> <!-- Twitter Share Link --> <a href= "https://twitter.com/share?url=<?php echo urlencode( $post_url ); ?>&text=<?php echo urlencode( get_the_title() ); ?>" target= "_blank" > </a> <!-- LinkedIn Share Link --> <a href= "https://www.linkedin.com/shareArticle?mini=true&url=<?php echo urlencode( $post_url ); ?>&title=<?php echo urlencode( get_the_title() ); ?>" target= "_blank" > </a> <!-- WhatsApp Share Link --> <a href= "https://wa.me/?text=<?php echo urlencode( get_the_title() . ' ' . $post_url ); ?>" target= "_blank" > </a> <!-- Copy Link Button --> <button class = "copy-btn" onclick= "copyToClipboard()" > Copy Link</button> </div> <!--php } ?--> |
How It Works
- Specify the Post: Replace 123 in $specific_post_id = 123; with the ID of the post where you want the sharing buttons to appear.
- Check Post ID: The if ( get_the_ID() == $specific_post_id ) ensures that the sharing buttons are only displayed for the specified post.
- Generate Links: Sharing links for platforms like Facebook, Twitter, LinkedIn, and WhatsApp are dynamically created using the post's URL and title.
Adding the Code
- Locate the File: Edit your theme’s single.php or a custom template file.
- Paste the Code: Add the snippet at the desired location within the file.
- Customize: Update the icon URLs (https://example.com/) and adjust styling as needed.
Enhancements
- Dynamic Post Targeting: If you want to target multiple specific posts, replace the condition with an array, like so:
1234
$specific_posts
= [123, 456];
// Replace with your post IDs
if
( in_array( get_the_ID(),
$specific_posts
) ) {
// Display buttons
}
- Styling: Use CSS to align, style, and animate the buttons for a better user experience.
- JavaScript for Copy Button:
1234
function
copyToClipboard() {
navigator.clipboard.writeText(
"<!--php echo $post_url; ?-->"
);
alert(
"Link copied to clipboard!"
);
}
This approach ensures your social sharing buttons appear only where you need them. It's ideal for promoting a specific article or post that you want to make more shareable.
No comments:
Post a Comment