WordPress.org

Ready to get started?Download WordPress

Forums

Query Set Issues (3 posts)

  1. Gemfruit
    Member
    Posted 10 months ago #

    I'm using the pre_get_posts hook, and trying to define which categories are displayed on a specific page. I created a function in functions.php that checks to see if I'm on that page, but I can't get the query to list the posts from an array of categories.

    function games_category( $query ) {
    
    	$categories = array ('random', 'games');
    
    	if ($query->is_main_query() && is_category($categories)) {
    		echo("This is being read"); //This was read in my test
    
    		$args = array(
    		     'category_name' => 'articles', //can't take array, want to use $categories, threw an error
    			);
    
    			//$query->set( 'args', $args ); //this did nothing
    			$query->query_vars['category_name'] = 'random';  //can't take array, but setting a single category works
    			return $query;
    		}
    	}
    	add_action( 'pre_get_posts', 'games_category' );

    Essentially, I don't understand the query->set portion of this code. I was using 'args', $args at one point, but I don't understand that, and I believe I found that on a forum. It currently did nothing, it simply displayed the default posts of the category, and not what I was specifying in $args.

    I just want to set the query 'category_name' to an array of categories, but can't figure out the syntax, or how to go about it best. The 'args $args route would be better, as I could set other properties, but one step at a time.

    Any ideas what I'm doing wrong?

  2. vtxyzzy
    Member
    Posted 10 months ago #

    Looking at this Category Parameters section seems to imply that category__name can take a comma separated string of slugs. Worth a try.

  3. Aahan Krish
    Member
    Posted 8 months ago #

Reply

You must log in to post.

About this Topic