如何在wordpress中通过id post获取类别名称

时间:2016-12-07 04:36:36

标签: php wordpress woocommerce

我想在wordpress中创建一个api,然后我创建一个这样的代码:

case 'product_onsale':
	$response = array();
	$args = array(
		'post_type' => 'product',
		'posts_per_page' => 30,
		'meta_query' => array(
			'relation' => 'OR',
			array( // Simple products type
				'key' => '_sale_price',
				'value' => 0,
				'compare' => '>',
				'type' => 'numeric'
			) ,
			array( // Variable products type
				'key' => '_min_variation_sale_price',
				'value' => 0,
				'compare' => '>',
				'type' => 'numeric'
			)
		)
	);
	$loop = new WP_Query($args);
	if ($loop->have_posts()):
		$meta = array(
			"api_status" => 1,
			"api_message" => "success",
			"result" => ""
		);
		$meta = array();
		while ($loop->have_posts()):
			$loop->the_post();
			$meta['result'][] = array(
				"id" => get_the_ID() ,
				"post_name" => get_the_title() ,
				"stock_status" => get_post_meta(get_the_ID() , '_stock_status', true) ,
				"price" => get_post_meta(get_the_ID() , '_price', true) ,
				"regular_price" => get_post_meta(get_the_ID() , '_regular_price', true) ,
				"sale_price" => get_post_meta(get_the_ID() , '_sale_price', true) ,
				"Stock_status" => get_post_meta(get_the_ID() , '_stock_status', true) ,
				"category" => the_category() ,
			endwhile;
		endif;
		echo json_encode($meta);
		break;

然后在那里,我想在我的结果中按帖子ID显示类别,我尝试添加

  

the_category

我需要在代码中进行哪些改进,以便它可以像我想要的那样工作?

2 个答案:

答案 0 :(得分:0)

你需要使用如下:

        $meta = array();
        while ($loop->have_posts()):
            $loop->the_post();
            $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );
            $meta['result'][] = array(
                "id" => get_the_ID() ,
                "post_name" => get_the_title() ,
                "stock_status" => get_post_meta(get_the_ID() , '_stock_status', true) ,
                "price" => get_post_meta(get_the_ID() , '_price', true) ,
                "regular_price" => get_post_meta(get_the_ID() , '_regular_price', true) ,
                "sale_price" => get_post_meta(get_the_ID() , '_sale_price', true) ,
                "Stock_status" => get_post_meta(get_the_ID() , '_stock_status', true) ,
                "category" => $product_cats);
            endwhile;
        endif;
        echo json_encode($meta);

答案 1 :(得分:0)

在while循环中,您可以按get_the_category()

获取该帖子的类别

$CatObj = get_the_category();

这将为您提供变量$CatObj中的类别数组。

运行一个简单的foreach循环来获取数组$catnames中的所有类别。

$catnames = array();
        foreach ($CatObj as $key => $value) {
            $catnames[] = $value->name;
        }

现在通过使用php的implode函数,在while循环中显示逗号分隔的类别,如下所示:

echo implode(', ', $catnames);