R
R
Rasul Gitinov2018-04-13 15:03:49
WordPress
Rasul Gitinov, 2018-04-13 15:03:49

How to make a universal function for displaying records?

There is a function that displays all records of a given type:

$args = array(
  'post_type'      => 'works',
  'numberposts'    => -1
);
$lastposts = get_posts( $args );
foreach( $lastposts as $post ){ setup_postdata($post);
  get_template_part( 'works-item' );
}
wp_reset_postdata();

How can I improve this function so that posts from this category are automatically displayed on the category page?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Max Medar, 2018-04-13
@raselgit

Something like this (I wrote from memory, so errors are possible):

$term      = get_queried_object();
$term_slug = $term->slug;
$_posts    = new WP_Query( array(
  'post_type'      => 'works',
  'posts_per_page' => 10,
  'tax_query'      => array(
    array(
      'taxonomy' => 'category', // или вашу таксономию
      'field'    => 'slug',
      'terms'    => $term_slug,
    ),
  ),
) );
if ( $_posts->have_posts() ) :
  while ( $_posts->have_posts() ) :
    $_posts->the_post();
                get_template_part( 'works-item' );
  endwhile;
endif;
wp_reset_postdata();

S
Sergey Gerasimov, 2018-04-13
@mrTeo

By default, 'category' => 0 is passed to the function, so add the optional parameter $category = 0 to your function, and set the value to your array of arguments:
$args['category'] = $category;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question