Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!