Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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');
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda