2015-01-15 32 views
-1

此代碼工作正常,並返回數組中的子類別,如果沒有任何小類不返回結果,IF is_array但是沒有按預期的wordpress子類別

$parentCatName = single_cat_title('',false); 
    $parentCatID = get_cat_ID($parentCatName); 
    $childCats = get_categories('child_of='.$parentCatID); 
    if(is_array($childCats)): 
     foreach($childCats as $child){ ?> 
    <?php query_posts('cat='.$child->term_id . '&posts_per_page=1'); 
     while(have_posts()): the_post(); $do_not_duplicate = $post->ID; ?> 
    <!-- POST CODE --> 
    <?php get_template_part('content', 'thumbs'); ?> 
    <!-- END POST CODE --> 
    <?php 
    endwhile; 
    wp_reset_query(); 
    } 
    endif; 
    ?> 

,如果我嘗試插入頭部的,如果是數組,它返回頭之後是否有子類或不即:

$parentCatName = single_cat_title('',false); 
$parentCatID = get_cat_ID($parentCatName); 
$childCats = get_categories('child_of='.$parentCatID); 
if(is_array($childCats)): 
echo 'Sub-Categories:' ; 
    foreach($childCats as $child){ ?> 
<?php query_posts('cat='.$child->term_id . '&posts_per_page=1'); 
    while(have_posts()): the_post(); $do_not_duplicate = $post->ID; ?> 
<!-- POST CODE --> 
<?php get_template_part('content', 'thumbs'); ?> 
<!-- END POST CODE --> 
<?php 
endwhile; 
wp_reset_query(); 
} 
endif; 
?> 

我解決它通過使用計數,但似乎笨拙對我來說,它應該有與數組一起工作。

<?php 
    $parentCatName = single_cat_title('',false); 
    $parentCatID = get_cat_ID($parentCatName); 
    $childCats = get_categories('child_of='.$parentCatID); 
    $countChild = count($childCats); 
    if ($countChild > 0) : echo '<h2>Sub-Categories:</h2>'; endif; 
    if(is_array($childCats)): 
     foreach($childCats as $child){ ?> 
    <?php query_posts('cat='.$child->term_id . '&posts_per_page=1'); 
     while(have_posts()): the_post(); $do_not_duplicate = $post->ID; ?> 
    <!-- POST CODE --> 
    <?php get_template_part('content', 'thumbs'); ?> 
    <!-- END POST CODE --> 
    <?php 
    endwhile; 
    wp_reset_query(); 
    } 
    endif; 
    ?> 
+0

什麼是你的問題? –

+0

如果'is_array'不工作,則'is_array'參數**不是數組**。 'var_dump($ childCats)'並檢查有什麼。 –

+1

你認爲一個數組可以爲空('count(...)== 0'),但仍然是一個數組('is_array(...)== true') – JCOC611

回答

1

正如評論問題不在於is_array()工作不說,問題是你是不是測試,以查看是否數組有任何行。

你這樣做的做法很好。沒有辦法做到這一點,不需要執行代碼。如果我這樣做,我可能會短路IF語句是這樣的:

if (is_array($childCats) and count($childCats)>0) { 
    ... 
} 

這樣,你跳過呼應了標題和打擾的foreach - 它現在是打與不執行,因爲數組是空。

HTH,

= C =

+0

謝謝卡爾我不停地敲我的頭,知道有更好的辦法.. :) – KatS

相關問題