Upload
konstantin-kovshenin
View
4.666
Download
10
Embed Size (px)
Citation preview
WP_Query
is_home()is_single()is_page()
query_posts()
if ( have_posts() )while ( have_posts() )the_post();
query_posts( 'cat=-5' );$posts = get_posts( 'cat=-5' );$posts = new WP_Query( 'cat=-5' );
10 posts
10 posts 10 postscat = -5+
max_num_pages = 3
404.php index.phpmax_num_pages = 5
pre_get_posts
add_action( 'pre_get_posts', 'my_func' );function my_func( $query ) {$query->set( 'cat', '-5' );
}
$query->is_main_query()
add_action( 'pre_get_posts', 'my_func' );function my_func( $query ) {if ( $query->is_main_query() )$query->set( 'cat', '-5' );
}
add_action( 'pre_get_posts', 'my_func' );function my_func( $query ) {if ( $query->is_main_query() )if ( $query->is_search() )$query->set( 'post_type', 'post' );
}
add_action( 'pre_get_posts', 'my_func' );function my_func( $query ) {if ( $query->is_main_query() )if ( $query->is_search() )$query->set( 'posts_per_page', 30 );
}
add_action( 'pre_get_posts', 'my_func' );function my_func( $query ) {if ( $query->is_main_query() )if ( $query->is_home() )$query->set( 'post_type', array( 'post', 'book',
) );}
query_posts();$posts = get_posts();$posts = new WP_Query();
$popular = new WP_Query( 'cat=3' );while ( $popular->have_posts() ) {$popular->the_post();...
}
$popular = new WP_Query( 'cat=3' );while ( $popular->have_posts() ) {$popular->the_post();...
}
// Основной запросwhile ( have_posts() ) {the_post();...
}
// Основной запросwhile ( have_posts() ) {the_post();...
$category = get_the_category();$related = new WP_Query( 'cat=' ... );while ( $related->have_posts() ) {$related->the_post();...
}}
query_posts()
$wp_query
function have_posts() {global $wp_query;return $wp_query->have_posts();
}
$wp_query =& $wp_the_query;
function &query_posts( $query ) {...unset( $wp_query );$wp_query = new WP_Query();return $wp_query->query( $query );
}
function wp_reset_query() {...unset( $wp_query );$wp_query =& $wp_the_query;
}
$popular = new WP_Query( 'cat=3' );while ( $popular->have_posts() ) {$popular->the_post();...
}
// Основной запросwhile ( have_posts() ) {the_post();...
}
query_posts( 'cat=3' );while ( have_posts() ) {the_post();...
}wp_reset_query();
// Основной запросwhile ( have_posts() ) {the_post();...
}
pre_get_posts
Если нужно изменить основной запрос
new WP_Query; get_posts()
Если нужен вторичный запрос
query_posts()
Если нужна головная боль