Connect with us

    Hi, what are you looking for?

    Devs

    How to Add Open Graph Tags in WordPress Using PHP

    How to Add Open Graph Tags in WordPress Using PHP

    Open Graph (OG) tags are essential for ensuring that your website content is displayed correctly on social media platforms when shared. These tags help platforms determine which image, title, and description to use when showcasing your content. In this article, you’ll learn how to add these tags to your WordPress theme using PHP, ensuring that the featured image is correctly displayed for each shared post.

    Step 1: Understanding Open Graph Tags

    Before diving into the code, let’s review what Open Graph tags are and why they are important.


    • og:title: Defines the title of the post.
    • og:description: Provides a brief description of the post.
    • og:image: Specifies the image to be used when sharing the post.
    • og:url: Specifies the canonical URL of the post.
    • og:type: Defines the type of content, such as an article, video, etc. For blog posts, we use “article”.

    These tags are placed within the <head> section of your site’s HTML and are read by social media platforms like Facebook, Twitter, and LinkedIn, among others.

    Step 2: Adding the Code to Your Theme

    Now that you understand the importance of Open Graph tags, let’s add the necessary code to your theme’s functions.php file. If you’re using a child theme, add the code to the child theme’s functions.php file to ensure your changes are not overwritten during future updates to the parent theme.

    1. Access the WordPress Dashboard and go to Appearance > Theme Editor.
    2. Select the functions.php file of your theme or child theme.
    3. Add the following PHP code at the end of the file:
    4. function add_opengraph_tags() {
      if (is_single() || is_page()) {
      global $post;
      if (has_post_thumbnail($post->ID)) {
      $img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), ‘full’);
      } else {
      // Default image URL if the post has no featured image
      $img_src = array(‘https://www.example.com/default-image.jpg’);
      }// Post title
      $title = get_the_title();
      // Post description
      $description = get_the_excerpt();echo ‘<meta property=”og:title” content=”‘ . esc_attr($title) . ‘”/>’;
      echo ‘<meta property=”og:description” content=”‘ . esc_attr($description) . ‘”/>’;
      echo ‘<meta property=”og:image” content=”‘ . esc_url($img_src[0]) . ‘”/>’;
      echo ‘<meta property=”og:url” content=”‘ . get_permalink() . ‘”/>’;
      echo ‘<meta property=”og:type” content=”article”/>’;
      }
      }
      add_action(‘wp_head’, ‘add_opengraph_tags’);

    Code Explanation:

    • add_opengraph_tags(): This function checks if the current page is a post or page and, if so, generates the appropriate Open Graph tags.
    • Featured Image:
      • has_post_thumbnail($post->ID): Checks if the post has a featured image set.
      • wp_get_attachment_image_src(): Retrieves the full-size URL of the featured image. If the post does not have a featured image, a default image is used.
    • Title and Description:
      • get_the_title() and get_the_excerpt(): Retrieve the post title and description, which are used for the og:title and og:description tags, respectively.
    • Canonical URL and Content Type:
      • get_permalink(): Retrieves the URL of the current post for the og:url tag.
      • og:type: Set to “article” to indicate that the content is an article.

    Step 3: Verifying the Implementation

    After adding the code to functions.php, it’s important to verify that the Open Graph tags are being generated correctly.

    1. View the page source: On any post or page, right-click and select “View Page Source” or a similar option. Look for the Open Graph tags within the <head> section.
    2. Use the Facebook Sharing Debugger:
      • Visit the Facebook Sharing Debugger.
      • Enter the URL of your post and click “Debug”.
      • Facebook will show the information it detects, including the image, title, and description. This helps identify if the tags are being generated correctly.

    Step 4: Troubleshooting Common Issues

    • Image Not Displaying: Ensure that the featured image is set on the post. If a default image is used, verify that the image URL is correct and publicly accessible.
    • Conflicts with Other Plugins: Some SEO or social media plugins may interfere with the generation of Open Graph tags. Try temporarily disabling these plugins to see if the issue persists.
    • Caching: If you’re using a caching plugin, clear the site’s cache to ensure the new settings are applied.

    Summary

    Adding Open Graph tags manually to your WordPress theme using PHP is an excellent way to ensure your content is displayed correctly on social media platforms. With this code, you have full control over how your posts are shared, including which image, title, and description are used. Additionally, you avoid relying on extra plugins, keeping your site lighter and faster.


    Now that you’ve configured the Open Graph tags, your posts should be shared correctly on social media, with the featured images appearing as expected. If you have any questions or need further assistance, feel free to leave a comment below!

    Photo by Negative Space

    Written By

    My name is Juan de Souza, a 26-year-old entrepreneur, investor, blogger, and streamer. My journey in business began at the age of 10, leveraging a dial-up internet connection in Brazil to start my first venture. Currently, I reside in Porto, Portugal, where I have been based since 2025.

    Comments
    Advertisement

    Join Our Discord Server

    Advertisement
    Advertisement

    Recommended Posts for You

    HeartstopperHeartstopper

    LGBTQIA+

    Check out the full review of Netflix's Heartstopper series and find out if the Heartstopper series delivers everything it promises in full!

    Cinema

    “One of the most memorable cartoons of the 20th and 21st centuries. Its story, characters and writing are utterly captivating. “Little Bear” is known...

    Curiosities

    Super Mario World, also known as “Super Mario Bros. 4” in Japan, is without a doubt one of the most popular games of all...

    Cinema

    “Courage the Cowardly Dog” tells the story of Courage, a dog who’s easily scared and lives on a farm with Muriel and Eustace Bagge...

    Cinema

    Who doesn’t know this epic cartoon from Hanna-Barbera, Wacky Races, where eleven competitors vied in every episode for the world title of “World’s Wackiest...

    Cinema

    Sagwa, one of the best cartoons still airing on the Futura channel. In fact, all the shows on Futura are excellent. It tells the...

    Cinema

    “Do you remember the classic cartoon Timon and Pumbaa? It’s an animated TV series produced by Walt Disney Animation, starring the warthog and meerkat...

    Cinema

    At the end of the 1930s, animation was at its peak. It was called the “Golden Age” by many film enthusiasts, where classic characters...

    Curiosities

    Grand Theft Auto V (GTA V) is known for its vast open-world gameplay, where players can explore, complete missions, or just cause chaos. One...

    Cinema

    Woody Woodpecker, one of the most beloved characters of all time. Adored by children, teenagers, and adults alike. The show itself dates back to...

    Others

    “Castelo Rá‑Tim‑Bum” premiered in 1994 on TV Cultura, delighting fans of the original “Rá‑Tim‑Bum” who were tired of its reruns, as well as other...

    Tech

    If you grew up playing console games in the 1980s and 90s and never heard this one, count yourself lucky—very lucky. Here’s the urban...

    DisneyDisney

    Cinema

    Walt Disney, one of the largest and most influential entertainment giants in the world, has a long history of innovation in animation. From its...

    Games

    “Nintendo 64” is Nintendo’s third home video game console. Commonly abbreviated as “N64,” it launched on June 23, 1996 (Japan) and on September 29 in the United States....

    Games

    How about transforming your Minecraft into an even more immersive game? With that in mind, the “Realistico” Mod Pack was developed—a texture pack with...

    Games

    It's time to talk about Far Cry 4: a new game in the iconic open-world franchise that first arrived over 10 years ago with paradisiacal...

    Should I Cover My Webcam with a Sticker?Should I Cover My Webcam with a Sticker?

    Tech

    We’ve all heard about the risks of being tracked online and how cybercriminals exploit vulnerabilities to access personal data. One particular topic that often...

    Games

    You’ve definitely seen, heard about, or played Just Dance at some point—it’s simply one of the most incredible games ever created and maintained by...

    Games

    Need For Speed Heat has finally hit the streets and is increasingly reminiscent of the franchise’s golden-era titles, such as Need For Speed Underground...

    Plants vs. Zombies Garden WarfarePlants vs. Zombies Garden Warfare

    Games

    Recently, Plants vs. Zombies Garden Warfare was released—it’s the new game from PopCap, famous for its mobile hits. This time, we have a review...