<?php 
 
function themes_related_posts( $post_id, $post_type, $taxonomy, $related_count, $args = array() ) {
  $terms			= get_the_terms( $post_id, $taxonomy );
  if ( empty( $terms ) ) $terms = array();
  $term_list		= wp_list_pluck( $terms, 'slug' );
  $related_args		= array(
    'post_type'			=> $post_type,
    'posts_per_page'	=> $related_count,
    'post_status'		=> 'publish',
    'post__not_in'		=> array( $post_id ),
    'orderby'			=> 'rand',
    'tax_query'			=> array(
      array(
        'taxonomy'		=> $taxonomy,
        'field'			=> 'slug',
        'terms'			=> $term_list
      )
    )
  );
  return new WP_Query( $related_args );
}

function themes_related_posts_by_cat( $post_id, $post_type, $taxonomy, $r_count, $args = array() ) {    
    
	global $wpdb, $post, $opt_themes, $wp_query; 
    if (!is_single()) {
        return; // Only run on single post pages
    }
 
    $current_post_id = $post->ID;

    // Get the current post's categories
    $categories = get_the_category($current_post_id);
    if (empty($categories)) {
        return; // No categories assigned
    }

    // Assume the first category is the primary one (adjust if your posts have multiple)
    $primary_cat = $categories[0];
    
    // Get the parent category ID (0 if no parent)
    $parent_cat_id = $primary_cat->parent;
    
    // If no parent, fall back to the primary category itself
    if ($parent_cat_id == 0) {
        $parent_cat_id = $primary_cat->term_id;
    }

    // Query args: Posts in the parent category, exclude current post, limit to 3
    $args = array(
        'post_type'      => $post_type,
        'post__not_in'   => array($current_post_id),
        'posts_per_page' => $r_count, // Change as needed
        'cat'            => $parent_cat_id,
        'orderby'        => 'rand', // Randomize for variety (or use 'date' for recent)
    );
 
	return new WP_Query( $args );
}

function themes_related_devs( $post_id, $post_type, $taxonomy, $related_count, $args = array() ) {
  $terms			= get_the_terms( $post_id, $taxonomy );
  if ( empty( $terms ) ) $terms = array();
  $term_list		= wp_list_pluck( $terms, 'slug' );
  $related_args		= array(
    'post_type'			=> $post_type,
    'posts_per_page'	=> $related_count,
    'post_status'		=> 'publish',
    'post__not_in'		=> array( $post_id ),
    'orderby'			=> 'rand',
    'tax_query'			=> array(
      array(
        'taxonomy'		=> $taxonomy,
        'field'			=> 'slug',
        'terms'			=> $term_list
      )
    )
  );
  return new WP_Query( $related_args );
}
