Wordpress - how to get current category name inside functions.php?

Viewed 31

how to get the current category name of the page inside functions.php? this is for adding a load more functionality based on a category per page.

this is what my current code looks like

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');
1 Answers

Are you looking for something like this?

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