在我的主要plugin.php文件中,我根据自定义帖子类型ID从wp_postmeta数据库获取/获取文件
$ wpsv_save_metadata = get_post_meta($ post-> ID);
然后根据此ID,我可以使用以下命令获取wpsv_video_width,wpsv_video_height等值:
$ wpsv_save_metadata [ 'wpsv_video_width'] [0];
但是我无法将该值(wpsv_video_width,wpsv_video_height)传递给我的javascript文件。
如何将值传递给我的javascript文件,以便我可以动态更改宽度(win.style.width)和height(win.style.height):
function yScrollHandler(){
var win = document.getElementById("styleku-video-container");
if((window.pageYOffset + window.innerHeight) >= 1000){
//win.style.webkitTransition = "right 0.7s ease-in-out 0s";
win.style.transition = "right 0.7s ease-in-out 0s";
win.style.right = "0px";
win.style.position = "fixed";
win.style.bottom = "0px";
win.style.padding = "10px";
win.style.width = "400px";
win.style.height = "295px";
} else {
win.removeAttribute("style");
}
}
window.onscroll = yScrollHandler;
请帮忙。谢谢。
答案 0 :(得分:0)
首先创建javascript变量,然后附加你的js文件,在你的js文件中使用那个js全局变量。如下。
<?php
$width = $wpsv_save_metadata['wpsv_video_width'][0];
$height = $wpsv_save_metadata['wpsv_video_height'][0];
?>
<script>
var width = <?php echo $width; ?> // use width variable in your js file
var height = <?php echo $height; ?> // use height variable in your js file
</script>
<script src="your js file path"></script>
答案 1 :(得分:0)
我建议您使用wp_localize_script。
has a neat example与您的问题相似。
答案 2 :(得分:0)
如果从单独的站点加载js,则为备用方法。
如果您没有将js加载到主题中,那么您就无法使用wp_localize_script,因此您需要一种替代方法来包含根文件夹中的 wp-load.php
文件WordPress的。在插件文件夹中创建两个文件:
<强> JS-template.js 强>
/wp-content/plugins/your-plugin/js/js-template.js
var mymessage = '[[my-message]]'; // in php use str_replace() to replace this
console.log('mymessage', mymessage);
获取-js.php 强>
/wp-content/plugins/your-plugin/js/get-js.php
<?php
// Drop this into your plugin folder and access it directly
// https://example.com/wp-content/plugins/your-plugin/js/get-js.php
// It will load a js file named js-template.js
/**
* Finds the wp root folder.
* Navigate through the parent directories to find the wp-load.php file.
* Stop after reaching 10 directories up, so we don't run into a
* recursion error.
*
* @param $path directory to look into
* @param $max_recursive the max number of parent directories to navigate into
*
* @return string|boolean Either a string of the path or false if the max recursion is reached
*/
function find_parent_wp_root($path = './', $max_recursive = 10) {
if( $max_recursive === 0 )
return false;
if( file_exists( realpath($path) . '/wp-load.php' ) ) {
return realpath($path) . '/';
} else {
return find_parent_wp_root($path . '../', $max_recursive-1);
}
}
$www_root = find_parent_wp_root($path = './');
if( ! $www_root ) {
http_response_code(404);
} else {
define('WP_USE_THEMES', false);
require( $www_root . 'wp-blog-header.php');
$js = file_get_contents('js-template.js');
$js = str_replace('[[my-message]]', 'some new value', $js);
header('Content-Type: application/javascript');
echo $js;
}