Last active
December 21, 2023 11:29
-
-
Save danlapteacru/d8a1270c0ee5ce355eda0b1e0d469399 to your computer and use it in GitHub Desktop.
Filter posts by post title first letter in WordPress (PHP 7.x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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