Adding thumbnails to Generateblocks Local Pattern Library

tdrayson

I was building a website for a client and we are making heavy use of the GenerateBlocks Local Pattern library feature.

However, something that annoyed me was not being able to see the lovely featured image I set. This is used for the block preview when looking at the actual pattern library in the editor.

I went searching for a way to modify the main list to show the featured image there for quick and easy reference when searching back through my local blocks.

generateblocks pattern library
Credit to Misha Rudrastyh. This is a fork of his code that I modified to work with the GenerateBlocks Pattern Library

Snippet

Add this to your functions.php or code snippet plugin

PHP

        <?php

// This action hook allows to add a new empty column
add_filter("manage_gblocks_templates_posts_columns","tct_featured_image_column");

function tct_featured_image_column($cols)
{
    $cols =
        array_slice($cols, 0, 1, true) + [
            "featured_image" => "Featured Image",
        ] + // our new column
        array_slice($cols, 1, null, true);

    return $cols;
}

// This hook fills our column with data
add_action("manage_gblocks_templates_posts_custom_column","tct_render_the_column",10,2);

function tct_render_the_column($column_name, $post_id)
{
    if ("featured_image" === $column_name) {
        if (has_post_thumbnail($post_id)) {

            $id = get_post_thumbnail_id($post_id);
            $url = esc_url(wp_get_attachment_image_url($id, "medium"));
            ?><img data-id="<?php echo $id; ?>" src="<?php echo $url; ?>" /><?php
        }
        // This adds some styling for the size of the thumbnail
        echo "<style>.post-type-gblocks_templates #featured_image{width:150px;} .post-type-gblocks_templates td.featured_image.column-featured_image img{max-width: 100%;height: auto;}</style>";
    }
}

      
Copy

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

Newsletter

🔒I won't send you spam, I promise