Skip to content

Instantly share code, notes, and snippets.

@inetbiz
Created October 4, 2021 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inetbiz/a0240f9550caf31557c94837049913c6 to your computer and use it in GitHub Desktop.
Save inetbiz/a0240f9550caf31557c94837049913c6 to your computer and use it in GitHub Desktop.
WordPress Shortcode to JSON-LD relatedLink from current category
// Add Shortcode
function jsonlink( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'numberposts' => '',
),
$atts,
'relatedLink'
);
$related = new WP_Query(
array(
'category__in' => wp_get_post_categories( $post->ID ),
'posts_per_page' => $atts,
'post__not_in' => array( $post->ID )
)
);
if( $related->have_posts() ) {
while( $related->have_posts() ) {
$related->the_post();
echo "relatedLink: [". json_encode($query->get_post_permalink() ."]";
}
wp_reset_postdata();
}
}
add_shortcode( 'relatedLink', 'jsonlink' );
@inetbiz
Copy link
Author

inetbiz commented Oct 4, 2021

Usage

[realtedLink numberposts=5]

Bugs

Line #24 echo "relatedLink: [". json_encode($query->get_post_permalink() ."]";
I'm not good at writing PHP.

Expected Outcome

"relatedLink": [ "https://example.com/category-slug/post-name1", "https://example.com/category-slug/post-name2", "https://example.com/category-slug/post-name3" ],

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment