• Skip to main content

Julian Thomas Screawn

B.A. ,B.ED. ,M.ED.

  • Home
  • About
  • Websites
  • Resources
  • Coding
  • Contact

Adding Filter to WordPress Query

2025/11/10

function wp_filter_posts_where( $where, $query ) {
    global $wpdb;

    $starts_with = esc_sql( $query->get( 'starts_with' ) );

    if ( $starts_with ) {
        $where .= " AND $wpdb->posts.post_title LIKE '$starts_with%'";
    }

    return $where;
}
add_filter( 'posts_where', 'wp_filter_posts_where', 10, 2 );
With this filter added, we can query posts like this:

$query = new WP_Query( array(
    'starts_with' => 'M',
) );

Filed Under: Uncategorized

Copyright © 2025 · Servicing Moncton, Dieppe, Riverview and beyond! · Moncton Meditation · Moncton English Tutor