javascript 在页面中添加变量- WordPress

9w11ddsr  于 5个月前  发布在  Java
关注(0)|答案(3)|浏览(57)

当我在Wordpress中创建页面时,这些页面上的行动号召链接总是有相同的URL。我希望能够全球化这个变量,但我正在努力找到一个好的方法来做到这一点。
如果我在制作简单的PHP页面,我可以简单地包括e.g.

$URLpath = "http://example.com/my/page";

字符串
然后在html:

<a href="<?=$URLpath?>">Call to action</a>


显然我不能在Wordpress CMS中这样做,因为它呈现为<?=$URLpath?>
我可以添加,比如说,<a href="#MyVariable#">Call to action</a>,并在页面加载后使用JavaScript替换整个html块,但这样做并不高效。
还有更好的方法吗?我对Wordpress还很陌生。

2hh7jdfx

2hh7jdfx1#

你可以在你的functions.php文件中添加一个简短的代码来打印你的cta,或者更好地创建一个带有一些参数的插件来管理这个链接。
例如,在functions.php中,您可以添加

function cta_func( $atts ){
   $URLpath = "http://example.com/my/page";       
   return '<a href="'.$URLpath.'">Call to action</a>';
}
add_shortcode( 'cta', 'cta_func' );

字符串
在你的页面/帖子中,你可以简单地写这个简短的代码。

...
[cta]
...


有关简码的更多信息,请参阅codex https://codex.wordpress.org/Shortcode_API

yfjy0ee7

yfjy0ee72#

在WordPress中这样做的一个好方法是使用他们的wp_localize_script()
在你的functions.php文件中,你可以使用:

// For sake of example I will put your data inside an array,
// but you can set a single value.
$dataForJS = array(
  $URLPath => "http://example.com/my/page"
);

// wp_localize_script() takes 3 parameters:
// 1. Name of the registered script, this is the name you used in wp_register_script()
//    here I am naming it "main" but it can be anything.
// 2. Name of the variable.
//    This name is then available in your JS and will contain your data.
// 3. The data you want to pass, it can be a single value or array
wp_localize_script( 'main', 'd', $dataForJS );

字符串
在您的JavaScript中,您将能够通过调用变量d来访问此数据。
这样做的目的是,如果页面请求“主”脚本,WordPress将添加一个script标签,其中包含您的数据,并确保它被放置在您的“主”脚本运行之前。

kg7wmglp

kg7wmglp3#

wp_add_inline_script()是在WordPress 4.5版本中引入的,现在是向页面添加JavaScript变量的最佳实践。

wp_add_inline_script( 'mainjs', sprintf("const myDomain = '%s'", MY_DOMAIN), 'before' );

字符串

相关问题