Should I reset $wp_query?

Question

I am not totally new on WordPress but the query thing is a bit confusing to me. I searched the web and read a lot of articles, but I couldn’t find what I needed. Maybe it could help a lot of people who have WordPress skills like me.

I want to create a shortcode and I need to loop through a custom post type called events.

function leweb_get_suggested_events() {

    // Query
    global $wp_query;

    // Arguments  
    $args = array(
        'post_type' => 'events',
    );  

    ob_start();

    $query = new WP_Query( $args );

    if( $query->have_posts() ) {
        echo '<ul>';
        while( $query->have_posts() ) {
            $query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
        echo '</ul>';
    }

    $output = ob_get_clean();
    return $output;

}
add_shortcode( 'leweb_suggested_events', 'leweb_get_suggested_events' );

The query is right and its working. But should I reset something?

I call the global $wp_query to get in the main loop. This is what I found out on reading some articles.

Then I start my own loop with $query = new WP_Query($args);
So I have two loops right? The main loop and my own loop.

Should I reset them both or just one of them, or is it fine like above?

0
, , , LovinQuaQua 3 years 2019-10-30T18:24:33-05:00 0 Answers 79 views 0

Leave an answer

Browse
Browse