Categories
Advanced

Add HTML to WordPress List Table

Lets try to add some HTML code in the product name column in the Woocommerce product table. 

We want the end result to be:

Just filtering the title is not enough. Let’s take a look at this example:

add_action('current_screen', function($screen){
   if($screen->id == "edit-product"){
      add_filter("the_title", function($title, $id){ 
         if(has_term('music', 'product_cat',$id)){
	    return $title . "<i style='color: green';> music<i/>";
	}
	 return $title;
      }, 10 ,2);
});

The end result will look like:

Because Woocommerce is escaping the HTML. There is no direct filter for this. You have to use the WordPress esc_html filter:

add_action('current_screen', function($screen){
   if($screen->id == "edit-product"){
      add_filter("the_title", function($title, $id){
         if(has_term('music', 'product_cat',$id)){
	     return $title . "<i style='color: green';> music<i/>";
	 }
	 return $title;
      }, 10 ,2);

      add_filter("esc_html", function($safe, $unsafe){
         if(has_term('music', 'product_cat')){
             return $unsafe;
	 }
	 return $safe;
      }, 10 ,2);
   }
});

If this is a good enough solution for you, awesome! But I will also include an alternate approach.

This approach makes more sense you will not doing anything that could potentially collide with other plugins.

We will use the filter post_class hook. to add our own custom class.

add_action('current_screen', function($screen){
   if($screen->id == "edit-product"){
      add_filter("post_class", function($classes,$class){
         $id = the_ID();
         if(has_term('music', 'product_cat',$id)){
               $classes[] = "music";
	 }
	 return $classes;
      }, 10 ,2);
   }
});

This adds the class ‘music’ to all products in the music category.

To finish we will use the jQuery append method to insert our HTML.

document.addEventListener("DOMContentLoaded", function() {
   jQuery("tr.music td.name a.row-title").append("<i style='color: green;'> music</i>");	
});

That’s it!

The final code might look like:

add_action('current_screen', function($screen){
   if($screen->id == "edit-product"){
      add_filter("post_class", function($classes,$class){
         $id = the_ID();
         if(has_term('music', 'product_cat',$id)){
               $classes[] = "music";
	 }
	 return $classes;
      }, 10 ,2);
      ?>
<script>
    document.addEventListener("DOMContentLoaded", function() {
      jQuery("tr.music td.name a.row-title").append("<i style='color: green;'> music</i>");
    });

</script>
    <?php
    }
}); 

But you may want to separate the javascript from the PHP. Good luck and happy coding!

Leave a Reply

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