使用AJAX加载帖子和类别

时间:2016-12-06 作者:Jonas Vestergård Olsen

是否有任何方法可以使此函数同时输出另一个包含当前选定类别数据的html模板?

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 个回复
SO网友:Emil

当然,这个get_template_part() 函数可以引用不同的文件多次调用,因此如果partials/-文件夹中,只需在此处添加第二个函数调用。

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(
}
这将包括文件partials/listing-category.php.

编辑:我误解了你的问题要显示与类别本身相关的数据,可以使用get_category 函数获取包含以下属性的对象:

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
)
当然,如何显示这些数据取决于您。

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);
   // ...
}