I am trying to inject a <script> into multiple wordpress posts using my plugin, which is created with react as a frontend.
This is all I have tried to achieve this, but nothing seems to work.
- tried using the
addAction('hook name', 'namespace', 'callback')
from @wordpress/hooks but this doesn't seem to work. (below code in JS file).
myObj.addAction('wp_head', 'namespace', function() {
<script>console.log("Hello World")</script>;
});
myObj.doAction('wp_head');
- made an AJAX call to php to trigger the
add_action('wp_head', 'callback')
, but <script> tag is not being added to the but works without the AJAX, if we try to do this from the entry file of the plugin manually. (below code in PHP file)
//to create the wp_ajax_* hooks in my PHP script.
add_action('wp_ajax_request_function','ajax_request_function');
//AJAX call from react component.
jQuery(document).ready(function ($) {
$.ajax({
url: ajaxurl,
data: {
'action': 'ajax_request_function',
'post_type': 'POST'
},
success: function (data) {
window.alert(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
});
function inject_script_to_head() {
?>
<script>
alert("adding this to header");
</script>
<?php
}
function ajax_request_function()
{
if(isset($_POST))
{
add_action('wp_head', 'inject_script_to_head');
}
die();
}
source https://stackoverflow.com/questions/68966907/is-it-possible-to-trigger-injection-of-script-to-multiple-wordpress-posts-from
Comments
Post a Comment