wp_nav_menu_objects with pre_get_posts

I am trying to query the posts based on my navigation menu.
i.e I take the object id of the first item in navigation menu and want to query posts in that way,

Here are the Codes.

Read More

To Get first Item from Navigation Menu

 function get_theme_item( $theme_location ) {
     if( ! $theme_location ) return false;

     $theme_locations = get_nav_menu_locations();
     if( ! isset( $theme_locations[$theme_location] ) ) return false;

     $menu_obj = get_term( $theme_locations[$theme_location], 'nav_menu' );
     if( ! $menu_obj ) return false;

    $menu_items = wp_get_nav_menu_items($menu_obj->term_id);
    foreach ($menu_items as $menu_item) {
      $qid = $menu_item->object_id;
        break;
     }
     return $qid;
}

Well, this works flawlessly and returns the id of first menu item.

Querying posts code:

 function p_query_posts($query) {
    $id = get_theme_item('header_menu');
 if (  $query->is_main_query() && is_front_page() ) {
    $query->set( 'post_type', array( 'album_post' ) );
      $taxquery = array(
    array(
        'taxonomy' => 'album',
        'field' => 'id',
        'terms' => array($id)
        )
    );

$query->set( 'tax_query', $taxquery );
}

return $query;
}
add_action('pre_get_posts','p_query_posts');

PROBLEM:
This gives me an 500 Internal server error, without displaying any error.
if i change $id to 12 , ie $id = '12', it works properly.

Any help appreciated.

Related posts