wp-block as a shortcode

In my last post I raved about the excellent plugin wp-blocks by Keir Whitaker and then went on to extend it a little.

Time to extend it a little further, this time by adding a shortcode.

Shortcodes are the handy square bracketed code snippets which conjure up more content and functionality direct from a page or post content.

The wp-blocks plugin is currently intended to work with the theme template files in PHP. Unfortunately (or fortunately?) PHP does not get parsed within the content areas. This does stop malicious code from being included, but it does limit things when you know what you’re doing.

The following code will give you a short code to work with which looks similar to the PHP code snippit you would include in your theme template file.

   * Gets the block data by 'name' and returns it for use in a content shortcode
   * Requires http://wordpress.org/extend/plugins/wp-blocks/
   * @param string $name
   * @return string
   * @author Iain Cuthbertson
  function get_wp_block_shortcode( $atts ) {
    extract( shortcode_atts( array(
      'name' => '',
    ), $atts ) );

    global $wpdb;
    $block_slug = trim($name);
    $data = (array)$wpdb->get_row("SELECT * FROM {$wpdb->prefix}wpb_content WHERE name = '{$name}' AND active = TRUE");  
    if($data) return get_wrapped_block_content($data);
  add_shortcode('get_wp_block', 'get_wp_block_shortcode');

Add that to your theme’s functions.php file and then you will be able to add blocks to your content with, for example:

[get_wp_block name="foo"]

One thought on “wp-block as a shortcode”

  1. I would just like to say thank you for your snippet, i always use wp-blocks and now i have the option to add to posts/pages you have just made an awesome plugin even better. Thanks Again,

    Hope all is well your end

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.