I have >100 custom post type articles in Metabox that serve as dictionary articles. I now want to build one page which links all articles based on their initial letters in the title (aka a table of content for this dictionary)
Example
Articles starting with A
Article A1
Article A2
Article A3
Articles starting with B
Article B1
Article B2
Article B3
My options
Create a custom field and add the initial letter there. Then create 26 different sections. Sounds not right
Custom query (I cannot figure out how to use a regex or sth similar in the query)
I think your best bet is creating a custom query type / custom query types.
A starting point:
Create a helper function to fetch the posts from the DB (adjust the parameters like post_type to your needs).
function get_dictionary_posts( $letter ) {
global $wpdb;
return $wpdb->get_results( "
SELECT * FROM {$wpdb->prefix}posts
WHERE post_type = 'post' AND post_status = 'publish' AND post_title LIKE '{$letter}%'
ORDER BY post_title ASC
", OBJECT );
}
I created another version with just two query types: One for the letters (outer query) and another one for the posts starting with a specific letter (inner query). So you just need to nest two query loops like this:
It is not yet working, (at least the custom queries are not showing up in the UI) so I am trying to understand the script better to understand my error.
I changed the post_type = ‘b2b-sales-dictionary’ as registered through Metaxbox.
From Metabox: register_post_type( ‘b2b-sales-dictionary’, $args );
Can I add function and filter all into one PHP snippet? I would think so. Any caveat with all the semicolons?
What does the second parameter in 10, 2 do?
$query_obj is an instance of the \Bricks\Query class object
Thanks a lot for the quick reply!
Yes, that was it!
At first I thought it wasn’t the solution, because I had saved it in WP Code Box 2 after your message and it did not work.
But then I saved it directly in the Bricks child theme and it worked. Many, many thanks! Now I can avoid 25 loops on the page
Just 2 more questions:
What is ‘as’ in this line? Is it optional?
$control_options[‘queryTypes’][“letters”] = esc_html__( “Letters”, ‘as’ );
How can I ensure that the quotation marks at the beginning of sources are ignored?
E.G.
B1 Source
“B2 Source”
B3 Source
EDIT: Found the answer to question 2 - you just have to change the function get_posts_starting_with_letter:
function get_posts_starting_with_letter( $letter ) {
global $wpdb;
return $wpdb->get_results( $wpdb->prepare("
SELECT * FROM {$wpdb->prefix}posts
WHERE post_type = 'post' // has to be adapted if CPT
AND post_status = 'publish'
AND (
post_title LIKE %s
OR post_title LIKE %s
)
ORDER BY post_title ASC
",
$letter . '%',
'"' . $letter . '%'
), OBJECT );
}