加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何将变量传递给动作钩子函数?

发布时间:2020-12-13 17:43:02 所属栏目:PHP教程 来源:网络整理
导读:我有一个函数将初始化我的WordPress主题中的图像滑块,但是我无法将 PHP变量传递给它.这是代码: function slideshowSettings ($pause_time) {$code = "scriptjQuery(function(){ jQuery('#camera_wrap_3').camera({ height: '40%',thumbnails: true,time: ".
我有一个函数将初始化我的WordPress主题中的图像滑块,但是我无法将 PHP变量传递给它.这是代码:

function slideshowSettings ($pause_time) {
$code = "<script>
jQuery(function(){
    jQuery('#camera_wrap_3').camera({
        height: '40%',thumbnails: true,time: ".$pause_time.",fx: '".$transition_effect."',transPeriod: ".$transition_speed.",autoAdvance: ".$auto_advance.",minHeight: '50px',mobileNavHover: false,imagePath: '".get_template_directory_uri()."/images/'
    });
});
</script>";

echo $code;
}
add_action('wp_head','slideshowSettings');

变量分配在函数上方,但我从函数得到的输出如下所示:

<script>
jQuery(function(){

    jQuery('#camera_wrap_3').camera({
        height: '40%',time:,fx: '',transPeriod:,autoAdvance:,imagePath: 'http://www.brainbuzzmedia.com/themes/simplybusiness/wp-content/themes/simplybusiness/images/'
    });
});
</script>

我怎样才能传递这些变量?

解决方法

你不能为wp_head添加参数,因为当do_action(‘wp_head’)时,没有任何参数传递给你的钩子函数;由wp_head()函数调用. add_action()的参数是

>挂钩的动作,在你的情况下“wp_head”
>您要执行的功能,在您的情况下“幻灯片设置”
>执行的优先级,默认值为10
>函数接受的参数数量(但必须通过do_action传递)

如果你需要能够将钩子函数外部的这些值传递给wp_head,我会使用apply_filters来修改一个值:

function slideshowSettings(){
    // set up defaults
    $settings = array('pause_time'=>10,'other'=>999);
    $random_text = "foo";

    // apply filters
    $settings = apply_filters('slideshow_settings',$settings,$random_text);

    // set array key/values to variables
    extract( $settings );

    // will echo 1000 because value was updated by filter
    echo $pause_time;

    // will echo "foobar" because key was added/updated by filter
    echo $random_text; 

    // ... more code
}
add_action( 'wp_head','slideshowSettings' );

function customSettings($settings,$random_text){
    // get your custom settings and update array
    $settings['pause_time'] = 1000;
    $settings['random_text'] = $random_text . "bar";
    return $settings;
}
// add function to filter,priority 10,2 arguments ($settings array,$random_text string)
add_filter( 'slideshow_settings','customSettings',10,2 );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读