How to detect custom query inside `posts_where` hook?

If we have the query arguments like this $args = array( ‘queryid’ => ‘blackjack’, … ); $q = new WP_Query( $args ); Note we added one custom query argument that is not officially present in here. Now we can identify the exact query by that queryid if we use the second parameter of the posts_where … Read more

Get posts by category with pure SQL query

If you want to be able to get the category by name, this should work: SELECT DISTINCT substr(post_title, – instr(reverse(post_title), “https://wordpress.stackexchange.com/”) + 1) AS year FROM {$wpdb->posts} p LEFT JOIN {$wpdb->term_relationships} rel ON rel.object_id = p.ID LEFT JOIN {$wpdb->term_taxonomy} tax ON tax.term_taxonomy_id = rel.term_taxonomy_id LEFT JOIN {$wpdb->terms} t ON t.term_id = tax.term_id WHERE post_status=”publish” AND … Read more

WP database error for comments_popup_link()

Your template code includes $wpdb->print_error(). This function prints the last database error between [ and ] brackets, and the executed SQL code. But if there is no error, you just see the empty brackets and the SQL. $wpdb->show_errors() is used to enable displaying of database errors. If you want to see all database errors, you … Read more

WordPress custom archive page

Of course it breaks. Pagination depends on the main query saved in the $wp_query object and you have overwritten that. When the next page load the ordinary wp_query that you have not overwritten will run and it won’t match the one you’ve altered. Create a filter for pre_get_posts to alter the main query. function pregp_wpse_97354($qry) … Read more

How can I display a specific user’s first published post?

The following query retrieves the oldest post of a specified user/author: $user_id = 42; // or whatever it is $args = array( ‘posts_per_page’ => 1, ‘post_status’ => ‘publish’, ‘author’ => $user_id, ‘orderby’ => ‘date’, ‘order’ => ‘ASC’, ); $first_post = new WP_Query($args); if ($first_post->have_posts()) { $first_post->the_post(); // Now you can use `the_title();` etc. wp_reset_postdata(); } … Read more

Get IDs of posts currently visible on archive

When the wp_enqueue_scripts action fires, the main query has already run and the posts are in the global $wp_query. We just need to grab the ID from each object in $wp_query->posts, the wp_list_pluck function makes that easy: function wpd_get_post_ids(){ if( is_archive() ){ global $wp_query; $post_ids = wp_list_pluck( $wp_query->posts, ‘ID’ ); // $post_ids now contains an … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)