Yesterday i asked how it would be best to load all existing pages and their content on front page - to create single page layout. (Single page theme)
From the info on that page i created my own pre_get_posts hook in functions.php:
function show_all_pages_on_index( $query ) {
if ( (is_front_page() || is_home()) && $query->is_main_query() ) {
$query->set('post_type', 'page');
$query->set('parent', '0');
$query->set('post_status', 'publish');
$query->set('orderby', 'menu_order');
$query->set('order', 'ASC');
}
}
add_action( 'pre_get_posts', 'show_all_pages_on_index' );
If i put echo in the condition there it gets printed out, so i guess the hook works.
but this snippet in index.php still only prints out the initial blogpost that gets created with wordpress install: index.php:
$myposts = get_posts();
foreach( $myposts as $post ) : setup_postdata($post);
echo "<li><a href='". the_permalink() ."'>". the_title()."</a></li>";
endforeach;
wp_reset_postdata();
HTML:
http://localhost/hello-world/Hello world!<li><a href=''></a></li>
Edit - to show what worked in my case as single page layouyt:
functions.php:
function show_all_pages_on_index( $query ) {
if ( (is_front_page() || is_home()) && $query->is_main_query() ) {
$query->set('post_type', 'page');
$query->set('post_parent', 0);
$query->set('post_status', 'publish');
$query->set('orderby', 'menu_order');
$query->set('order', 'ASC');
}
}
add_action( 'pre_get_posts', 'show_all_pages_on_index' );
index.php:
while ( have_posts() ) {
the_post();
get_template_part( 'content', 'page' );
}
From there on wordpress'own tempate logic takes over using content-page.php or content.php, which pretty much means you can create different templates for subpages but you need to create them so that they actually fit into single page layout.
Thanks to everybody who contributed:)
get_posts()
. Use the main query only.if ( have_posts() ) …
.$query->set( 'posts_per_page', -1 );
.