WordPress.org

Ready to get started?Download WordPress

Forums

pre_get_posts with parameters (1 post)

  1. Gemfruit
    Member
    Posted 1 year ago #

    I'm currently in the middle of switching from query_posts to pre_get_posts functionality, as it's the proper way to go about it. When I used query_posts, I would have an array of conditions, for posts per page, order by, etc. I can't seem to figure out how to do this with pre_get_posts, syntax-wise that is. Before I just did this:

    $args = array(
    	'category_name' => '!featured',
    	'offset' => 2,
    	'posts_per_page' => 2,
    );
    
    query_posts($args);

    Since pre_get_posts is a hook, and not a function call, I can't just pass $args as a parameter. This is the code I currently have (different page, same idea). In functions.php:

    /**
    * Change posts per page
    */
    function change_post_per_page( $query ) {
    	if ( $query->is_main_query() && $query->is_home() ) {
    	$args = array(
    		'category_name' => 'featured',
    		'offset' => 2,
    		'posts_per_page' => 2,
    	);
    
    	$query->set( 'args', $args );
    	return $query;
    	}
    }
    add_action('pre_get_posts', 'change_post_per_page', 1);

    Logically, I'm trying to make the posts on my front page have an offset of 2, only display posts from my featured category, and only show 2 posts. It's essentially the same as when I did query_posts, but I don't know how to make pre_get_posts use these conditions. How do I go about this?

Topic Closed

This topic has been closed to new replies.

About this Topic