2014-02-09 77 views
0

以下代碼成功從我的Wordpress網站獲取category「工具」的所有Woocommerce產品。通過發帖獲取Wordpress數據

<?php 
$args = array(
'post_type' => 'product', 
'posts_per_page' => 100, 
'product_cat' => 'tools' 
); 
$loop = new WP_Query($args); 

while ($loop->have_posts()): 
$loop->the_post(); 
global $product; 
echo '<br /><a href="' . get_permalink() . '">' . woocommerce_get_product_thumbnail() . ' ' . the_title() . ' ' . the_content() . ' ' . get_post_meta(get_the_ID() , '_regular_price', true) . ' ' . get_post_meta(get_the_ID() , '_sale_price', true) . '</a>'; 
endwhile; 
wp_reset_query(); 
?> 

這工作正常,並返回在category「工具」中的所有產品。

但是我現在試圖通過其post id獲得產品。所以,而不是由categoryid。我想要獲得上述產品的所有數據,即標題,內容,圖像,銷售價格和正常價格。

我試了下面的代碼,但它沒有奏效。

<?php 
$args = array(
'post_type' => 'product', 
'posts_per_page' => 100, 
'ID' => '254' 
); 
$loop = new WP_Query($args); 

while ($loop->have_posts()): 
$loop->the_post(); 
global $product; 
echo '<br /><a href="' . get_permalink() . '">' . woocommerce_get_product_thumbnail() . ' ' . the_title() . ' ' . the_content() . ' ' . get_post_meta(get_the_ID() , '_regular_price', true) . ' ' . get_post_meta(get_the_ID() , '_sale_price', true) . '</a>'; 
endwhile; 
wp_reset_query(); 
?> 

如何獲得關於產品的所有信息,因爲我在第一段代碼(按類別)做到了,但它的ID呢?

因此,例如,在上面的代碼中,我試圖獲取產品上的數據,其帖子ID爲254.因此,有關該產品的信息。

我認爲我會在$args陣列中尋找ID而不是product_cat

請幫忙。

回答

1

試試這個(除非我讀了一些錯誤)和閱讀評論:

<? 
$args = array(
// 'post_type' => 'post', // what I used to test 
'post_type' => 'product', // what you need 
'posts_per_page' => 100, 
//'ID' => '254' // this would limit the results to ID 254 ONLY - so this is bad 
); 
// Generates the result set 
$loop = new WP_Query($args); 
//echo "<pre>\r\n"; // makes output easy to read 

// uncomment next line to see what else is available 
// var_dump($loop->posts); 

// Don't actually need to be in the loop to use the query result 
foreach ($loop->posts as $p){ 
    echo 'post_title :'.$p->post_title."<br />\r\n"; 
    echo 'post_name :'.$p->post_name."<br />\r\n"; 
    echo 'post_content :'.$p->post_content."<br />\r\n"; 
    echo 'ID :'.$p->ID."<br />\r\n"; 
} 

使用型「帖子」他的工作是我的地方WP沙箱。我相信Woo使用產品的自定義帖子類型(只是一個新名稱的帖子/頁面 - WP中的超級方便功能)。

祝你好運。

+0

實際上使用的是''p'=> 254',它的工作方式與@Ohgodwhy上面的註釋中的建議一致,並且遵循您的示例 – Tester

+0

酷。 Thx綠色複選標記。有很多方法可以做你想做的事情,但這是一個更簡單,相當簡單的方法,建立在你的例子之上。如果你知道帖子ID是「254」,你可以跳過所有其他的籃筐。該ID在WP系統中是唯一的。其他過濾器有助於保證該帖子具有「產品」質量。在使用中有兩個注意事項:1 - 在循環中或其他查詢周圍,這可能會變得不可靠(需要重置過濾器/查詢),2 - 我建議添加一個過濾爲「發佈」,所以你不會得到草稿/等泄漏。吉爾德運氣。 –

0

'orderby'=> 'id'添加到您的wp查詢文章中,它會正常工作,祝您好運。

+1

但是'ID'確實是一個有效的索引?不是'p'還是'page_id'? – Ohgodwhy

+0

所以你的意思是'$ args = array( 'post_type'=>'product', 'posts_per_page'=> 100, 'orderby'=> 254 );'....這會返回數據產品ID爲254? – Tester

+0

我認爲你可以使用post_id ='wanted_post_id'在查詢後將工作正常 –