0

我有一个类别查询,在我的类别查询中,我想通过查询的类别 ID(或名称或其他)获取产品(只有一个)我开始查询:

<?wpsc_start_category_query(array('category_group'=> get_option('wpsc_default_category'))); ?> 

然后尝试使用 get_posts() 函数获取产品:

$args = array(
 'post_type' => 'wpsc-product',
 'posts_per_page' => 1,
 'tax_query' => array(
  array(
  'taxonomy' => 'wpsc_product_category',
  'field' => 'id',
  'terms' => $aka
 )));
$cat1_posts = get_posts($args);

$aka 是:

$aka = '[wpsc_category_id]';

但是当我回显 $cat1_posts[0]->ID; 它只显示每个类别的最后一个产品 ID。问题是什么?仅回显 [wpsc_category_id] 效果很好。在过去的几天里,我尝试了一切。我会给你买饼干寻求帮助

我必须知道,我需要 foreach 或类似的东西

4

1 回答 1

1

您可以使用 get_terms() 函数。所以像这样的东西(未经测试)

<?php
    //for each category, show latest post
    $cat_args=array(
      'orderby' => 'name',
      'order' => 'ASC'
       );
    $categories = get_terms( 'wpsc_product_category');
      foreach($categories as $category) { 
        $args=array(
          'showposts' => 1,
          'post_type' => 'wpsc-product',
          'wpsc_product_category' => array($category->slug)
        );
        $posts=get_posts($args);
          if ($posts) {
            echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
            foreach($posts as $post) {
              setup_postdata($post); ?>
              <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
              <?php
            } // foreach($posts
          } // if ($posts
        } // foreach($categories
    ?>
于 2013-02-21T03:54:03.413 回答