未定义的常量WP_PLUGIN_URL

时间:2014-02-26 09:08:49

标签: javascript php wordpress plugins

我正在创建Wordpress插件,我开始使用一些js文件。为了在js文件中使用php,我使用php header("Content-type: text/javascript")并开始在底部插入其余的javascript代码。当我尝试使用WP_PLUGIN_URL时,它告诉我没有定义。如何以这种方式定义WP_PLUGIN_URL?

Myscript.js原来是myscript.php。

<?php 
header("Content-type: text/javascript");
$bigStarsPath =  WP_PLUGIN_URL.'/horoscope-plugin/js/icons/star.png';
$smallStarsPath = WP_PLUGIN_URL.'/horoscope-plugin/js/icons/small.png';
?>

/* JS Start Here*/
(function($) {
$.fn.jRating = function(op) {
var defaults = {
/** String vars **/
 bigStarsPath : '<?php echo $bigStarsPath; ?>', // path of the icon stars.png
 smallStarsPath : '<?php echo $smallStarsPath; ?>', // path of the icon small.png
 ...

插件索引页:

function myscript() {
wp_enqueue_script('jquery');
/*REGISTER ALL JS FOR SITE*/
wp_register_script('jRating', WP_PLUGIN_URL.'/horoscope-plugin/js/jRating.jquery.php');

/*REGISTER ALL CSS FOR SITE*/;
wp_register_style('stylesheet',WP_PLUGIN_URL.'/horoscope-plugin/css/style.css');

/*CALL ALL CSS AND JS SCRIPT*/
wp_enqueue_style('stylesheet');
wp_enqueue_script('jRating');   
}
add_action('wp_enqueue_scripts','myscript');

2 个答案:

答案 0 :(得分:1)

你可以这样做,

首先将此代码添加到主题的functions.php文件

function mycustomjs_init()
{
    wp_enqueue_script( 'mycustomjs', "JS_FILE_PATH");

    $bigStarsPath =  WP_PLUGIN_URL.'/horoscope-plugin/js/icons/star.png';
    $smallStarsPath = WP_PLUGIN_URL.'/horoscope-plugin/js/icons/small.png';

    wp_localize_script( 'mycustomjs', 'bigStarsPath', array('url' => $bigStarsPath));
    wp_localize_script( 'mycustomjs', 'smallStarsPath', array('url' => $smallStarsPath));
}
add_action( 'wp_print_scripts', 'mycustomjs_init' );

JS_FILE_PATH替换为您的js文件路径...

现在在js文件中,使用您定义的变量,例如bigStarsPath.url&amp; smallStarsPath.url ...

希望它有用......

答案 1 :(得分:0)