Here is one way… split the AJAX function thusly:
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
$cat_id = $_POST[ 'cat' ];
echo load_cat_posts($cat_id);
die(1);
}
function load_cat_posts ($cat_id) {
$args = array (
'cat' => $cat_id,
'posts_per_page' => 10
);
$posts = get_posts( $args );
global $post;
ob_start ();
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<div id="post-<?php echo $post->ID; ?>" <?php post_class(); ?>>
<div class="article">
<div class="article__thumbnail"><?php the_post_thumbnail();
?></div>
<div class="article__content">
<div class="article__header"><?php the_title(); ?></div>
<div class="article__brief"><?php
the_field('post_excerpt'); ?></div>
<div class="article__link"><?php the_content(); ?></div>
</div>
</div>
</div>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
return $response;
}
And in the template, add a line to get the first subcategory in loop and call the split function directly:
<?php //Best Practices ?>
<div class="tabs__content" id="best-practices">
<nav class="category-group">
<?php $categories = get_categories(array('child_of' => 4));
?>
<ul class="filter">
<?php $firstsubcat=""; // clear just in case
foreach($categories as $cat) {
// to grab the first subcategory
if ($firstsubcat == '') {$firstsubcat = $cat->term_id;} ?>
<li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" href="#"><?php echo $cat->name; ?></a></li>
<?php } ?>
</ul>
</nav>
// call the function directly
<div class="category-post-content"><?php echo load_cat_posts($firstsubcat); ?></div>
</div>
<?php //End Best Practices ?>
Alternatively, you could use jQuery to target and fake the click of the correct ID on document load to call the AJAX (replacing ’73’ with the subcat ID):
add_action('wp_footer','subcat_loader');
function subcat_loader() {
echo "<script>jQuery(document).ready(function($) {$('#cat-73').click();});</script>";
}