我创建了一个插件,它从短代码获取属性并将它们传递给java脚本,它工作正常,但我认为它编写错误。请告诉我如何以正确的方式编写代码。
短代码
[yoolek-googlemap-v1 lat =“51”lng =“17”zoom =“15”]
public function __construct()
{
add_shortcode( $this->tag, array($this, 'run_yoolek' ) );
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
}
public function run_yoolek($atts)
{
wp_enqueue_style( $this->tag.'-css',plugin_dir_url( __FILE__ ).'style.css');
wp_enqueue_script($this->tag.'-google-maps', 'https://...');
wp_enqueue_script($this->tag.'-js', plugin_dir_url( __FILE__ ).'script.js');
$atts = shortcode_atts(array(
'lat' => '51',
'lng' => '0',
'zoom' => '9',
), $atts, $this->tag );
$this->admin_lat = $atts['lat'];
$this->admin_lng = $atts['lng'];
$this->admin_zoom = $atts['zoom'];
$params = array(
'lat' => $this->admin_lat,
'lng' => $this->admin_lng,
'zoom' => $this->admin_zoom,
);
wp_localize_script($this->tag.'-js', 'MyScriptParams', $params );
ob_start();
echo $this->admin_lat.",";
echo $this->admin_lng.",";
echo $this->admin_zoom;
echo "<div id='".$this->tag."-map-canvas'></div>";
return ob_get_clean();
}
在之前的版本中,我将所有“排队”放在
中add_action('wp_enqueue_scripts',array($ this,'cssjs'));
在函数__construct()中,但是我无法将vars从run_yoolek传递给wp_localize_script。 这是我的工作代码:
public function __construct()
{
add_action( 'wp_enqueue_scripts', array( $this, 'cssjs' ) );
add_shortcode( $this->tag, array($this, 'run_yoolek' ) );
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
}
public function run_yoolek($atts)
{
$atts = shortcode_atts(
array(
'lat' => '51',
'lng' => '0',
'zoom' => '9',
), $atts, $this->tag );
$this->admin_lat = $atts['lat'];
$this->admin_lng = $atts['lng'];
$this->admin_zoom = $atts['zoom'];
ob_start();
echo $this->admin_lat.",";
echo $this->admin_lng.",";
echo $this->admin_zoom;
echo "<div id='".$this->tag."-map-canvas'></div>";
return ob_get_clean();
}
/*ADMIN,PLUGIN HOOKS AND FUNCTIONS*/
public function cssjs() {
wp_enqueue_style( $this->tag.'-css',plugin_dir_url( __FILE__ ).'style.css');
wp_enqueue_script($this->tag.'-google-maps', 'https://...');
wp_enqueue_script($this->tag.'-js', plugin_dir_url( __FILE__ ).'script.js');
$params = array(
'lat' => $this->admin_lat,
'lng' => $this->admin_lng,
'zoom' => $this->admin_zoom,
);
wp_localize_script($this->tag.'-js', 'MyScriptParams', $params );
}