0

I'm trying to create php code to change the Wordpress header. With the help of https://wordpress.stackexchange.com/a/134524, I have the following:

add_filter( 'wp_headers', 'add_meta_to_header' );
function add_meta_to_header($headers) { 
    if ( is_page('Page title') ) {
        $headers['X-UA-Compatible'] = 'IE=edge,chrome=1';
    }
    return $headers;
}

My problem is I don't know what the syntax should be to add multiple meta tags to the header. For example I would like to add: <meta name='twitter:card' content='summary_large_image'/>. How should I include this inside the if statement?

Should that then be something like: headers['meta name, content'] = 'twitter:card, summary_large_image';?

1 Answer 1

1

HTTP headers are different than the HTML head. The meta tag you're looking to add (for the Twitter card) is actually a meta tag that gets place in the HTML head.

So to achieve exactly what you're looking to do from a PHP "functions" file, you'd want to hook into wp_head instead. Like this:

add_action('wp_head', function(){
    echo '<meta name="twitter:card" content="summary_large_image" />';
});

You can piggyback on a single hook to add as many meta tags as you need (since I see you're declaring the large summary size for Twitter, you'll probably want to tell it which image to use as well. You can do it like this:

add_action('wp_head', function(){
    echo '<meta name="twitter:card" content="summary_large_image" />';
    echo '<meta name="twitter:image" content="' . get_the_post_thumbnail_url() . '" />'; //The post thumbnail is the featured image– you could change this to a different image if desired
    echo '<meta name="twitter:creator" content="@yourtwitterusername" />'; //You can add the Twitter username of the author here (by hardcoding or even pull from the author's profile)
});

Think of the WordPress actions (or "hooks") as points when things happen– so the above code just tells WordPress: "hey, when you trigger the wp_head action, run this code as well".

Here is a list of all (or most) of the WP actions. I use this list all the time, so it's worth a bookmark.

Remember with filters you need to return, but with actions you just do what you want to happen at that point (which is why we are just echoing here).

Sidenote: I know the is_page() function accepts strings, but using the page title here can be fragile in case the title ever gets changed. Consider using the post ID there instead– so like is_page(123)

Hope that helps!

1
  • 1
    Thanks! That worked perfectly!
    – Nick
    Feb 27, 2021 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.