How to display WooCommerce product long description in the head?

I want to get the long description of the WooCommerce product to display it in the head…

The following code works fine for the product short description:

<head>
    <meta name="description" content="<?php
    $excerpt = '';
    if (has_excerpt()) {
        $excerpt = wp_strip_all_tags(get_the_excerpt());
        echo $excerpt;
    }
?>"/>
</head>

But I want the long description to be displayed instead, so I made some changes to the code:

<head>
    <meta name="description" content="<?php
    $description = '';
    if (has_description()) {
        $description = wp_strip_all_tags(get_the_description());
        echo $description;
    }
?>"/>
</head>

Unfortunately, it doesn’t work at all.

How to display WooCommerce product long description in the head?

HTML

<head>
    <meta name="description" content="<?php
    $product = wc_get_product( get_the_ID() );
    if ( $product->has_description() ) {
        $description = wp_strip_all_tags( $product->get_description() );
        echo $description;
    }
    ?>"/>
</head>

Explanation:

  1. Retrieve the Product Object:
  • Use wc_get_product( get_the_ID() ) to get the product object based on the current post ID.
  1. Check for Description:
  • Use $product->has_description() to check if the product has a long description.
  1. Get and Display Description:
  • If the product has a description, use $product->get_description() to retrieve it.
  • Strip HTML tags using wp_strip_all_tags() to ensure a clean description.
  • Echo the description within the <meta> tag’s content attribute.

This code will effectively display the long description of the WooCommerce product in the head section of your page.