Method of adding open graph meta tag without plug-ins in WordPress

Jiang saw that many META parts of the website header have open graph meta tags, but my theme does not come with my own. If I use plug-ins, it can certainly be achieved, but it is not my original intention, because I do not like to install too many plug-ins. I am thinking about whether it can be achieved without plug-ins. Here I collate the methods of adding open graphs to WordPress shared and modified by foreign websites, First sort it out, and then modify it on the basis of changes.

 //Lets add Open Graph Meta Info add_action('wp_head', 'fc_opengraph'); function fc_opengraph() { if( is_single() || is_page() ) { $post_id = get_queried_object_id(); $url = get_permalink($post_id); $title = get_the_title($post_id); $site_name = get_bloginfo('name'); $description = wp_trim_words( get_post_field('post_content', $post_id), 25 ); $image = get_the_post_thumbnail_url($post_id); if( ! empty( get_post_meta($post_id, 'og_image', true) ) )  {	 $image = get_post_meta($post_id, 'og_image', true); } else { $image = 'set your image URl here'; } $locale = get_locale(); echo '<meta name="description" content="Put your website description here">'; echo '<meta property="og:locale" content="' .  esc_attr($locale) . ' " />'; echo '<meta property="og:type" content="article" />'; echo '<meta property="og:title" content="' .  esc_attr($title) . ' | ' .  esc_attr($site_name) . ' " />'; echo '<meta property="og:description" content="' .  esc_attr($description) . ' " />'; echo '<meta property="og:url" content="' .  esc_url($url) . ' " />'; echo '<meta property="og:site_name" content="' .  esc_attr($site_name) . ' " />'; if($image) echo '<meta property="og:image" content="' . esc_url($image) . '" />'; // Twitter Card echo '<meta name="twitter:card" content="summary" />'; echo '<meta name="twitter:site" content="@yourtwitterhandle" />'; echo '<meta name="twitter:creator" content="@yourtwitterhandle" />'; echo '<meta name="twitter:title" content="' .  esc_attr($title) . ' | ' .  esc_attr($site_name) . ' " />'; echo '<meta name="twitter:description" content="' .  esc_attr($description) . ' " />'; echo '<meta name="twitter:image" content="' .  esc_attr($image) . ' " />'; } }

Modify as needed.

Reference from: https://medium.com/ @harshcrop/wordpress-og-tags-scrtip-no-need-to-use-third-party-plugins-bb82731cd4d0

Vote for you

Source: Lao Jiang Tribe » Method of adding open graph meta tag without plug-ins in WordPress |Welcome to share (public account: Chiang's circle of friends)

Get new information from webmaster/add QQ group from the public account "Chiang Kai shek's circle of friends"【 one billion twelve million four hundred and twenty-three thousand two hundred and seventy-nine 】Get preferential promotion from merchants