Ние създаваме уебсайтове за теб и твоят бизнес. За информация и запитвания: +359 876 700 417

How to Add Open Graph Meta Tags in WordPress

04.03.2020

How to Add Open Graph Meta Tags in WordPress

If you want to add Open Graph Meta Tags on your WordPress website, you can manually add this functionality to your WordPress theme.

This small code snippet, will help you to add Open Graph Meta Tags in your WordPress theme.

/**
 * Add Open Graph Meta Tags
 */

function meta_og() {
    global $post;

    if ( is_single() ) {
        if( has_post_thumbnail( $post->ID ) ) {
            $img_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
        } 
        $excerpt = strip_tags( $post->post_content );
        $excerpt_more = '';
        if ( strlen($excerpt ) > 155) {
            $excerpt = substr( $excerpt,0,155 );
            $excerpt_more = ' ...';
        }
        $excerpt = str_replace( '"', '', $excerpt );
        $excerpt = str_replace( "'", '', $excerpt );
        $excerptwords = preg_split( '/[\n\r\t ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY );
        array_pop( $excerptwords );
        $excerpt = implode( ' ', $excerptwords ) . $excerpt_more;
        ?>
<meta name="author" content="Your Name">
<meta name="description" content="<?php echo $excerpt; ?>">
<meta property="og:title" content="<?php echo the_title(); ?>">
<meta property="og:description" content="<?php echo $excerpt; ?>">
<meta property="og:type" content="article">
<meta property="og:url" content="<?php echo the_permalink(); ?>">
<meta property="og:site_name" content="Your Site Name">
<meta property="og:image" content="<?php echo $img_src[0]; ?>">
<?php
    } else {
        return;
    }
}
add_action('wp_head', 'meta_og', 5);

To add this functionality manually, you will need to copy and paste this code snippet in to your functions.php file of your WordPress child theme.

IMPORTANT: Aways use a child theme in WordPress!

English
Контакти
гр. София
+359 876 700 417
Cart