Filter WordPress Loop

1

How can I filter the loop in WordPress? I need to create multiple loop with different filters. Example: Extract the last post from category x.

    
asked by anonymous 15.07.2017 / 18:56

2 answers

2

It's not very clear what you want. The loop is just an iteration over a set of posts coming from a query:

if( have_posts() ) {
    while( have_posts() ) {
        the_post();
    }
}

In the case of the "original" loops of each page, this query is done by the core and the object is stored in the global $wp_query .

If what you want is not to display the last post of each page you can within the loop skip that iteration:

if( have_posts() ) {
    while( have_posts() ) {
        the_post();

        // pula o último post da página atual
        if( $wp_query->current_post + 1 === $wp_query->post_count ) {
            continue;
        } 
    }
}

Now if you want to remove an X post from the list of posts before running the loop, you can use the strong > pre_get_posts for this.

    
16.07.2017 / 17:15
1

To query the Wordpress database, use the WP_Query class. If you want the last post, eg:

$args = array( 'posts_per_page' => 1 ); $query = new WP_Query( $args );

You can use several parameters for the query as "author" or "category", and sort by "oderby".

See the full doc: link

    
16.07.2017 / 20:15