I am using this code, I wanted to display 5 post on loop on home page but without changing homepage setting to "latest posts".
...
<?php if ( is_home() ) {
$query = new WP_Query( 'cat=-3,-8' );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
} else {
...
?>
...
CodePudding user response:
Try out this code in your theme's functions.php.
Use the shortcode. [show_latest_posts]
in block editor Or <?php do_shortcode('[show_latest_posts]'); ?>
.
add_shortcode('show_latest_posts', 'zillion_latest_post_shortcode', 10);
function zillion_latest_post_shortcode(){
ob_start();
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page'=>5,
'order'=>'DESC',
'orderby'=>'ID',
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<h3>'.get_the_title().'</h3>';
echo '<div>'.get_the_content().'</div>';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
$contents = ob_get_clean();
return $contents;
}
CodePudding user response:
let one variable on line no 3 like $x=0; then enter while loop just check if condition if($X==5)then break ; also under of if condition use $x ; to increase when loop is running.