• Resolved rockstaremperor

    (@rockstaremperor)


    Hi,
    My WordPress site is on PHP 8.1. I am using the following scripts via a code snippet

    function blogger_query_vars_filter( $vars ) {
      $vars[] = "blogger";
      return $vars;
    }
     
    add_filter('query_vars', 'blogger_query_vars_filter');
     
    function blogger_template_redirect() {
      global $wp_query;
      $blogger = $wp_query->query_vars['blogger'];
      if ( isset ( $blogger ) ) {
        wp_redirect( get_wordpress_url ( $blogger ) , 301 );
        exit;
      }
    }
     
    add_action( 'template_redirect', 'blogger_template_redirect' );
     
    function get_wordpress_url($blogger) {
      if ( preg_match('@^(?:https?://)?([^/]+)(.*)@i', $blogger, $url_parts) ) {
        $query = new WP_Query ( 
          array ( "meta_key" => "blogger_permalink", "meta_value" => $url_parts[2] ) );
        if ($query->have_posts()) { 
          $query->the_post();
          $url = get_permalink(); 
        } 
        wp_reset_postdata(); 
      } 
      return $url ? $url : home_url();
    }
    

    Though the code is working fine, I am getting PHP errors as below

    PHP Warning:  Undefined array key "blogger" in /home/lsudlknf/public_html/wp-content/plugins/code-snippets/php/snippet-ops.php(505) : eval()'d code on line 10
    

    Please help.

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

    (@bungeshea)

    You need to check whether the blogger key exists before attempting to access it:

    add_filter( 'query_vars', function ( $vars ) {
    	$vars[] = 'blogger';
    	return $vars;
    } );
    
    add_action( 'template_redirect', function () {
    	global $wp_query;
    	if ( array_key_exists( 'blogger', $wp_query->query_vars ) ) {
    		wp_redirect( get_wordpress_url( $wp_query->query_vars['blogger'] ), 301 );
    		exit;
    	}
    } );
    
    function get_wordpress_url( $blogger ) {
    	$url = '';
    
    	if ( preg_match( '@^(?:https?://)?([^/]+)(.*)@i', $blogger, $url_parts ) ) {
    		$query = new WP_Query ( array( 'meta_key' => 'blogger_permalink', 'meta_value' => $url_parts[2] ) );
    		if ( $query->have_posts() ) {
    			$query->the_post();
    			$url = get_permalink();
    		}
    		wp_reset_postdata();
    	}
    	return $url ? $url : home_url();
    }
    Thread Starter rockstaremperor

    (@rockstaremperor)

    I did not understand. Where do I check?
    Above is a Redirection code from Blogger to WordPress and the redirection is working fine without problem. Error is reported in Error Log only.

    Plugin Author Shea Bunge

    (@bungeshea)

    Did you try using the updated code I posted? Your snippet code contained a bug that was producing that error message.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘PHP Error’ is closed to new replies.