Change meta tags programatically

Is there a way to change the meta tags not in the head but in a template file through code?

I would like to change the meta tags

meta property="og:title" content="title" / 
meta property="og:description" content="description" / 
meta property="og:image" content="thumbnail_image" /

They are automatically set when calling the facebook SDK. Is there a way to change these tags in my code (not in header.php)?

I've tried to do this in my child template (content-share.php):

?php
   add_action( 'wp_head', 'add_meta_tags' , 10 );
?

And then in functions.php of my theme I have:

function add_meta_tags() {
    echo 'meta property="og:title" content="Test"' . "\n";
}

But that doesn't do anything. Also when I add a die; in the function nothing changes. It's like my function isn't called.

How can I solve this?

Topic post-meta functions facebook actions wp-head Wordpress

Category Web


I think you need to do the add_action( 'wp_head', 'add_meta_tags' , 10 ); in your functions.php instead of the template to get the function called. And it adds it then everywhere where you have wp_head(). So if you want to only call it content-share.php you need some conditioning logic like

if (is_page_template('page-templates/content-share.php')) {
  add_action( 'wp_head', 'add_meta_tags' , 10 );
}

Of course change the page-templates folder to be what ever the folder is where you have the template in your theme folder.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.