WordPress How To Add meta tags to the header

By default, WordPress does not add the needed tags to the head section, so that previews on social media look good. It does to a certain degree especially if you add featured images manually to a blog post.

However, if you’re automating any part of the blog post creation, then there is a way to search the blog content for a suitable image and use that. This then happens dynamically.

Add the following code to your theme’s function.php file: –

// Add custom meta to the header

function set_header_metadata(){

global $post;

$post_id = $post->ID;
if (empty($post_id)) {

$PageTitle = $post->post_title;
$posttype = $post->post_type;
$permalink = get_permalink($post->id);

// Attempt to retrieve the img source
$doc = new DOMDocument();
$tags = $doc->getElementsByTagName(‘img’);
$PageImage = null;
foreach ($tags as $tag) {
if (!$PageImage) {
$PageImage = $tag->getAttribute(‘src’);

if (strpos(strtolower($PageImage),’.jpg’) !== false ||
strpos(strtolower($PageImage),’.jpeg’) !== false) {
if (strpos(strtolower($PageImage),’.gif’) !== false) {

$metatag = ‘<meta property=\”og:title\” content=\”‘.$PageTitle.’\” />’;
$metatag .= ‘<meta property=\”og:image\” content=\”‘.$PageImage.’\” />’;
$metatag .= ‘<meta property=\”og:image:type\” content=\”‘.$PageContent.’\” />’;
$metatag .= ‘<meta property=\”og:type\” content=\”article\” />’;

echo $metatag;
add_action(‘wp_head’, set_header_metadata);

You can see this being used by looking at blog posts on CryptoSocialClub, where we have feeds coming in from blog authors. The blog posts are created automatically, so now it adds the meta tags correctly so they look great on Facebook, Google+ etc. etc.

This entry was posted in News. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.