• I want to create a shortcode of myself that outputs “blocks”.

    Level 1: Setting a pure text

    I know how to do a simple shortcode. Let’s take this example.

    add_shortcode( 'greet', 'myNiceShortCode' );
    function myNiceShortCode( array $attributes )
    {
        // Process attributes
        $result = "Hello, world!";
        return $result;
    }

    If I set then [greet volume="loud"] I see Hello, world! in its place.

    Level 2: Outputting HTML

    I see I can output HTML there:

        $result = "<h2>Hello, world!</h2>";

    I can see the Hello, world! as an <h2> in the page or post.

    Level 3: My Question: How can I now output “full blocks”?

    Now I want something more advanced:

    I want the shortcode to output “full blocks” the same than those I could add manually. Say I want to add a full gallery block with photos being:

    $data = [
        [
            // ????? What other things?
            "image" => ???? whatever to get "image-1.jpg" from the gallery,
        ],
        [
            // ????? What other things?
            "url" => ???? whatever to get "image-2.jpg" from the gallery,
        ],
    ];
    
    $result = ?????? function of $data;

    I mean: I know I want those 2 photos. I don’t want to spit “pure html” as then I loose all the magic of working with the block system (responsiveness, using the theme defaults, etc.) so I want just to spit out the gallery “as if I set it manually”, but all automagically outputted from my short-code.

    I don’t want to print <div><img ...><img ...></div> but the gallery block itself.

    How can I output “something” that means “here this is not pure HTML, this is a block” to the rendering loop?

    • This topic was modified 1 year, 1 month ago by xmontero.
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    If you look at the HTML source code of a gallery block, you’ll see it is literally a series of image blocks. The magic you are after happens within the editor. If you moved the block content to a shortcode, you divorce it from normal editor content and thus the magic is gone.

    There is a built-in [gallery] shortcode, but I think you’d need to use the classic editor for its “magic” to work. This magic is an exception to the rule that shortcodes are not meant to be interactive. You’re supposed to know what attributes are needed and you provide them, there’s no magic UI to help you define the correct attribute values.

Viewing 1 replies (of 1 total)
  • The topic ‘How to create blocks from shortcodes?’ is closed to new replies.