Is it possible to trigger injection of <script> to multiple wordpress posts from a plugin?

Viewed 91

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.

  1. 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');

  1. 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();
}

1 Answers

This code will never run:

function ajax_request_function()
{
    
    if(isset($_POST))
    {
        add_action('wp_head', 'inject_script_to_head');
    }   
    die();
}

Try this one:

function inject_script_to_head() {
  if(is_single()){
    ?>
        <script>
            alert("adding this to header");
        </script>
    <?php
    }
}

add_action('wp_head', 'inject_script_to_head');
Related