Custom wordpress SQL statement for a website

I think this could be life saver for you . This is a simple function for creating multiple loops. It retrieves a list of latest posts or posts matching criteria. <?php $posts_array = get_posts( $args ); ?> <?php $args = array( ‘numberposts’ => 5, ‘offset’ => 0, ‘category’ => , ‘orderby’ => ‘post_date’, ‘order’ => … Read more

Joining tables not working in the post editor page

The easy way in the admin is to do a 2nd custom query using the post_id from the post object. function custom_posts_data( $posts, $query ) { global $wpdb; if ( !count( $posts ) ) return $posts; while ( $posts as $post ) { $query = “SELECT * FROM {$wpdb->prefix}my_plugin_table WHERE post_id={$post->ID}”; $results = $wpdb->get_results( $query … Read more

order posts by a secondary query that counts items

The way to go is apply custom filters to the WP_Query you are running. add_filter(‘posts_clauses’, function ($clauses, $query) { global $wpdb; // only run the filter for a given query // do your checks and return early if (!$query->is_main_query() || !$query->is_post_type_archive(‘tracklist’)) { return $clauses; } $clauses[‘fields’] .= “, COUNT(items.id) AS track_count”; $clauses[‘join’] .= ” LEFT … Read more