2

In the example below, $shortcodes is a multidimensional array with shortcode data.

foreach( $shortcodes as $shortcode ) {

    // Here we have the shortcode name, could be 'custom_person_john'.
    $shortcode_name = $shortcode['slug'];

    // Anonymous function should be referred to as 'custom_person_john'.
    $shortcode_name = function( $shortcode ) {

      // Build shortcode attributes.
      $atts = shortcode_atts( array(
        'name' => 'john',
        'type' => 'mammal'
      ), $atts );

      $markup = '<div class="'.$atts['name'].'">';
         $markup .= '<div>';
            // $shortcode should contain custom markup from the array.
            $markup .= $shortcode['html'];
         $markup .= '</div>';
      $markup .= '</div>';

      return $markup;

    };

    // Trying to register the shortcode
    add_shortcode( $shortcode['slug'], $shortcode_name( $shortcode ) );

};

So this is not working, but I can't grasps why. If I dump all the registered shortcodes, they don't show up in the list. Trying to load them simple echo's [custom_person_john]. I don't have errors either.

Edit: If anyone has other ideas on how to create them dynamically out of an array, feel free to suggest :)

5
  • What hook are you using to register the shortcodes? If you're just throwing this into functions.php I suggest maybe adding it into init to see if that helps. – Howdy_McGee Jul 31 '15 at 20:59
  • @Howdy_McGee Thanks for your help, unfortunately it's inside an init hook already. – piggypig Jul 31 '15 at 21:05
  • you overwrite $shortcode_name the second time you use this variable. changing the name will to go a step ahead but in the shortcode function, i think you will not have access to $shortcode['html'] so you have to do this on a other way – mmm Jul 31 '15 at 21:29
  • @mmm Thanks you're right, updated my answer. I have access to $shortcode inside the function. I dumped it by doing var_dump($shortcode), returns all the correct values. – piggypig Jul 31 '15 at 21:43
  • you have access because $shortcode_name( $shortcode ) construct a HTML string but add_shortcode need a function - from where come informations of $shortcodes ? you need to access theses informations inside the shortcode functions, I prepare a answer with a example – mmm Aug 1 '15 at 16:32
5

the shortcodes doesn't shop up in the liste because it's not a valid declaration with a valid function callback on the 2nd argument

try this to see what append :

// shortcode data

add_filter("shortcode_list", function ($shortcode_list) {
    $shortcode_list["slugA"] = array(
        "html" => "test html 1",
    );

    return $shortcode_list;
});

add_filter("shortcode_list", function ($shortcode_list) {
    $shortcode_list["slugB"] = array(
        "html" => "test <strong>html 2 - [slugA]</strong>",
    );

    return $shortcode_list;
});


// shortcodes declaration

add_action("init", function () {

    $shortcodes = apply_filters("shortcode_list", array());

    foreach (array_keys($shortcodes) as $shortcode_slug) {
        add_shortcode($shortcode_slug, "shortcode_callback");
    };

});


// callback function

function shortcode_callback($atts, $content = "", $tag) {

    // Build shortcode attributes.
    $atts = shortcode_atts( array(
        'name' => 'john',
        'type' => 'mammal'
    ), $atts);


    // shortcode data
    $shortcodes = apply_filters("shortcode_list", array());
    $shortcode = $shortcodes[$tag];


    // construct result of the shortcode

    $markup  = "";
    $markup .= '<div class="'.$atts['name'].'">';
        $markup .= '<div>';
            // $shortcode should contain custom markup from the array.
            $markup .= $shortcode['html'];
            //$markup .= do_shortcode($shortcode['html']); // to replace shortcodes in the "html" data


            $markup .= '<pre>';
            $markup .= print_r($atts, TRUE);
            $markup .= '</pre>';

        $markup .= '</div>';
    $markup .= '</div>';

    return $markup;

}
2
  • Awesome! Let me have a good look at this and get back to you. Love the fact we're still pulling data from the array. – piggypig Aug 2 '15 at 18:57
  • Digg it, did some tweaks for my situation but got it working with your solution :) – piggypig Aug 3 '15 at 13:04
1

Few months ago I was working on a similar thing where I had to generate short codes dynamically. But I took a different approach.

What I did was as following;

  1. I registered a short code and custom post type for which I had to use that dynamic short code.

  2. Then added attribute for post name (slug) in that short code to get data dynamically to display on front end.

Here is sample code for how you can do that;

// Shortcode to display html in frontend
// [dynamic_shortcode name='post-slug']
function dynamic_shortcode( $atts ) {

    // Get Attributes
    extract( shortcode_atts(
            array(
                'name' => ''   // DEFAULT SLUG SET TO EMPTY
            ), $atts )
    );

    // WP_Query arguments
    $args = array (
        'name'              =>  $name,     // GET POST BY SLUG  // IGNORE IF YOU ARE GETTING ERROR ON THIS LINE IN YOUR EDITOR
        'post_type'         => 'your-post-type', // YOUR POST TYPE
        'post_status'       => 'publish', // POST STATUS
    );


    // The Query
    $query = new WP_Query( $args );

    // The Loop
    if ( $query->have_posts() && $name != '' ) {
        while ( $query->have_posts() ) {
            $query->the_post();

            $html_src = get_post_meta( get_the_ID() , 'html_src' , true);  // GET HTML SOURCE FROM YOUR POST META

            if ( $html_src) {
                return $html_src; // RETURN HTML TO DISPLAY ON FRONT END
            }

        }
    } else {
        // no posts found
        return '<p style="color: red" >Sorry You have set no html for this slug...</p>';

    }


// Restore original Post Data
    wp_reset_postdata();
}
add_shortcode( 'dynamic_shortcode', 'dynamic_shortcode' );

Hope this might work for you as well.

1
  • Good thinking, I like the approach. I'm going to see if I can get a similar approach to work in my project. I would upvote, but can't yet :) – piggypig Aug 2 '15 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.