Here’s an example how you could use your first code in the second one. In my code I also took the liberty to suggest one way of making your code more clear and easier to read by splitting the code into separate functions.
// add the following helper functions to functions.php
function travel_trip_type_image_url( int $term_id ) {
$img_id = get_term_meta( $term_id, 'wp_travel_trip_type_image_id', true );
return ( $img_id && is_int($img_id) ) ? wp_get_attachment_url( $img_id ) : '';
}
function travel_location_terms() {
$terms = get_terms( array(
'taxonomy' => 'travel_locations',
'hide_empty' => false,
'parent' => 0
) );
return ( $terms && ! is_wp_error($terms) ) ? $terms : array();
}
function itineraries_query( string $term ) {
$args = array(
'post_type' => 'itineraries',
'tax_query' => array(
array(
'taxonomy' => 'travel_locations',
'field' => 'slug',
'terms' => $term,
),
),
);
return new WP_Query($args);
}
function itineraries_loop( WP_Query $query ) {
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
the_title('<h2>','</h2>');
// use get_template_part( 'your-post-entry-template' );
// or write html markup here
}
wp_reset_postdata();
}
}
function travel_type_header( WP_Term $term ) {
if ( $term_img_url = travel_trip_type_image_url( $term->term_id ) ) {
// modify html output as needed
printf(
'<a href="https://wordpress.stackexchange.com/questions/352682/%s"><img src="https://wordpress.stackexchange.com/questions/352682/%s" alt="https://wordpress.stackexchange.com/questions/352682/%s"></a>',
esc_url( get_term_link( $term ) ),
esc_url( $term_img_url ),
esc_attr( $term->name )
);
}
}
// use in some template file
foreach ( travel_location_terms() as $travel_location ) {
travel_type_header( $travel_location );
itineraries_loop( itineraries_query( $travel_location->slug ) );
}
But if you don’t want to use the suggested split, then just put your first code between the foreach
and $term_link
lines.
To use this code you need to
- check and, if needed, update the meta key used in
travel_trip_type_image_url()
, - check and, if needed, update
taxonomy
andpost type
names used in code, - update the loop entry html output inside
itineraries_loop()
to your liking, - update the term header html output inside
travel_type_header()
to your liking, - have terms and post in your custom taxonomy and post type.