我创建了一个短代码,它自动生成具有给定数组键和值的短代码。函数名称不会动态生成。
注意:数组KEY = ShortcodeName和Value = Wordpress Option字段。
add_shortcode("auto_gen", "auto_gen");
function auto_gen() {
$a = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
foreach ($a as $k => $v) {
if(has_shortcode($k)) {
echo "<br>Found: ". $k;
} else {
add_shortcode($k, $k. "_init");
function $k. "_init"() {
return get_option[$v, ''];
}
}
add_shortcode();
echo $k ." -> ". $v. "<br />";
}
}
有任何可能的方法来做到这一点。
注意:
这里,get_address数组键是一个短代码。它通过循环时动态生成。 get_address是可变的。如果我用get_user_address更改get_address,则生成get_user_address generate。 “get_address”,“get_phone”在END LEVEL处是可变的。
开发人员还生成短代码来访问使用get_options创建的wp_options,只需按下数组中的元素即可。例如“shortcode_name”=&gt; “OPTION_NAME”
答案 0 :(得分:1)
函数add_shortcode
包含third parameter,其中包含当前的短代码,因此可以多次使用相同的回调:
$all = array( 'address', 'phone', 'fax', 'email', 'hrs_mon', 'hrs_sat' );
foreach ( $all as $s )
add_shortcode( "get_$s", 'general_shortcode' );
function general_shortcode( $atts, $content = '', $shortcode = '' )
{
switch( $shortcode )
{
case 'get_address':
$return = 'ADDRESS';
break;
case 'get_phone':
$return = 'PHONE';
break;
default:
$return = 'OTHER SHORTCODES';
break;
}
return $return;
}
另一种可能性:
Class AllShortcodes{
private $all = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
public function __construct() {
foreach ( $this->all as $key => $value )
add_shortcode( $key, array( $this, 'general_shortcode' ) );
}
public function general_shortcode( $atts, $content = '', $shortcode = '' )
{
return $this->all[$shortcode];
}
}
$myShortcodes = new AllShortcodes;
答案 1 :(得分:0)
请尝试以下代码:
add_shortcode("auto_gen", "auto_gen");
function auto_gen() {
$a = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
foreach ($a as $k => $v) {
if(has_shortcode($v,$k)) {
echo "<br>Found: ". $k;
} else {
add_shortcode($k, $k."_init");
$func =$k."_init";
$func($v);
}
echo $k ." -> ". $v. "<br />";
}
}
function get_address_init ($v) {
return get_option($v, '');
}
function get_phone_init ($v) {
return get_option($v, '');
}
function get_fax_init ($v) {
return get_option($v, '');
}
function get_email_init ($v) {
return get_option($v, '');
}
function get_hrs_mon_init ($v) {
return get_option($v, '');
}
function get_hrs_sat_init ($v) {
return get_option($v, '');
}