WP Query with custom Shortcode

There are few issue with your code

  • When using WP_Query in conjuction with the_post() or using get_posts() in conjuction with setup_postdata( $post ), you need to reset the $post global with wp_reset_postdata(), not wp_reset_query(). wp_reset_query() is used in conjuction with query_posts() which you should never ever use

  • You would want to reset posdata between your endwhile and endif statements. If you don’t have any posts, there is no need to reset $post as you have never changed it.

  • Where possible, you should avoid using globals. Globals are evil. WordPress has already made such a huge mess of it. Don’t dirty global space any further. There are a couple of excellent posts on-site with extremely good alternatives to using globals. Be sure to make use of the on-site search function

  • pre_get_posts alters all queries, front end and back end. You will specifically need to target a specific query on a specific page to avoid unexpected behavior. If you only need to target the main query on your search pahe, you will need to add the following conditions

    if (    !$query->is_main_query() // Bail if this is not the main query
         && !$query->is_search() // Bail if this is not the search page
    ) {
        return;
    }
    
  • Never ever make use of unsanitized data coming from form inputs or from super globals. These are popular places which is used by hackers to inject malicious code into a website. ALWAYS ALWAYS sanitize, validate and/or escape any user supplied data according to the type of data you expect. Don’t even trust your own input. A simple piece of code injected into a URL or a form field can give a hacker full access to your site which will compromise your complete site. If you are running a site with personal info, you can land yourself in jail for leaking personal info. So please, ALWAYS SANITIZE, VALIDATE AND ESCAPE APPROPRIATELY

tech