JamalDols
JamalDols

Reputation: 510

WordPress get posts by category_name

I have a CPT in the single-portfolio.php file where I would like to list blog posts according to their category.

That is, the items I have in my CPT called Portfolio are "India", "USA", "Mexico", "Spain" and "Italy". The blog categories are exactly the same.

How can I get the news in the India page to return to me with the India category? And on the USA page the news with category USA...etc

<?php
$args = array(
  'post_type' => 'post',
  'posts_per_page' => 3,
  'category_name' => 'usa'
);
$query = new WP_Query( $args );
?>
<section class="news-slider">
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="slider-container">
          <div class="slick-slider">
            <?php while( $query->have_posts() ) : $query->the_post() ?>
            <div class="slick-slide" style="background-image:url(<?= the_post_thumbnail_url() ?>)">
              <a class="permalink" href="<?= the_permalink() ?>"></a>
              <div class="title-container">
                <span class="meta-category"><?php the_category( ', ' ); ?></span>
                <h3 class="title"><?php the_title() ?></h3>
              </div>
            </div>
            <?php endwhile; 
wp_reset_postdata(); ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

Upvotes: 0

Views: 1632

Answers (1)

disinfor
disinfor

Reputation: 11558

If I understood your question, you are trying to show regular Posts on your CPT post where the name of the CPT Post is the same as the posts category name.

If that's the case you can do this (new lines are commented):

<?php

// Get the post object;
global $post;
// Get the post_name (e.g. slug) of the post
$slug = $post->post_name;
// As long as the slug of your CPT post is the same as the slug of your post category, this works.

$args = array(
  'post_type' => 'post',
  'posts_per_page' => 3,
  // Use the $slug variable here.
  'category_name' => $slug,
);
$query = new WP_Query( $args );
?>
<section class="news-slider">
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="slider-container">
          <div class="slick-slider">
            <?php while( $query->have_posts() ) : $query->the_post() ?>
            <div class="slick-slide" style="background-image:url(<?= the_post_thumbnail_url() ?>)">
              <a class="permalink" href="<?= the_permalink() ?>"></a>
              <div class="title-container">
                <span class="meta-category"><?php the_category( ', ' ); ?></span>
                <h3 class="title"><?php the_title() ?></h3>
              </div>
            </div>
            <?php endwhile; 
wp_reset_postdata(); ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

Upvotes: 1

Related Questions