Why can I not use setup_postdata($post) in the sidebar?

Your function works in your page template but not in the sidebar because at the point that your template is processed, $post already contains the post that has been loaded for the page. I tried your code and, just like Michael said, all I needed to add was the global declaration of $post inside the … Read more

Query all posts where meta value is empty

I think you forgot about the inherit post status. The default one in WP_Query is publish. You should also use = instead of LIKE, to avoid using LIKE ‘%%’ in the SQL query. So try to add this: ‘post_status’ => ‘inherit’ and ‘compare’ => ‘=’ into your query arguments, to match the empty _wp_attachment_image_alt string … Read more

Is it possible to select against a post’s parent’s fields with WP_Query?

You should use posts_join and posts_where filters to modify JOIN and WHERE clauses. add_filter( ‘posts_join’ , ‘se333659_posts_join’, 20, 2 ); add_filter( ‘posts_where’ , ‘se333659_posts_where’, 20, 2 ); function se333659_posts_join( $join, $query ) { global $wpdb; if ( isset($query->query_vars[‘_rev_of_publ’]) && $query->query_vars[‘_rev_of_publ’] == ‘1’ ) { $join .= ” LEFT JOIN {$wpdb->posts} AS rev_p ON ({$wpdb->posts}.post_parent = … Read more

Get all authors with at least one post of ‘custom post type’

For now post_type support is not currently available for count_user_posts(), so put the below code in theme’s functions.php file. function count_user_posts_by_type( $userid, $post_type=”post” ) { global $wpdb; $where = get_posts_by_author_sql( $post_type, true, $userid ); $count = $wpdb->get_var( “SELECT COUNT(*) FROM $wpdb->posts $where” ); return apply_filters( ‘get_usernumposts’, $count, $userid ); } Now this function would take … Read more

Get the exact SQL query that get_posts() generated

The get_posts() function creates an instance of WP_Query inside the function and simply returns the array of results. This WP_Query instance doesn’t override the global $wp_query and is out of scope by the time you need it. In short, I don’t see a way how you can get the requested SQL via get_posts(). An alternative … Read more

date_query not returning some posts in date range

Your syntax is incorrect for your date_query. It should be an array of an array, not just an array. I also suspect that your problem might be related to PHP and not WordPress. Your before date is invalid. PHP only supports dates between 13 December 1901 and 19 January 2038, so your dates need to … Read more

get posts based on meta value of the author

Get for all users / authors with user meta field. meta1 = true $args = array( ‘meta_key’ => ‘meta1’, ‘meta_value’ => ‘true’, ‘meta_compare’ => ‘=’, ‘fields’ => ‘all’, ); $users = get_users( $args ); Store user id and login into an array authors $authors = array(); foreach ( (array) $users as $user ) { authors[ … Read more