Get Related Posts by Tag if Tag is Empty Get Posts by Category

I was calling the category id instead of the category name.

Here’s the code that by default tries using tags to bring in relevant posts, and if there are no posts by tags it’ll bring in posts using the same category. This code work in the single.php using the Ajax Load More wordpress plugin.

// Related Posts by tag
$terms = wp_get_post_tags($post->ID); // get current categories
$term_array = []; // Create empty category array

foreach( $terms as $term ) { // Loop founf categories
$term_array[] = $term->slug;
}
$query = '';

$args = array(
'posts_per_page'    => 1,
'post__not_in'  => $post->ID ,
'tag'               => implode(",", $term_array),
'post_type'         => 'post'
);
$related_posts = get_posts( $args );
if ($related_posts) { // Tags

$query = ' tag="'. implode(",", $term_array) .'"';

} else {

$categories = wp_get_post_categories($post->ID);

if($categories){
$categories_array = [];
foreach ($categories as $category) {
$cat = get_term( $category );
$categories_array[] = $cat->slug;
}
if(!empty($categories_array)){
$query = ' category="'. implode(",", $categories_array) .'"';
}
}

}

echo do_shortcode('[ajax_load_more'. $query .' post__not_in="' . $post->ID . '" post_type="post" posts_per_page="3" scroll="false" progress_bar="true" progress_bar_color="blue" images_loaded="true" button_label="Load More" css_classes="related-posts-container" button_loading_label="Loading More" container_type="div" ]');