Skip to content

Instantly share code, notes, and snippets.

@danlapteacru
Last active December 21, 2023 11:29
Show Gist options
  • Save danlapteacru/d8a1270c0ee5ce355eda0b1e0d469399 to your computer and use it in GitHub Desktop.
Save danlapteacru/d8a1270c0ee5ce355eda0b1e0d469399 to your computer and use it in GitHub Desktop.
Filter posts by post title first letter in WordPress (PHP 7.x)
<?php
/**
* Filter posts by post title first letter in WordPress (PHP 7.x)
*/
add_filter('posts_where', function (string $where, WP_Query $query): string {
$wpdb = $GLOBALS['wpdb'];
$starts_with = esc_sql($query->get('title_starts_with'));
if (empty($starts_with)) {
return $where;
}
$where .= $wpdb->prepare(" AND $wpdb->posts.post_title LIKE %s", $starts_with . '%');
return $where;
}, 10, 2);
<?php
$query = new WP_Query([
'post_type' => 'post',
'title_starts_with' => 'A',
]);
// OR
add_action('pre_get_posts', function (WP_Query $query): void {
if (! $query->is_main_query() || ! $query->is_post_type_archive('post')) {
return;
}
$query->set('title_starts_with', 'A');
}, 10, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment