John Davidson

php - Wordpress get post from tags

0 comments
Message:


(first of all i'm new with php)
i have a wordpress blog where i have written about some ppl and i added their names as tags in a costum taxonomy to avoid multi language field with polylang.
I was looking for a loop that allow to show, for every tag, the title of post where tag exist.
Example => post's name: "what a chef can do?" (tagged Alex P.)
result: -Alex P. "what a chef can do?" 05/10/2020 - "Tomatos in the world" 15/12/2020.
For every person(tag) i have to make an Accordion.


i've started to write code but i'm not looking for a solution and i'm getting lost.


<?php $tag_args = array(
'orderby' => 'title',
'order' => 'ASC'
);
?>
<ul id="Genre-List">
<li>DEFAULT</li>
<?php
$terms = get_terms(
array(
'taxonomy' => 'chef',
'hide_empty' => false,
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
print_r($terms);
foreach ( $terms as $term ) {

?>
<li><a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a></li>
<?php
}
}
?>

Thanks if anyone can help about this.. im really getting mad.



My Answer:
php
$tags = get_terms( array(
'taxonomy' => 'post_tag',
'hide_empty' => false,
) );

foreach ( $tags as $tag ) {
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $tag->slug,
),
),
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
echo '

' . $tag->name . '

';
echo '';
}

wp_reset_postdata();
}
?>


This code will retrieve all tags from the 'post_tag' taxonomy and then loop through each tag to display the title of posts that have that tag. It will display the tag name as a heading and then list the titles of the posts under that tag.

Rate this post

5 of 5 based on 8067 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us