0

Is there any way to make this function also output another html template with the current selected category's data?

function load_cat_posts () {
$cat_id = absint($_REQUEST['cat']);
$args = array (
  'cat' => $cat_id,
  'posts_per_page' => 10,
  'order' => 'DESC'
);

global $post;
$posts = get_posts($args);

ob_start ();

foreach ( $posts as $post ) {
  setup_postdata( $post ); ?>

<?php get_template_part( 'partials/listing', 'post'); ?>

<?php } wp_reset_postdata();

$response = ob_get_contents();
ob_end_clean();

echo $response;
die(
}

1 Answer 1

1

Sure, the get_template_part() function can be called multiple times referencing to different files, so if you have a file in the partials/-folder, all you have to do is add a second function call here.

function load_cat_posts () {
    $cat_id = absint($_REQUEST['cat']);
    $args = array (
       'cat' => $cat_id,
       'posts_per_page' => 10,
       'order' => 'DESC'
   );

    global $post;
    $posts = get_posts($args);

    ob_start ();

    foreach ( $posts as $post ) {
        setup_postdata( $post ); ?>

        <?php get_template_part( 'partials/listing', 'post'); ?>
        <?php get_template_part( 'partials/listing', 'category'); ?>

    <?php } wp_reset_postdata();

    $response = ob_get_contents();
    ob_end_clean();

    echo $response;
    die(
}

This will include the file partials/listing-category.php.

Edit: I misunderstood your question! To display the data related to the category itself, you can use the get_category function to fetch an object containing the following attributes:

stdClass Object
(
    [term_id] => 85
    [name] => Category Name
    [slug] => category-name
    [term_group] => 0
    [term_taxonomy_id] => 85
    [taxonomy] => category
    [description] => 
    [parent] => 70
    [count] => 0
    [cat_ID] => 85
    [category_count] => 0
    [category_description] => 
    [cat_name] => Category Name
    [category_nicename] => category-name
    [category_parent] => 70
)

How you want to display this data is, of course, up to you.

function load_cat_posts () {
    $cat_id = absint($_REQUEST['cat']);
    $args = array (
       'cat' => $cat_id,
       'posts_per_page' => 10,
       'order' => 'DESC'
   );

   $category = get_category($cat_id);
   // ...
}
2
  • But would'nt that be within the foreach? I only want a single category picked out. Commented Dec 9, 2016 at 8:03
  • Hey, I think I misunderstood, see the updated answer.
    – Emil
    Commented Dec 9, 2016 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.