2015-10-16 84 views
1

当我在Wordpress中创建页面时,这些页面上的调用动作链接始终具有相同的URL。我希望能够全球化这个变量,但我正在努力找到一个好办法。向页面添加变量 - wordpress

如果我正在制作简单的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很新。

+0

参考为什么不能您在WordPress的PHP脚本? – Filype

+0

你想通过wordpress可视化编辑器添加php代码吗? – madforstrength

回答

1

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

+1

这并不是在技术上回答我的问题,但确实给了我一种思考的替代方式,所以授予了答案 - 谢谢! –

1

一个好办法在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标记,并确保它放置在“主要”脚本运行之前。