Wordpress:使用插件选项来修改jquery

时间:2013-02-19 16:09:20

标签: wordpress plugins

我正在尝试添加插件选项以更新jquery,但不知道如何做到这一点。我正在使用wp_enqueue_script()添加jquery,因此它不允许将php函数(get_option())添加到jquery代码中。请帮我解决这个问题。

Jquery代码:

jQuery(document).ready(function(){

    $cnt = 0;

    jQuery('#add-photo-button').click(function(){

    if($cnt == 3){ // where 3 should replaced with plugin option function/varible
        jQuery('#add-photo-button').prop('disabled', true);
        jQuery('#add-photo-button').addClass('disabled');
    }
    $cnt++;
        var current_count = jQuery('input[type="file"]').length;
        //var next_count = current_count + 1;

        jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');    

    });  

});

1 个答案:

答案 0 :(得分:1)

请参阅wp_localize_script()功能。

您必须将脚本入队,然后将要在JavaScript中引用的数据本地化(或者更确切地说:将数据作为内联JavaScript传递),最后更新脚本以引用新定位的全局对象。请参阅下面的示例。


实施例

1-将您的脚本排入插件,然后使用wp_localize_script()“本地化”变量数据。确保对两个函数调用都使用相同的句柄。

<?php

// !! Edit the variables below to suit your plugin

$add_photo_button_handle = 'some_handle';
$add_photo_button_js = plugins_url( '/add_photo_button.js', __FILE__ );

$photo_num = get_option( 'add_photo_button_cnt' ); // Here you fetch the option data.

// Enqueue your script
wp_enqueue_script( $add_photo_button_handle, $add_photo_button_js );

// Set the data you want to pass to your script here
$data = array( 'photo_button_cnt' => $photo_num );

// Localize the script, the 'photo_button_cnt' value will now be accessible as a property in the global 'add_photo_button' object.
wp_localize_script( $add_photo_button_handle, 'add_photo_button', $data );
?>

2-更改脚本以引用本地化对象

<script type="text/javascript">
jQuery(document).ready(function(){

    $cnt = 0;

    jQuery('#add-photo-button').click(function(){

    //============================================
    // See how we access the localized object.
    //============================================

    if($cnt == add_photo_button.photo_button_cnt ){ 
        jQuery('#add-photo-button').prop('disabled', true);
        jQuery('#add-photo-button').addClass('disabled');
    }
    $cnt++;
        var current_count = jQuery('input[type="file"]').length;
        //var next_count = current_count + 1;

        jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');    

    });  
});
</script>