0

I'm trying make my wordpress homepage to show only 2 blogpost. with different showing element. one of them is float-left and one is float-right. on native php it's easy to fetch result as array. and print them with $result[0] and $result[1].

But on wordpress idk to do that. maybe u guys can help me to guide any documentation. like wp_query or etc. and dont forget to give me an example line of code

*sorry my english was so bad. I hope you guys read this and reply to this.

My current line of code is:

$blogposts = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => 2,
    ));
while ($blogposts->have_posts()) {
        $blogposts->the_post();

}
Ahmet Zeybek
  • 1,196
  • 1
  • 13
  • 24
Ariakun
  • 23
  • 5

1 Answers1

0

If you're more comfortable with arrays, you can always make use of the get_posts() function instead, which takes arguments (almost) exactly like the WP_Query() Class. get_posts() actually makes use of WP_Query as well.

That said, your code wouldn't be all that difficult to modify with "native PHP" as you mentioned. It's just a while loop instead of a foreach loop, both of which are similar control structures.

All you have to do is add a counter variable and increment it after each pass using the increment operator: ++;

Here's a quick code sample for you:

$args = array(
    'posts_per_page' => 2,
);

$query = new WP_Query( $args );

if( $query->have_posts() ){
    $count = 0; // Start a Counter

    while( $query->have_posts() ){
        $query->the_post();

        printf( '<div class="post float-%s">', ($count++ % 2 == 0) ? 'left' : 'right' ); // If counter is odd: "left", even: "right"
            printf( '<h4 class="post-title">%s</h4>', get_the_title() );
            the_content();
        echo '</div>';
    }
} else {
    echo 'No Posts Found.';
}

A couple of things:

  • I moved the $args array to its own variable. Some queries can get pretty complex, having them as a designated variable can improve long-term maintainability.

  • You also don't need the post_type argument if you just want post, because that's the default value.

  • I added an if clause, so if your posts ever disappeared or you moved this code, there'd be a fall back for "nothing found".

  • I used a bit of a complex Ternary Operator in the post class. I increment it there so we don't need another line to increment the $count later, and it removes the need for a multi-line "if/else" to determine left or right.

  • Beyond that, you didn't provide a markup structure so I made use of a the_ and get_the_ function if you're unaware of the difference.

Xhynk
  • 13,513
  • 8
  • 32
  • 69
  • omg, i never thinking about that. This is a very good idea. when I add $count to my if statement. thanks, problem solved.. :) – Ariakun Jan 16 '20 at 15:28