如何通过WordPress中的ID帖子获取类别名称



我想在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

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

内部循环您可以通过 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);

您需要像以下内容一样使用:

        $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);

最新更新