Filter Loop Wordpress

Asked

Viewed 164 times

1

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

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 saved in the global $wp_query.

If what you want is not to display the last post of each page you can inside 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 you run the loop, you can use the hook pre_get_posts for that reason.

1

To make queries to the Wordpress database use the Wp_query class. If you want the last post, for example:

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

You can use several parameters for the query such as "Author" or "Category", and sort by "oderby".

See the full doc: https://codex.wordpress.org/Class_Reference/WP_Query

Browser other questions tagged

You are not signed in. Login or sign up in order to post.