What best practices should be followed when implementing a category filter in WordPress using PHP?
When implementing a category filter in WordPress using PHP, it is best practice to first check if the category parameter is set in the URL and then use it to filter the posts accordingly. This can be done by modifying the main query using the pre_get_posts hook and setting the category parameter based on the URL value.
function custom_category_filter( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
if ( is_category() ) {
$category = get_query_var( 'category_name' );
if ( $category ) {
$query->set( 'category_name', $category );
}
}
}
}
add_action( 'pre_get_posts', 'custom_category_filter' );
Related Questions
- What are the potential issues of storing both first and last names in the same database column in PHP?
- What is the best way to store and update visitor information, such as IP address and timestamp, in a PHP application?
- In welchen Fällen ist es sinnvoll, Zeit mit PHP hochzuzählen und zwischenzuspeichern, und wann sollten stattdessen Zeit- und Datumsfunktionen verwendet werden?