Based on our chat in the comments here’s what I came with. Please advise if it works.
<?php
function primary_category_query_shortcode( $post, $atts ) {
//global $post; //Uncomment this global if it still doesn't work.
$atts = shortcode_atts( $defaults, $atts, 'primary_category_query' );
$my_meta = get_post_meta ( $post->ID, '_yoast_wpseo_primary_category', true );
// WP_Query arguments
$args = array (
'posts_per_page' => '4',
'meta_query' => array(
array(
'key' => '_yoast_wpseo_primary_category',
'value' => $my_meta
),
),
);
// All this would do is echo the ID of the category, correct? Just for testing?
//echo get_post_meta( get_the_ID(), '_yoast_wpseo_primary_category', true);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) { ?>
<section class="recent-posts clear">
<?php while ( $query->have_posts() ) : $query->the_post() ; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>>
<a href="https://wordpress.stackexchange.com/questions/364402/<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</article>
<?php endwhile; ?>
</section>
<?php } else {
echo 'Sorry, no more found.';
}
/* Restore original Post Data */
wp_reset_postdata();
}
?>
An explanation, what I suspect may be happening is that your attempt to get the Yoast Primary Category isn’t succeeding because, based on your var_dump() you’re not getting the post ID, it’s coming back as NULL
. So instead we’ll include the $post in the function()
and if that still doesn’t work, we’ll use global $post;
to make sure it’s being referenced. (That would be the second line, just uncomment it if it doesn’t work without it.)
I’ve also commented out the echo get_post_meta( get_the_ID(), '_yoast_wpseo_primary_category', true );
because that would, in theory, just echo out the ID number of the category. So I assumed you had that in there for testing.