繁体   English   中英

在页面中添加变量-Wordpress

[英]Adding a variable into a page - wordpress

当我在Wordpress中创建页面时,这些页面上的号召性用语链接始终具有相同的URL。 我希望能够全球化此变量,但正在努力寻找一种实现此变量的好方法。

如果我要编写简单的PHP页面,则可以仅包含例如

$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。

在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标签,并确保将其放置在“主”脚本运行之前。

您可以在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM