1

I have this code and the $var1 arrives empty to my function i dont know why, i've tested declaring the variable inside the function and it does work but when i try to declare it outside the function and pass it as a parameter with the do_action it doesn't work, any insights on this ? thanks

The add_shortcode works fine

$name="link";   
    add_shortcode($name, 'aa_link_shortcode' );

    function shorcode_resources($var1) {
        global $post;
       $shortcode_found = false;

       if ( has_shortcode($post->post_content, $var1) ) {
          $shortcode_found = true;
       } 

       if ( $shortcode_found ) {
        wp_enqueue_style( 'core', ABS_URL . '/shortcode/css/flipbox.css' , false ); 
        wp_enqueue_script( 'my-js',ABS_URL . '/shortcode/js/flipbox('.$var1.').js', false );
       }

}

do_action( 'wp_enqueue_scripts', $name);    
add_action( 'wp_enqueue_scripts', 'shorcode_resources', 10, 1 );

2 Answers 2

3

You are doing the do_action before the action is add, try moving it:

$name = "link";
add_shortcode($name, 'aa_link_shortcode');

function shorcode_resources($var1) {
    global $post;
    $shortcode_found = false;

    if (has_shortcode($post->post_content, $var1)) {
        $shortcode_found = true;
    }

    if ($shortcode_found) {
        wp_enqueue_style('core', ABS_URL . '/shortcode/css/flipbox.css', false);
        wp_enqueue_script('my-js', ABS_URL . '/shortcode/js/flipbox(' . $var1 . ').js', false);
    }
}

//first we add the action
add_action('wp_enqueue_scripts', 'shorcode_resources', 10, 1);
//then we do the action
do_action('wp_enqueue_scripts', $name);

also remember that wp_enqueue_scripts its an action that WP will trigger too

1
  • This seems correct! Commented Nov 3, 2017 at 2:59
1

I'm not really sure of the intent of this code, but more than likely the problem is that you are trying to change a built in hook. wp_enqueue_scripts is an actual WordPress hook that does not accept any arguments. Even though you declared you are passing one, when WP runs its wp_enqueue_scripts hook, it's going to ignore it. Maybe try using a global variable instead.

$shortcode_name="link";   
add_shortcode($shortcode_name, 'aa_link_shortcode' );

function shorcode_resources() {
   global $post, $shortcode_name;
   $shortcode_found = false;

   if ( has_shortcode($post->post_content, $shortcode_name) ) {
      $shortcode_found = true;
   } 

   if ( $shortcode_found ) {
    wp_enqueue_style( 'core', ABS_URL . '/shortcode/css/flipbox.css' , false ); 
    wp_enqueue_script( 'my-js',ABS_URL . '/shortcode/js/flipbox('.$shortcode_name.').js', false );
   }
}

add_action( 'wp_enqueue_scripts', 'shorcode_resources', 10 ); 
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.