【问题标题】:Get post from CPT with same categoryname as the title从 CPT 获取与标题相同类别名称的帖子
【发布时间】:2016-01-19 12:54:37
【问题描述】:

我正在处理一个页面,我想在该页面上显示与帖子标题具有相同类别名称的类别中的帖子(自定义帖子类型)。

我还在学习,这就是为什么我希望你们能帮助我。 :)

我有什么:

  • CPT 命名为“鞋子”
  • CPT类:运动鞋、靴子、运动鞋
  • CPT 命名为“文章”
  • CPT 类别:运动鞋、靴子、运动鞋

在页面 ~/sneakers/ (来自 CPT 'shoes')我想显示来自类别 'sneakers' 的文章。

这是我目前所拥有的:

global $post;
$cat_ID = array();
$categories = get_the_category();
foreach($categories as $category) {
    array_push($cat_ID,$category->cat_ID);
}

$args = array(
    'orderby' => 'date',
    'order' => 'DESC',
    'post_type' => '[THE_TITLE]',
    'numberposts' => -1,
    'category__in' => $cat_ID
);

$cat_posts = get_posts($args);
if ($cat_posts) {
    foreach ($cat_posts as $cat_post) {
?>

<li><a href="<?php echo get_permalink($cat_post->ID); ?>"><?php echo $cat_post->post_title; ?></a></li>
    <?php
    }
}

【问题讨论】:

  • 这 'sneakers' ... 等等。它们是默认的“类别”分类法还是附加到 CPT 的自定义分类法?
  • 这些是默认分类法
  • 你能告诉我你想在哪里展示这篇文章 - 在页面模板上、在单个帖子模板上 http://site/shoes/shoe1、在类别模板上 http://site/category/sneakers/、在自定义帖子模板上 http://site/shoes/ 等. 因为您可以根据具体情况应用不同的解决方案。
  • 在名为 'sneakers' (site/sneakers) 的 single-shoes.php 上,我想显示来自 'sneakers' 类别的 'articles' 的所有帖子。这很难解释,但我正在尽力而为。感谢您帮助理解问题!

标签: php wordpress post categories


【解决方案1】:

好的,基于问题和以下解释:

我们在single-shoes.php 中显示单鞋信息。

我们要抓取并显示articles自定义帖子类型的信息,并且该文章必须属于特定类别,名称为=post_title

如果是这种情况,您可以执行以下操作:

  1. 我们希望我们的帖子来自 articles 自定义帖子类型,因此我们必须将 'post_type' =&gt; 'articles' 放入 $args 数组中。
  2. 我们希望返回的帖子属于类别,名称=post_title,因此我们必须将'category_name' =&gt; get_the_title() 放入$args

代码是:

    <?php

    $args = array(
        'orderby' => 'date',
        'order' => 'DESC',
        'post_type' => 'articles',
        'posts_per_page' => -1,
        'category_name' => get_the_title()
    );

    $articles = new WP_Query($args);

    if ( $articles->have_posts() ) :
        while( $articles->have_posts() ) : $articles->the_post(); ?>
            <li><a href="<?php the_permalink();?>"><?php the_title();?></a></li>
    <?php
        endwhile;
        endif;

        wp_reset_postdata();
    ?>

P.S. 我对类别名称仍然有些困惑,仍然不确定我是否正确理解了如何获取该值,但是,如果您可以获取该值,则上面提供了查询.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多