Should I use Pre Get Posts or WP_Query

pre_get_posts will run the same query, so both will take same time. But, If you utilize pre_get_posts action you will save one or more SQL queries. Right now, WordPress is running default query and then you run your query with this function which replace the results of the default query (resulting, default query is of … Read more

How to store and receive variables in WP sessions?

Sessions aren’t enabled in wordpress by default, if you want to activate php sessions add this at the beginning of your functions.php: if (!session_id()) { session_start(); } You now can use $_SESSION[‘your-var’] = ‘your-value’; to set a session variable. Take a look at the PHP documentation on sessions. Update: There was a second answer, which, … Read more

How to extend WP_Query to include custom table in query?

Important disclaimer: the proper way to do this is NOT to modify your table structure, but to use wp_usermeta. Then you will not need to create any custom SQL to query your posts (though you’ll still need some custom SQL to get a list of everyone that reports to a particular supervisor – in the … Read more

How to print the excuted sql right after its execution

The $wpdb object has some properties getting set for that: global $wpdb; // Print last SQL query string echo $wpdb->last_query; // Print last SQL query result echo $wpdb->last_result; // Print last SQL query Error echo $wpdb->last_error; Note: First of all you have to set define( ‘SAVEQUERIES’, true ); in your wp-config.php file at root folder … Read more

Exclude post ID from wp_query

I suppose this was heavy, but to answer your original question, I’ve collected all of the posts id’s in an array in the first loop, and excluded those posts from the second loop using ‘post__not_in’ which expects an array of post id’s <?php $args1 = array(‘category_name’ => ‘test-cat-1’, ‘order’ => ‘ASC’); $q1 = new WP_query($args); … Read more

Pagination when using wp_query?

Replace <!– WHAT GOES HERE?????? –> with the pagination code below: <div class=”pagination”> <?php echo paginate_links( array( ‘base’ => str_replace( 999999999, ‘%#%’, esc_url( get_pagenum_link( 999999999 ) ) ), ‘total’ => $query->max_num_pages, ‘current’ => max( 1, get_query_var( ‘paged’ ) ), ‘format’ => ‘?paged=%#%’, ‘show_all’ => false, ‘type’ => ‘plain’, ‘end_size’ => 2, ‘mid_size’ => 1, ‘prev_next’ … Read more

meta_query with meta values as serialize arrays

No, it is not possible, and could even be dangerous. Serialised data is an attack vector, and a major performance issue. I strongly recommend you unserialise your data and modify your save routine. Something similar to this should convert your data to the new format: $args = array( ‘post_type’ => ‘my-post-type’, ‘meta_key’ => ‘_coordinates’, ‘posts_per_page’ … Read more