Javascript Wordpress-使用自定义post字段中的参数创建动态onclick重定向方法
老实说,我不是wordpress env的大师。但我必须解决一个问题。我的模板代码如下:Javascript Wordpress-使用自定义post字段中的参数创建动态onclick重定向方法,javascript,php,ajax,wordpress,Javascript,Php,Ajax,Wordpress,老实说,我不是wordpress env的大师。但我必须解决一个问题。我的模板代码如下: <div class="section-one"> <div class="section-one-container"> <h1><?php the_title(); ?></h1> <?php the_excerpt(); ?> <div class="link">
<div class="section-one">
<div class="section-one-container">
<h1><?php the_title(); ?></h1>
<?php the_excerpt(); ?>
<div class="link">
<a href="" target="_blank">Go to the presentation</a>
</div>
</div>
<?php if(has_post_thumbnail())
echo '<div class="image">';
the_post_thumbnail('full');
echo '</div>';
?>
</div>
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
$custom_field = get_post_meta($postid,"meta_key",true); //get the custom field
// Localize the script with new data
$data = array(
'some_value' => $custom_field
);
wp_localize_script( 'some_handle', '_object', $data );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
问题是,将自定义字段值传递到GoTour函数的正确方法是什么?如何使用wordpress字段值创建JS params对象?
如何将JS代码与PHP代码混合,例如:
const params = {
color: <?php the_field('color'); ?>,
label: <?php the_field('label'); ?>,
mode: <?php the_field('mode'); ?>
...
}
const参数={
颜色:,
标签:,
模式:
...
}
您似乎面临的主要问题是将php数据传递给JS文件。wp_localize函数正是针对这种情况而设计的。
在您的情况下,需要首先在functions.php中注册js文件,并按如下方式本地化变量:
<div class="section-one">
<div class="section-one-container">
<h1><?php the_title(); ?></h1>
<?php the_excerpt(); ?>
<div class="link">
<a href="" target="_blank">Go to the presentation</a>
</div>
</div>
<?php if(has_post_thumbnail())
echo '<div class="image">';
the_post_thumbnail('full');
echo '</div>';
?>
</div>
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
$custom_field = get_post_meta($postid,"meta_key",true); //get the custom field
// Localize the script with new data
$data = array(
'some_value' => $custom_field
);
wp_localize_script( 'some_handle', '_object', $data );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
然后,您可以访问php中的变量,如下所示:
var value = _object.some_value;