2012-02-22 36 views
0

我使用jcart http://conceptlogic.com/jcart/在wordpress中創建一些購物車功能。Wordpress + PHP:在另一個函數中使用帶in_array的數組變量

我想在我的functions.php文件中的另一個函數內訪問一個jcart函數。

foreach($jcart->get_contents() as $item) { 
    $psitems[] = $item['id']; 
} 

此代碼工作正常上的functions.php本身或page--它創建$psitems陣列,所以我可以檢查,如果該數組包含特定值的任何模板。現在

,下面的函數中:

function gallery_shortcode_fancybox($attr) { ... 

我有以下幾點:

foreach($jcart->get_contents() as $item) { 
    $psitems[] = $item['id']; 
} 

foreach ($attachments as $id => $attachment) { 
    $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_image($id, 'full', false, false) : wp_get_attachment_image($id, 'full', true, false); 

    $output .= "<div class='property'>"; 
    $output .= "$link"; 
    $output .= ' 
     <div class="property-details"> 
      <div class="property-details-inner"> 

       <form method="post" action="" class="jcart"> 
        <fieldset> 
         <input type="hidden" name="jcartToken" value="' . $_SESSION['jcartToken'] . '" /> 
         <input type="hidden" name="my-item-id" value="' . $id . '" /> 
         <input type="hidden" name="my-item-name" value="Photo #' . $id . '" /> 
         <input type="hidden" name="my-item-url" value="' . wp_get_attachment_url($id) . '" /> 
         <input type="hidden" name="my-item-qty" value="1" size="3" />'; 

    if(in_array($id,$psitems)) { 
     $output .= '<span class="action terminal pull-sheet">Image in Pullsheet</span>' 
    } else { 
     $output .=   '<input type="submit" name="my-add-button" value="Add to Pull Sheet" class="action terminal pull-sheet" />'; 
    } 
    $output .=    '</fieldset> 
       </form> 
      </div> <!-- property-details-inner --> 
     </div>'; 
    $output .= "</div>"; 
} 

return $output; 

我收到以下錯誤:

Call to a member function get_contents() on a non-object

如果我嘗試把原來的foreach($jcart->get_contents() as $item) { ...代碼在函數外面,我得到以下錯誤:

Warning: in_array() expects parameter 2 to be array, null given in... 

如何在函數內部訪問這個數組並避免這些錯誤?

謝謝!

回答

1

關於第一個錯誤,這意味着你必須初始化$ jcart。

至於警告,試試這個:使用初始化函數從原來的jcart.php腳本

$array = $jcart->get_contents(); 
foreach ($array as $item) ... 
+0

完美工作,感謝 – 2012-02-22 21:56:42

相關問題