1

I am using a WordPress plugin. Everything work fine. Exect when open a 404 page, I got this notice:

Notice: Trying to get property of non-object in D:\MYWEB\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\plugins\sama-author-review\user-rate.php on line 49

Line 49 looks like this:

'nonce' => wp_create_nonce('ajax-user-rate-nonce-'. $post->ID)

Here the code:

/**
 * enqueue scripts used in frontend
 *
 */
function sama_enqueue_scripts() {
    global $post, $sama_author_review;

    $ajax_vars = array(
        'url' => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce('ajax-user-rate-nonce-'. $post->ID)
    );
    // see author-review.php
    wp_localize_script( 'review', 'ajax_user_rate', $ajax_vars );
}

Is there a quick fix to resolve these error?

1 Answer 1

2

The $post global is not set on 404 pages, which leads to the error you are getting.

You can either check if

  • $post is set or

  • bail if the current page is a 404 page or

  • do all of the above

EXAMPLE

/**
 * enqueue scripts used in frontend
 *
 */
function sama_enqueue_scripts() {
     global $post, $sama_author_review;

    if ( !isset( $post ) )
        return;

     $ajax_vars = array(
         'url' => admin_url( 'admin-ajax.php' ),
         'nonce' => wp_create_nonce('ajax-user-rate-nonce-'. $post->ID)
     );
     // see author-review.php
     wp_localize_script( 'review', 'ajax_user_rate', $ajax_vars );
}

or

/**
 * enqueue scripts used in frontend
 *
 */
function sama_enqueue_scripts() {
     global $post, $sama_author_review;

    if ( is_404() )
        return;

     $ajax_vars = array(
         'url' => admin_url( 'admin-ajax.php' ),
         'nonce' => wp_create_nonce('ajax-user-rate-nonce-'. $post->ID)
     );
     // see author-review.php
     wp_localize_script( 'review', 'ajax_user_rate', $ajax_vars );
}
2
  • Thank you. 1000+. I am using your first answer and everything work fine.
    – Mailmulah
    Mar 13, 2016 at 17:21
  • My pleasure, glad it works. Enjoy ;-) Mar 13, 2016 at 17:22

Your Answer

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

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