Get posts by term id custom query

<?php
// Define the term ID you want to retrieve posts for.
$term_id = 42; // Replace with your desired term ID.
$taxonomy = 'your_taxonomy_slug';
$post_type = 'post_type_name';

// Create a custom WP_Query to retrieve posts with the specified term.
$args = array(
    'post_type' => $post_type,  // Replace with your custom post type if needed.
    'tax_query' => array(
        array(
            'taxonomy' => $taxonomy,  // Replace with your custom taxonomy name.
            'field'    => 'term_id',
            'terms'    => $term_id,
        ),
    ),
);

$query = new WP_Query($args);

// Check if there are posts found with the specified term.
if ($query->have_posts()) {
    while ($query->have_posts()) { $query->the_post();

        // Output your post content here.
        the_title();
        the_content();

    }

    // Restore original post data.
    wp_reset_postdata();

}else{
    // No posts found with the specified term.
    echo 'No posts found with the term ID: ' . $term_id;

}
?>