Using WordPress ‘posts_request’ PHP filter

posts_request is a WordPress PHP filter that allows you to modify the completed SQL query before it’s sent to the database.

Usage

add_filter( 'posts_request', 'your_custom_function', 10, 2 );

function your_custom_function( $request, $query ) {
    // your custom code here
    return $request;
}

Parameters

  • $request string – The complete SQL query.
  • $query WP_Query – The WP_Query instance (passed by reference).

More information

See WordPress Developer Resources: posts_request

Examples

Remove LIMIT from query

To remove the LIMIT clause from the SQL query, you can use the following code:

function remove_limit_from_query( $request, $query ) {
    $request = preg_replace( '/LIMIT\s\d+(,\s*\d+)?/', '', $request );
    return $request;
}
add_filter( 'posts_request', 'remove_limit_from_query', 10, 2 );

Order posts by title length

If you want to order posts by the length of their title, use the following code:

function order_by_title_length( $request, $query ) {
    $request = str_replace( 'ORDER BY wp_posts.post_title', 'ORDER BY CHAR_LENGTH(wp_posts.post_title)', $request );
    return $request;
}
add_filter( 'posts_request', 'order_by_title_length', 10, 2 );

Exclude posts with specific meta value

To exclude posts with a specific meta value, use the following code:

function exclude_meta_value( $request, $query ) {
    global $wpdb;

    $request = str_replace( "FROM {$wpdb->posts}", "FROM {$wpdb->posts} LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = 'your_meta_key'", $request );

    $request .= " AND {$wpdb->postmeta}.meta_value != 'your_meta_value'";

    return $request;
}
add_filter( 'posts_request', 'exclude_meta_value', 10, 2 );

Change post type in query

To change the post type in the SQL query, use the following code:

function change_post_type_in_query( $request, $query ) {
    $request = str_replace( "post_type = 'post'", "post_type = 'your_custom_post_type'", $request );
    return $request;
}
add_filter( 'posts_request', 'change_post_type_in_query', 10, 2 );

Remove posts with specific word in title

To remove posts with a specific word in their title, use the following code:

function remove_posts_with_word( $request, $query ) {
    global $wpdb;
    $word = 'your_word';
    $request = str_replace( "WHERE 1=1", "WHERE 1=1 AND {$wpdb->posts}.post_title NOT LIKE '%$word%'", $request );
    return $request;
}
add_filter( 'posts_request', 'remove_posts_with_word', 10, 2 );