Created
October 4, 2021 16:50
-
-
Save inetbiz/a0240f9550caf31557c94837049913c6 to your computer and use it in GitHub Desktop.
WordPress Shortcode to JSON-LD relatedLink from current category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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" ],