'Wordpress: inserting author image/avatar as og:image in head
In a post template I'm using a little code to show the author's image/avatar instead of a featured image.
<?php if ( $logo = get_avatar( get_the_author_meta( 'user_email' ), 200 ) ) : echo $logo; ?>
all well.. the author's logo is there But now, as I finishing the project, I would like to add 'og:image' metas in the I hoped to use a variation of this code in the function.php, but that does not work at all.
Now I have this:
add_action('wp_head', 'add_meta_tags',2);
function add_meta_tags(){
global $post;
$author_id = get_post_field('post_author' , $post->ID);
$ogimg = get_avatar_url($author_id->ID, array("size"=>400 )) ;
if( is_single() ) {
echo '<meta property="og:image" content="'. $ogimg .'" />';
}
}
$author_id gives the ID of the author, but I don't get the avatar of the author.
Solution 1:[1]
Couldn't figure out how to use the get_avatar_url
function, but found a workaround by extracting the src
value from the couple img
tag like this:
add_action('wp_head', 'add_meta_tags',1);
function add_meta_tags() {
global $post;
$author_id = get_post_field('post_author' , $post->ID);
$rawimg = get_avatar($author_id, 800) ;
$doc = new DOMDocument();
$doc->loadHTML($rawimg);
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
$ogimg = $tag->getAttribute('src');
echo '<meta property="og:image" content="'.$ogimg .'" />';
echo '<meta name="twitter:image" content="'. $ogimg .'" />';
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tyler2P |