Skip to content
All gists
Back to GitHub
Sign in
Sign up
Sign in
Sign up
{{ message }}
Instantly share code, notes, and snippets.
vanaf1979
/
related-posts-complete.php
Last active
Jan 12, 2021
Star
0
Fork
0
Star
Code
Revisions
3
Embed
What would you like to do?
Embed
Embed this gist in your website.
Share
Copy sharable link for this gist.
Clone via HTTPS
Clone with Git or checkout with SVN using the repository’s web address.
Learn more about clone URLs
Download ZIP
WordPress: Related posts with WP_Query.
https://since1979.dev/wordpress-related-posts-with-wp_query/
Raw
related-posts-complete.php
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
Show hidden characters
<?php
$
related_query
=
new
WP_Query
(
array
(
'post_type'
=>
'post'
,
'category__in'
=> wp_get_post_categories(get_the_ID()),
'post__not_in'
=>
array
(get_the_ID()),
'posts_per_page'
=>
3
,
'orderby'
=>
'date'
,
));
?>
<?php
if
(
$
related_query
->
have_posts
()) {
?>
<
div
class
="
related-posts-grid
"
>
<?php
while
(
$
related_query
->
have_posts
()) {
?>
<?php
$
related_query
->
the_post
();
?>
<
div
class
="
grid-item
"
>
<
a
href
="
<?php
the_permalink();
?>
"
>
<?php
the_post_thumbnail(
'post-thumb-small'
);
?>
</
a
>
<
h5
>
<
a
href
="
<?php
the_permalink();
?>
"
>
<?php
the_title();
?>
</
a
>
</
h5
>
</
div
>
<?php
}
?>
</
div
>
<?php
wp_reset_postdata();
?>
<?php
}
?>
<
style
>
.
related-posts-grid
{
display
:
grid;
grid-template-columns
:
1
fr
1
fr
1
fr
;
grid-gap
:
40
px
;
max-width
:
1000
px
;
margin
:
60
px
auto;
}
.
related-posts-grid
img
{
width
:
100
%
;
height
:
auto;
margin
:
0
0
10
px
0
;
}
.
related-posts-grid
h5
{
margin
:
0
;
}
.
related-posts-grid
h5
a
{
text-decoration
:
none;
}
</
style
>
Sign up for free
to join this conversation on GitHub
. Already have an account?
Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.