I want to put a shortcode in a WordPress website using JavaScript.
Website structure is
JavaScript
x
5
1
<div class="shop-container">
2
<div class="wrap">[shortcode here]</div>
3
<div class="wc-pr"> </div>
4
</div>
5
Firstly, i put div element to above wc-pr using below code.
JavaScript
1
11
11
1
<script>
2
const parent5 = document.querySelector('.shop-container');
3
const billingField1 = document.querySelector('.wc-pr');
4
5
const newDiv = document.createElement('div');
6
newDiv.setAttribute('id', 'wrap');
7
8
parent5.insertBefore(newDiv, billingField1);
9
</script>
10
11
Then i tried below code.
JavaScript
1
3
1
newDiv.innerHTML = `<?php do_shortcode("[shortcode here]");?>`;
2
newDiv.innerText = `<?php do_shortcode("[shortcode here]");?>`;
3
But not working. innertext is diplayed as raw, Hhtml is not showing.
Please let me know how do i solve this
Thank you.
Advertisement
Answer
You are creating/generating an HTML, so you must echo it to the script. So just adding echo to the PHP
newDiv.innerHTML = '<?php echo do_shortcode("[shortcode here]");?>';
instead of
newDiv.innerHTML = '<?php do_shortcode("[shortcode here]");?>';
should do it.