aditya kumar
aditya kumar

Reputation: 3023

how to query only one post in wordpress widget

I am making a wordpress widget for my wordpress theme. In the widget I am trying to query only one post on the front-page.php I am using WP_query for that. But the problem is it is getting all the posts available. I have no idea how to fix this. Any suggestion will be helpful.

My code

public function widget($args, $instance) {
        $posts_args = array(
            'post_type'     => 'post',
            'post_per_page' => 1,

            'order'         => 'DESC'
        );
        $posts_query = new WP_Query($posts_args);

        echo $args['before_widget'];

            if($posts_query -> have_posts()):
                while($posts_query->have_posts()): $posts_query->the_post();
                    echo '<div class="widget-single-content" style="background-image: url('.get_the_post_thumbnail_url().')">';
                    echo '<div class="content-box">';
                    echo '<h1><span>"</span>'.get_the_title().'<span>"</span></h1>';
                    echo '<button class="readmore-btn text-captalize">
                    <a href="'.get_the_permalink().'">Read More</a></button>';
                    echo '</div>';
                    echo '</div>';

                endwhile;
            endif;
        echo $args['after_widget'];

        //Query

    }

Upvotes: 1

Views: 150

Answers (1)

Bilawal Awan
Bilawal Awan

Reputation: 432

$posts_args = array(
'post_type'      => 'post',
'numberposts' => 1, //this show how many posts to query from DB
'order'          => 'DESC',
'posts_per_page' => 1//this show how many posts display
);

posts_per_page

Upvotes: 2

Related Questions