1
votes

I am getting the following errors:

wp_register_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the some_handle handle. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.)
wp_enqueue_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the some_handle handle. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.)

I've narrowed it down to some logic I've included in my functions.php file. What I am doing here is querying the database of users to see which users selected a certain checkbox on their registration form, though I must not be enqueueing the scripts correctly. Any idea on what I am doing wrong?

//1. get User Status
 $user_id   = get_current_user_id();
 $user_output =  get_user_meta($user_id, 'needs_extra_item', true);
 //echo $user_output[0];

//2. Register the script
wp_register_script( 'some_handle', './js/jqueryLaPuerta.js' );
 
//3. Localize the script with new data
$some_array = array(
    'some_string' => __( $user_output, 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $some_array );
 
//4. Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );```
1

1 Answers

2
votes

Assuming that this is all floating in your functions.php file, that is what this issue is; you need to hook the enqueue to the wp_enqueue_scripts action. That basically amounts to wrapping your logic in an a function and calling that function at the appropriate time. Assuming you are using a version of php that supports closures, something like this should work:

add_action('wp_enqueue_scripts', function(){
      //1. get User Status
      $user_id   = get_current_user_id();
      $user_output =  get_user_meta($user_id, 'needs_extra_item', true);
      //echo $user_output[0];

      //2. Register the script
      wp_register_script( 'some_handle', './js/jqueryLaPuerta.js' );

      //3. Localize the script with new data
      $some_array = array(
          'some_string' => __( $user_output, 'plugin-domain' ),
          'a_value' => '10'
      );
      wp_localize_script( 'some_handle', 'object_name', $some_array );

      //4. Enqueued script with localized data.
      wp_enqueue_script( 'some_handle' );
});

It is getting upset with you because you're enqueuing scripts as soon as the functions.php file is included. (Which is long before you're really supposed to.)