I want to display a page with ID=1149 in a particular place on another page. For that I’ve tried with this:
<div class="col-md-4 sidebarl">
<?php
$args = array(
'post_type' => 'page',
'post__in' => array(1149)
);
$query = new WP_Query($args);
while ($query->have_posts()) {
$query->the_post();
}
?>
</div>
But I am not getting anything, an empty page. Am I missing something?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I am not getting anything, an empty page. Am I missing something?
Yes, you are.
$query->the_post() does not display anything — it just moves the pointer/key in the posts array ($query->posts) to the next one, and setups the global post data ($GLOBALS['post']). So yes, in response to your answer, the_content() would be what you would use to display the content of the current post in the loop.
But actually, you could simply use the page_id parameter like so, to query a post of the page type and having a specific ID:
$args = array(
// Instead of using post_type and post__in, you could simply do:
'page_id' => 1149,
);
Also, you should call wp_reset_postdata() after your loop ends so that template tags (e.g. the_content() and the_title()) would use the main query’s current post again.
while ($query->have_posts()) {
$query->the_post();
the_content();
}
wp_reset_postdata();
And just so that you know, you could also use get_post() and setup_postdata() like so, without having to use the new WP_Query() way:
//global $post; // uncomment if necessary
$post = get_post( 1149 );
setup_postdata( $post );
the_title();
the_content();
// ... etc.
wp_reset_postdata();
Method 2
I am not sure if this is the correct answer, but I did it this way:
<div class="col-md-4 sidebarl">
<?php
$args = array(
'post_type' => 'page',
'post__in' => array(1149)
);
$query = new WP_Query($args);
while ($query->have_posts()) {
$query->the_post();
the_content();
}
?>
</div>
Method 3
You can try using the function “get_template_part()”. But to do this, you need to create a php-template for your current page and php-template for page 1149. Then, in your current page template, you include another template:
/** * Template Name: My current page template * Template Post Type: page */ <?php get_header(); ?> <?php the_content(); ?> ... <?php /* include template from page 1149 */ get_template_part( 'page-1149' ); ?> ...
https://developer.wordpress.org/reference/functions/get_template_part/
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0