当我在Wordpress中创建页面时,这些页面上的调用操作链接总是具有相同的URL。我希望能够全球化这个变量,但我正在努力找到一个好的方法来做到这一点。
如果我正在制作简单的PHP页面,我可以简单地包括例如
$URLpath = "http://example.com/my/page";
然后在html:
<a href="<?=$URLpath?>">Call to action</a>
显然我不能在Wordpress CMS中这样做,因为它呈现为<?=$URLpath?>
我可以在页面加载后使用javascript替换整个html块,然后添加<a href="#MyVariable#">Call to action</a>
和replace,但这样做感觉效率不高。
有更好的方法吗?我对Wordpress很陌生
你可以在你的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]
...
关于短代码的更多信息见法典参考https://codex.wordpress.org/Shortcode_API
在WordPress中使用wp_localize_script()是一个很好的方法
在functions.php文件中,可以使用as:
// 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
标记与你的数据在里面,并确保它被放置在你的"主"脚本运行之前。