2

I need to create a column-system for Wordpress with shortcodes, which is not a problem, but I'm trying to make it with less code.

I have an array with the data needed, I loop through it, create a unique-named function and set it as shortcode-function. The third step is a mystery. How can I create a function from a variable.

Here's an example, how it should be done:

$data[] = "first";
$data[] = "second";
foreach($data as $key => $value) {
    function $value($atts,$content) {
        return '<div class="'.$value.'">'.$content.'</div>';
    }
    add_shortcode($value,$value);
}

However, it seems that it's not possible to make it work like that in PHP. Is there any way to make this work, as I would not want to write all the (identical) functions separated. I could make the shortcode something like [col first]text[/col] but the client wants to have different names for every one of them.

2 Answers 2

5

you can use the double dollar syntax to use the value of a variable as a variable identifier,

Example:

$variable = "test";
$$variable = "value of test"

echo $test; //or echo $$variable;

I have never tried but you way want to try:

foreach($data as $key => $value)
{
    function $$value($atts,$content)
    {
    }
    add_shortcode($value,$value);
}

or a function like create_function

if your using PHP 5.3 or greater then you can do something like so:

$$value = function()
{

}

which should work fine

Sign up to request clarification or add additional context in comments.

2 Comments

create function prefix with $ is still not allowed in PHP. And for lamda-style, is not exactly using the $value as function name, is rather to let PHP to decide an unique name
Yea i haven't tried the function name technique, as for the lambda style, that should work on 5.3
0

I'm not sure how WP invocates the functions, but if it uses call_user_func then you might cheat by using an object with virtual methods:

class fake_functions {
    function __call($name, $params) {
        return '<div class="'.$name.'">'.$params[1].'</div>';
    }
}

$obj = new fake_functions();
foreach ($data as $value) {
    add_shortcode($value, array($obj,$value));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.