0

I asked Yoast SEO support about this as I'm using their plugin, but they don't have this feature:

Instead of having to set a meta description for each WooCommerce product I sell, I'd like to set it automatically to the description of the product's category (or primary category, if it has several).

I found some code to retrieve the product's category description (https://stackoverflow.com/questions/19249756/how-to-display-woocommerce-category-description), but I don't know how to set it as this product's meta description.

Can you please help? :)

Thank you very much.

1 Answer 1

1

Use the wpseo_metadesc filter:

function wpse_406559_product_meta_description_from_category( $description ) {
    if ( ! is_singular( 'product' ) || $description ) {
        // Bail early if not single product, or custom meta description is already set
        return $description;
    }

    $product_cats = get_the_terms( get_queried_object_id(), 'product_cat' );

    // Get first product category
    $product_cat = is_array( $product_cats ) ? current( $product_cats ) : null;

    if ( $product_cat ) {
        // Get Yoast SEO term meta
        $meta = get_option( 'wpseo_taxonomy_meta' );

        // Try to get Yoast SEO meta description for this product category
        $description = $meta['product_cat'][ $product_cat->term_id ]['wpseo_desc'] ?? null;

        if ( ! $description ) {
            // Fallback to default product category description field
            $description = wp_strip_all_tags( $product_cat->description );
        }
    }

    return $description;
}

add_filter( 'wpseo_metadesc', 'wpse_406559_product_meta_description_from_category' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.