• Resolved SilverSunrise

    (@silversunrise)


    Hi,

    since I changed to PHP 8.0 I get this error-message in the server logs:

    126359#0: *37455 FastCGI sent in stderr: “PHP message: PHP Warning: Attempt to read property “ID” on null in?…/wp-content/plugins/code-snippets/php/snippet-ops.php(582) : eval()’d code on line 5″ while reading response header from upstream

    I only have one snippet activated with the following code:

    add_action( 'template_redirect', 'redirect_to_primary_category' );
    function redirect_to_primary_category() {
    global $post;
    // If the post is single.
    if ( is_single( $post->ID ) ) {
    // If the post has multiple categories assigned.
    $cats = wp_get_post_categories( $post->ID );
    if ( count( $cats ) > 1 ) {
    // Get the primary category.
    $primary_category = get_post_meta( $post->ID, 'rank_math_primary_category', true );
    // If the primary category isn't in the URL, redirect.
    global $wp;
    $primary_object = get_term( $primary_category );
    if ( 0 !== strpos( $wp->request, $primary_object->slug ) ) {
    $primary_url = home_url( '/' . $primary_object->slug . '/' . $post->post_name . '/' );
    wp_safe_redirect( $primary_url, 301 );
    exit;
    }
    }
    }
    }

    I cannot find any error in this snippet. Could you please take a look?

    Thank you so much

    Joachim

    • This topic was modified 7 months, 2 weeks ago by SilverSunrise.

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Plugin Author Shea Bunge

    (@bungeshea)

    Hi Joachim,

    You can’t be assured that the global $post variable will be set on each instance that the function is called. You can just include it in your if statement to avoid this error:

    add_action( 'template_redirect', 'redirect_to_primary_category' );
    function redirect_to_primary_category() {
    	global $post;
    	// If the post is single.
    	if ( $post && is_single( $post->ID ) ) {
    		// If the post has multiple categories assigned.
    		$cats = wp_get_post_categories( $post->ID );
    		if ( count( $cats ) > 1 ) {
    			// Get the primary category.
    			$primary_category = get_post_meta( $post->ID, 'rank_math_primary_category', true );
    			// If the primary category isn't in the URL, redirect.
    			global $wp;
    			$primary_object = get_term( $primary_category );
    			if ( 0 !== strpos( $wp->request, $primary_object->slug ) ) {
    				$primary_url = home_url( '/' . $primary_object->slug . '/' . $post->post_name . '/' );
    				wp_safe_redirect( $primary_url, 301 );
    				exit;
    			}
    		}
    	}
    }
Viewing 1 replies (of 1 total)
  • The topic ‘PHP error / eval()’d code’ is closed to new replies.