Allow HTML in WooCommerce Product Excerpt

WooCommerce’s Gutenberg blocks for product excerpts do not allow HTML tags by default, even though the product description in the backend can include HTML. To overcome this limitation, I created a custom block for the product excerpt. Here’s the process I followed and the necessary code.

Step-by-Step Solution

  1. Enqueue Block Editor Assets: Add the following PHP code to your theme’s functions.php file to enqueue the block editor script.
function mytheme_enqueue_block_editor_assets() {
    // Enqueue block editor script
    wp_enqueue_script(
        'mytheme-block-editor-js', // Handle
        get_theme_file_uri('/build/index.js'), // Path to the JS file
        array( 'wp-blocks', 'wp-i18n', 'wp-element' ), // Dependencies
        filemtime(get_theme_file_path('/build/index.js')) // Version: file modification time for cache busting
    );
}

add_action('enqueue_block_editor_assets', 'mytheme_enqueue_block_editor_assets');
  1. Render the Custom Block: Define the PHP function to render the custom block on the front end. Add this code to your functions.php file.
function render_my_post_excerpt_block($attributes, $content) {
	$post_id = $attributes['postId'];
	$post = get_post($post_id);
	$excerpt = apply_filters('the_excerpt', $post->post_excerpt);

	return '<div>' . $excerpt . '</div>';
}

register_block_type('my-plugin/my-post-excerpt', [
	'render_callback' => 'render_my_post_excerpt_block',
]);
  1. Create the Block Editor Script: Save the following JavaScript code in index.js within the build directory of your theme.
// Import dependencies
const { registerBlockType } = wp.blocks;
const { __ } = wp.i18n;
const { useSelect } = wp.data;
const { useEffect, useState } = wp.element;

registerBlockType('my-plugin/my-post-excerpt', {
  title: __('Product Excerpt', 'my-plugin'),
  icon: 'smiley',
  category: 'common',
  usesContext: ['postId'],
  attributes: {
    excerpt: {
      type: 'string',
      source: 'html',
      selector: 'p'
    }
  },
  edit: ({ attributes, setAttributes, context }) => {
    const { postId } = context;
    const { excerpt } = attributes;
    const [badges, setBadges] = useState([]);
    
    useEffect(() => {
      let isMounted = true;
      if (postId) {
        wp.data.resolveSelect('core').getEntityRecord('postType', 'product', postId).then(product => {
          if (product && product.excerpt && isMounted) {
            setAttributes({ excerpt: product.excerpt.rendered });
          }
        }).catch(error => {
          console.error('Error fetching product:', error);
        });

      }
      return () => {
        isMounted = false;
      };
    }, [postId]);

    return (
      <div>
        <div dangerouslySetInnerHTML={{ __html: excerpt || __('No excerpt', 'my-plugin') }} />
        <ul>
          {badges.map((badge, index) => (
            <li key={index}>{badge}</li>
          ))}
        </ul>
      </div>
    );
  },
  save: () => null // Render in PHP
});

By following these steps, you will be able to create a custom block that allows HTML in WooCommerce product excerpts. This custom block can be used to display excerpts with HTML tags on the front end, providing more flexibility in how product information is presented.

Leave a Comment

Your email address will not be published. Required fields are marked *