Halloween Sale 15% off Ends in See the plans
PHP

Inspect the Main Query and Its SQL

Lets administrators add ?wpide_query=1 to a front-end URL to print the main query's variables, the SQL it ran and the number of posts found at the bottom of the page.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'wp_footer', function () {
    if ( ! isset( $_GET['wpide_query'] ) || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    global $wp_query;
    $vars = array_filter( (array) $wp_query->query_vars, function ( $value ) {
        return '' !== $value && array() !== $value && null !== $value && false !== $value;
    } );

    echo '<div style="margin:2rem;padding:1rem;background:#fff;color:#1d2327;border:1px solid #c3c4c7;font:13px/1.5 monospace;position:relative;z-index:99999;overflow:auto">';
    printf( '<p><strong>Found posts:</strong> %d · <strong>Max pages:</strong> %d · <strong>Queried object:</strong> %s</p>', (int) $wp_query->found_posts, (int) $wp_query->max_num_pages, esc_html( is_object( get_queried_object() ) ? get_class( get_queried_object() ) . ' #' . get_queried_object_id() : 'none' ) );
    echo '<p><strong>SQL</strong></p><pre style="white-space:pre-wrap">' . esc_html( (string) $wp_query->request ) . '</pre>';
    echo '<p><strong>Query vars</strong></p><pre style="white-space:pre-wrap">' . esc_html( print_r( $vars, true ) ) . '</pre></div>';
}, PHP_INT_MAX );

Notes

Useful when a pre_get_posts change does not behave as expected.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.