Wordpress - 如何获取functions.php中的当前类别名称?

问题描述 投票:0回答:2

如何获取functions.php中页面当前的类别名称? 这是为了根据每页的类别添加加载更多功能。

这就是我当前的代码的样子

add_filter('query_vars', 'registering_custom_query_var');

function registering_custom_query_var($query_vars)
{
    $query_vars[] = 'id'; // Change it to your desired name
    return $query_vars;
}


function more_post_ajax() {

    global $wp_query;

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
    $category = get_category(get_query_var('cat')); 
  
    header("Content-Type: text/html");
  
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'category_name' => $category->name,
        'paged' => $page,
    );
  
    $loop = new WP_Query($args);
  
    $out = '';
  
    if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();
            $out .= '<div class="article_card"><div class="article_card__thumbnail">' . get_the_post_thumbnail() . '</div><div class="article_card__content"><h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h3><p class="body-small">' . wp_trim_words( get_the_excerpt(), 60 ) . '</p><a a href="' . get_the_permalink() . '"> Learn more →</a></div></div>';
        endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}
  
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
php wordpress wordpress-theming custom-wordpress-pages wordpress-gutenberg
2个回答
1
投票

您在寻找这样的东西吗?

<?php 
$post = get_post();
if ( $post ) {
  $categories = get_the_category( $post->ID );
  var_dump( $categories );
}

0
投票

使用以下内容:

get_queried_object()

这将返回类似这样的内容:

$page = get_queried_object();
echo '<pre>' . print_r($page, 1) . '</pre>';

结果:

WP_Term Object
(
    [term_id] => 279
    [name] => Shirts
    [slug] => shirts
    [term_group] => 0
    [term_taxonomy_id] => 279
    [taxonomy] => product_cat
    [description] => 
    [parent] => 277
    [count] => 54
    [filter] => raw
)

从这里,您可以使用以下内容:

echo $page->name;

获取类别名称:

Shirts

© www.soinside.com 2019 - 2024. All rights reserved.