0

I would like to use a php variable to input the value as the shortcode name for wordpress.

Basically I have an option where people can create an options and give it a shortcode name.

Something like the following:

Is this possible?

$shortcode_name = "name_here";
function $shortcode_name ($atts) {
// code here
}
add_shortcode ($shortcode_name , $shortcode_name);

Thanks

2

1 Answer 1

3

In PHP 5.3+ you have closures.

$shortcode_name = 'awesome';
${"{$shortcode_name}_fn"} = function($atts) {
  print('Awesome shortcode');
};
add_shortcode($shortcode_name, ${"{$shortcode_name}_fn"});

You can also have variable variable names, in this case, the variable that contains the function is named: awesome_fn.

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

5 Comments

Thanks for this. I get an error though - "Parse error: syntax error, unexpected '_fn' " - any ideas?
No problem. Hey check the updated answer, the variable variable name is now an interpolated string and the second argument for add_shortcode is the callable (a function in this case)
Yeah this works well :D The only thing is that I have this in a loop where for each id in the post type - to generate a shortcode with the options they give. When I do this, it works perfectly for the first. I then add another and it overights the first. I dont think this is your code, but thought I would check?
Try using an asociative array of functions. Or maybe check no id is repeated
no idea what that is - but I think thats another answer - thanks for the help :D

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.