0

I'm trying to make my first plugin, but when I try wp_enqueue_script the script file, I get errors about the ID, post_title, post_name, even though its a single page (i.e. not posts kind of page).

// enqueue scripts
function myplugin_enqueue_scripts( $hook ) {
    if ( !is_page('my-page'))  { return; }

    // define script url
    $script_url = plugins_url( 'public/myplugin.js', __FILE__ );

    // enqueue script
    // Below line cause the error
    wp_enqueue_script('myplugin', $script_url);

}
add_action( 'wp_enqueue_scripts', 'myplugin_enqueue_scripts', 1);

I get this error message:

[23-Jun-2020 21:59:56 UTC] PHP Notice:  Trying to get property 'ID' of non-object in /usr/www/users/sexerxm/example.server.com/wp-includes/class-wp-query.php on line 3994
[23-Jun-2020 21:59:56 UTC] PHP Notice:  Trying to get property 'post_title' of non-object in /usr/www/users/sexerxm/example.server.com/wp-includes/class-wp-query.php on line 3996
[23-Jun-2020 21:59:56 UTC] PHP Notice:  Trying to get property 'post_name' of non-object in /usr/www/users/sexerxm/example.server.com/wp-includes/class-wp-query.php on line 3998

Within myplugin.js is one line:

console.log("Please work");

I also tried the template_redirect hook but no difference. Why is this error being generated?

2
  • Are you trying this on a clean installation? Does the error persist if you try a regular string as the URL instead of the plugins_url function result? – Himad Jun 23 '20 at 22:23
  • Additionally its not a clean installation, the person has a woo commerce plugin installed and a few others. I am not sure i am allowed to disable them. I tried a high and low add_action priority to try negate other plugin interference but jad the same result – run_the_race Jun 24 '20 at 6:49
0

Issue 1

I was not seeing the embedded object in javascript because:

The error was, I thought plugins_url always resolved to the plugins dir, it resolves to the dir of __FILE__:

In my situation myplugin.js and myplugin.php are both in the same public/ dir, so this:

$script_url = plugins_url( 'public/myplugin.js', __FILE__ )

Was resolving as (notice the double public):

http://server.example.com/wp-content/plugins/myplugin/public/public/myplugin.js

instead of

http://server.example.com/wp-content/plugins/myplugin/public/myplugin.js

Issue 2

I still see the error, however even with my plugin disabled, and managed to track it down to WooComerce by looking at the debug network tab and seeing the ajax request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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