menu

arrow_back How do I check a post for tags in WordPress?

by
1 vote
Can you tell me how to check the current post for tags and, if they are, with the same (!) tags display similar posts. Now I'm displaying posts either in a particular category or with a precisely defined tag, for example:
<?php
$arg = array (
'tag__in' => 166, // выводить посты, имеющие такой тег
'posts_per_page' => 3, // сколько постов выводить
'orderby' => rand // рандомно
);
?>

2 Answers

by
 
Best answer
0 votes
// проверяем наличие тегов
if ( has_tag() ) {
$tags = wp_get_post_tags( get_the_ID() );

$tags_array = array();
foreach ( $tags as $key => $tag ) {
$tags_array[] = $tag->term_id; // собираем в массив
}

$args = array (
'post_type' => 'post',
'tag__in' => $tags_array, // получаем посты, имеющие такой же тег
'post__not_in' => array( get_the_ID() ), // исключаем текущий пост
'posts_per_page' => 3,
'orderby' => rand
);
} else {
// или получаем любые последние посты
$args = array (
'post_type' => 'post',
'posts_per_page' => 3,
'orderby' => date
);
}
by
0 votes
For some reason, this block of code does not work: I found a post with a new tag, (the tag is not anywhere else - only for this page), but no recent posts are not displayed, according to this code. What could be the problem?
Maybe because the page itself has a tag, it counts and is already ignored?
} else {
// или получаем любые последние посты
$args = array (
'post_type' => 'post',
'posts_per_page' => 3,
'orderby' => date
);