CATEGORY__NOT_IN和变量中的ID值

时间:2012-05-24 作者:user983248

如何从两个变量中设置category\\uu not\\u in的值。在我的示例中,我只是硬编码要排除的每个类别的ID,但是。。。如何从一些变量传递这些值?

    $category_a = get_category_by_slug(\'fbrt\');
    $category_b = get_category_by_slug(\'contact\');

    $exclude = get_the_ID();
    global $wp_query;
    $exclude = $wp_query->post->ID;
    $args = array(
        \'category_name\' => \'olympic-physique\',
        \'category__not_in\' => array(1, 2),
        \'posts_per_page\' => -1,
        \'orderby\' => \'title\', 
        \'order\' => \'DESC\'
);

1 个回复
SO网友:fuxia

get_category_by_slug() 返回类别对象或FALSE:

$cat1 = get_category_by_slug( \'cata\' );
print \'<pre>\' . htmlspecialchars( print_r( $cat1, TRUE ) ) . \'</pre>\';
结果:

stdClass Object
(
    [term_id] => 3
    [name] => Cat A
    [slug] => cata
    [term_group] => 0
    [term_taxonomy_id] => 3
    [taxonomy] => category
    [description] => 
    [parent] => 0
    [count] => 2
    [cat_ID] => 3
    [category_count] => 2
    [category_description] => 
    [cat_name] => Cat A
    [category_nicename] => cata
    [category_parent] => 0
)
因此,要获得一个ID数组,只需检查是否为每个slug获得了一个对象,然后添加term_id 到阵列:

$category__not_in = array();
$slugs            = array ( \'cata\', \'catdoesnotexist\' );
foreach ( $slugs as $slug )
{
    $cat = get_category_by_slug( $slug );
    $cat and $category__not_in[] = $cat->term_id;
}
$args = array (
    \'category__not_in\' => $category__not_in
);
与其硬编码脚本中的段塞,不如考虑添加term meta data 到类别。您将需要一个额外的查询来查找所有需要的术语,但您的脚本仍然可以重用。

结束

相关推荐

get_meta_data within a loop

我试图制作一个简单的小部件,它显示一个帖子列表,后面是每个帖子的一些元数据。这是我的代码:$eventdate 包含我需要检索的元数据。query_posts(\'\'); if (have_posts()) : echo \"<ul>\"; while (have_posts()) : the_post(); $eventdate = get_post_meta($post->ID, \'event-date