akcjareferencjaod 2.0.0
pre_get_posts
Opis
Modyfikuje obiekt WP_Query przed wykonaniem zapytania. Pozwala zmieniać listę wpisów na stronie głównej, w archiwach i wynikach wyszukiwania.
Przykład użycia
add_action( 'pre_get_posts', ... )php
add_action( 'pre_get_posts', 'wpdocs_show_books_on_home' );
function wpdocs_show_books_on_home( $query ) {
// modyfikuj tylko główne zapytanie na stronie głównej
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'book' ) );
$query->set( 'posts_per_page', 10 );
}
}
add_action( 'pre_get_posts', 'wpdocs_show_books_on_home' );
function wpdocs_show_books_on_home( $query ) {
// modyfikuj tylko główne zapytanie na stronie głównej
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'book' ) );
$query->set( 'posts_per_page', 10 );
}
}Wskazówka — Zawsze sprawdzaj is_main_query(), inaczej zmienisz też widgety, menu i inne pomocnicze zapytania.
Note: If using conditional tags, use the method versions within the passed instance (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions like is_main_query() test against the global $wp_query instance, not the passed one.
Parametry
| Parametr | Typ | Opis |
|---|---|---|
$query | \WP_Query | The WP_Query instance (passed by reference). |
Wywołanie
Rejestracja callbackaphp
// rejestracja funkcji zwrotnej
add_action( 'pre_get_posts', 'twoja_funkcja' );
function twoja_funkcja($param_1) {
// Twój kod
}
// rejestracja funkcji zwrotnej
add_action( 'pre_get_posts', 'twoja_funkcja' );
function twoja_funkcja($param_1) {
// Twój kod
}Popularne w tej kategorii