最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Wordpress: Outputting shortcode with Javascript? - Stack Overflow

programmeradmin3浏览0评论
<script language=”javascript”>
if (country_code==’US’)
{
document.write("[adrotate banner="1"]");
}
else
{
document.write("[adrotate banner="2"]");
}
</script>

[adrotate banner="x"] are wordpress shortcodes used for the Adrotate plugin

This script doesen't work because somehow outputting [adrotate banner="x"] is not possible? It uses the globally saved variable country_code.

I've tried with both " and ' (and the inner using one of them and the outer the other), but with no luck.

Any way to work around this and still use JS?

<script language=”javascript”>
if (country_code==’US’)
{
document.write("[adrotate banner="1"]");
}
else
{
document.write("[adrotate banner="2"]");
}
</script>

[adrotate banner="x"] are wordpress shortcodes used for the Adrotate plugin

This script doesen't work because somehow outputting [adrotate banner="x"] is not possible? It uses the globally saved variable country_code.

I've tried with both " and ' (and the inner using one of them and the outer the other), but with no luck.

Any way to work around this and still use JS?

Share Improve this question edited Apr 22, 2014 at 9:24 Tony 10.4k3 gold badges50 silver badges77 bronze badges asked Apr 30, 2013 at 16:27 user2336702user2336702 3431 gold badge4 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Shortcodes only work server side. If you want to work around it, you can submit the value using AJAX, call do_shortcode() on it in your PHP, return the results as JSON, and then write to the page.

http://codex.wordpress/Function_Reference/do_shortcode

As a side note, your example has a syntax error because you have double quotes inside your string, since it won't process as a shortcode. You either need to escape it or use single quotes.

Try to use ` backtick (Template literals) https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals?retiredLocale=it

<script language=”javascript”>
var option1 = `[adrotate banner="1"]`;
var option2 = `[adrotate banner="2"]`;

if (country_code=='US') {
    document.write(option1);
} else {
    document.write(option2);
}
</script>

also work with php code (workaround for single and double quote) :

<script language=”javascript”>
var option1 = `<?php echo do_shortcode('[adrotate banner="1"]'); ?>`;
var option2 = `<?php echo do_shortcode('[adrotate banner="2"]'); ?>`;

if (country_code=='US') {
    document.write(option1);
} else {
    document.write(option2);
}
</script>

发布评论

评论列表(0)

  1. 暂无评论