Forums

Using Tags with Categories (4 posts)

  1. galbustein
    Member
    Posted 3 years ago #

    Hello all,

    I am writing a WordPress plugin and have successfully managed to limit the categories displayed throughout the site using the following code:

    public function postFilter($query) {
    
    	$displayCategories = "1,2,3,4";
    
    	$displayCategoriesString = implode(",", $displayCategories);
    
    	if ($query->is_tag) {
    
    		// FIXME: limit tagged post results to current locale 
    
    		// I tried using query_vars initially
    		# $query->query_vars['cat'] = $displayCategoriesString;
    		# $query->query_vars['tag'] = 'testtag';
    
    		// then I tried using $query->set
    		# $query->set('cat', $displayCategoriesString);
    		# $query->set('tag', array('testtag'));
    		# $query->set('tag__in', array('testtag'));
    
    		// uncomment next line to dump data
    		# echo "<pre>"; die(var_dump($query)); die;
    	} else {
    		$query->query_vars['cat'] = $displayCategoriesString;
    	}
    	return $query;
    }
    
    // this method is used inside a class
    add_action('pre_get_posts', array(&$this, 'postFilter'));

    So the $displayCategories array contains a list of all allowed categories and this is working fine for limiting posts to particular categories, but when I try to use it for finding "results tagged with" (using $query->is_tag above) it is never finding any results.

    Is this because of the way that tags and categories work together in the wordpress core? Or does anyone have any ideas on why this is happening?

    SMc

  2. galbustein
    Member
    Posted 3 years ago #

    Sorry, the

    $displayCategories = "1,2,3,4";

    should be

    $displayCategories = array ("1", "2", "3", "4");

  3. galbustein
    Member
    Posted 3 years ago #

    [bump]

    Been trying to no avail - It is strange as it works with feeds and posts but not categories.

    I can't find anything in the documentation about this so maybe it is worth a bug report?

  4. Mike Walker
    Member
    Posted 3 years ago #

    Dunno if this will help, but it worked for me:

    // Filter out all the posts tagged with "demo"
    add_filter('request', 'em_filter_request');
    function em_filter_request($params) {
        $params['tag__not_in'] = array(18);
        return $params;
    }

Topic Closed

This topic has been closed to new replies.

About this Topic