Get all terms in a custom Wordpress Query? - php

I know how to get all of the Wordpress terms, but I need a "filtered" down version of the results. Is it possible to get all of the terms that are in the result of a Wordpress query? I have this query here:
<?php
$args=array(
'post_type' => 'gw_activity',
'post_status' => 'publish',
'orderby' => 'date',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'activity_category',
'value' => 'mindful_life',
'compare' => '='
)
),
'posts_per_page' => 10
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$all_terms = array();
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php $terms = wp_get_post_terms( $my_query->post->ID, array( 'gw_activity_tag' ) ); ?>
<?php
foreach ( $terms as $term ) {
$all_terms[] = $term->name;
}
?>
<?php endwhile; }
wp_reset_query();
?>
<!-- End Custom Query -->
<?php
$unique_terms = array_unique( $all_terms );
$result = array_unique($unique_terms);
foreach ($result as $value) {
echo $value . '<br />';
}
?>
But I can't figure how to run the query & put a "Where" clause in it, like you can with MySQL. Any help / suggestion or even point me in the right direction would be greatly appreciated. I'm stuck

Check this function: wp_get_post_terms()
Assuming your post supports two taxonomies called tax_a and tax_b, you can try something like this, exactly where you wrote your comment:
<?php $terms = wp_get_post_terms( $query->post->ID, array( 'tax_a', 'tax_b' ) ); ?>
<?php foreach ( $terms as $term ) : ?>
<p><?php echo $term->taxonomy; ?>: <?php echo $term->name; ?></p>
<?php endforeach; ?>
This will print all the terms for each post retrieved by the query.
EDIT
If what you want is all the terms in all the posts retrieved by the query, you can store the values in an array and then use a function like array_unique(), like this:
$all_terms = array();
foreach ( $terms as $term ) {
$all_terms[] = $term->name;
}
// ... and outside the WHILE loop
$result = array_unique( $all_terms );
foreach ( $result as $term ) {
echo $term . '<br/>;
}

Related

ACF Repeater random order all fields

Looking to output a Advanced Custom Fields repeater in random order. I have a repeater field "profiles" containing 5 "profile" post objects.
My code today is:
// Randomize and shuffle the rows
$rows = get_sub_field('profiles');
shuffle($rows);
$rand_repeater_fields = array_rand( $rows , 4 ); ?>
<?php if( have_rows('profiles') ):
$stage_index = 0; ?>
<?php while ( have_rows('profiles') ) : the_row();
// print rows only if in array
if (in_array(get_row_index() - 1, $rand_repeater_fields)) { ?>
<?php $post_object = get_sub_field('profile'); //row w. post object start
if( $post_object ):
$post = $post_object;
setup_postdata( $post ); ?>
<?php the_permalink();?>
<?php wp_reset_postdata(); ?>
<?php endif; ?> //row w. post object end
<?php // increment index
$stage_index++;
} ?>
<?php endwhile; ?>
This code successfully output 4 of 5 rows in random order, which means that it almost works as I wish.
How do I update this snippet to output ALL fields of the repeater fields, in random order, even if they are 3 or 10 in total?
Thankful for any suggestions!
<?php
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'rand',
'meta_query' => array(
array(
'key' => 'profiles',
'compare' => 'EXISTS'
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$profiles = get_field('profiles');
if( $profiles ):
foreach( $profiles as $profile ):
echo '<div class="profile">';
echo '<h2>' . $profile['profile'] . '</h2>';
echo '</div>';
endforeach;
endif;
}
}
wp_reset_postdata();
?>

Display html for selected products or products categories

Hello I am using advanced custom field plugin for displaying some html only for selected products or only for products for selected categories in option page with relationship picker. My result instead is displaying for all products. This is what I have:
$products = get_field('products_picker', 'option');
$categories = get_field('categories_picker', 'option');
$prom_img = get_field('prom_img', 'option');
if ( $products ) {
foreach( $products as $p ):
if( $post->ID == $p->ID ):
<img src="<?php echo $prom_img['url']; ?>">
endif;
endforeach;
}
if ( $categories ) {
foreach( $categories as $term ):
$category = get_term( $term );
if( has_term( $category, 'product_cat', $post )) {
?>
<img src="<?php echo $prom_img['url']; ?>">
endif;
endforeach;
}
In similar cases I create a new wp_query passing the array with the post IDs like below:
$posts = get_field('products_picker', 'option');
$new_query = new WP_Query(array(
'post_type' => array('post'),
'post__in' => $posts,
'orderby' => 'post__in',
));
if ( $new_query->have_posts() ) :
while ( $new_query->have_posts() ) : $new_query->the_post();
//your code here
endwhile;
endif;
For the categories part you can use a query like this:
$categories = get_field('categories_picker', 'option');
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories[0]
)
)
);
$cat_query = new WP_Query($args);
I've not tested this in Wordpress, but the first thing I would try is to rename the $post variable that pulls the ACF field to '$posts' (plural).
Then change the foreach loop as follows.
$posts = get_field('products_picker', 'option');
$prom_img = get_field('prom_img', 'option');
if ( $posts ) {
foreach( $posts as $post ):
setup_postdata($post);
$sales_html = '<div class="promo-badge test"><img src=' . $prom_img['url'] . '></div>';
wp_reset_postdata();
endforeach;
}
That might fix it... I'm not sure you won't need to turn the foreach loop into an actual Wordpress style loop (the type with while(have_posts()): the_post(); etc. like in #kaize answer below)
See here if my solution didn't help: https://www.advancedcustomfields.com/resources/querying-relationship-fields/

WordPress (nested) Post query, loop per category and then per ACF

I'll first tell my goal, than what I came up with so far.
My goal:
I've made a shortcode that works with VisualComposer.
In VC I can check the categories for this posttype.
The goal of the short code is to fist select and sort the posts per selected category.
Second, to divide and sort per ACF. Say, "custom_field_1"
Thirdly and last. to sort the posts alphabetically on "custom_field_2" and then on "custom_field_3".
Example:
Cat 1
red
post 1
post 2
blue
post 3
post 4
Cat 2
red
post 5
post 6
blue
post 7
post 8
Al right. I've tried it out myself first. And this is my code so far:
<?php
function productlist_sc($atts){?>
<?php
global $post;
$categories_array = array();
$thecategories = get_categories();
foreach( $thecategories as $category ){
$categories_array[] = $category->slug;
}
if($atts[ 'category' ]){
$atts[ 'category' ] = explode( ",", $atts[ 'category' ] );
}
//collect values, combining passed in values and defaults
$values = shortcode_atts(array(
'category' => ''
),$atts);
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0,
'slug' => $values['category']
) );
$current = get_the_ID($post->ID);
$cargs = array(
//'child_of' => 0,
'orderby' => 'name',
'parent' => 0,
'order' => 'ASC',
'hide_empty' => 1
//'taxonomy' => 'category', //change this to any taxonomy
);
// first sort all selected posts per category
foreach ( $categories as $tax ) :
// List posts by the terms for a custom taxonomy of any post type
$args = array(
'post_type' => 'products',
'orderby' => 'ASC',
'posts_per_page'=>-1,
'category_name' => $tax->slug
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<h2>Internal ID: <?php echo $tax->name; ?></h2><?php
// second sort all selected posts per custom_field_1
$mykey_values = get_post_custom_values( 'custom_field_1' );
foreach ( $mykey_values as $key => $value ) :
?><h3><?php the_field('custom_field_1'); ?></h3>
<div class="rtt_prod_table">
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div>
<?php if( get_field('custom_field_1') || get_field('custom_field_2') || get_field('custom_field_3') ): ?>
<ul>
<?php if( get_field('custom_field_2') ): ?>
<li>
<?php the_field('custom_field_2'); ?>
</li>
<?php endif; ?>
<?php if( get_field('custom_field_3') ): ?>
<li>
<?php the_field('custom_field_3'); ?>
</li>
<?php endif; ?>
</ul>
<?php endif; ?>
</div>
</div>
</div>
<?php endwhile; ?> <!-- end of the loop -->
<div><!-- end .accord-content -->
</div>
<?php wp_reset_postdata();
endforeach; // custom_field_1
?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<?php
endforeach; /* end $tax */ ?>
<?php
}
Alright, so I've found the answer.
I'll post it here for anyone looking for a solution. :)
Steps:
needed an array with all the unique values within "field 1"
ran an post query for each post, grabbed the value of "field 1" and put in an array
filtered all the duplicates
alphabetized the array
run a foreach in the array:
This is the code I added to the code above
$stack = array();
// query
$args = array(
'post_type' => 'products',
'orderby' => 'ASC',
'posts_per_page'=>-1,
'category_name' => $tax->slug
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
if( get_field('custom_field_1') ):
$stack[] = get_field('custom_field_1');
endif;
}
wp_reset_postdata();
}
$result = array_unique($stack);
sort($result);
foreach ( $result as $tax2 ) :
// run you code here
endforeach;
Have a great day boys and girls!

How to display categories as titles on my page in wordpress?

I have created a custom post type named "State Leagues" using types plugin. My post type has some categories and outputs both. When I display the posts' titles it displays correctly. My code for displaying post titles is this:
<?php
$args = array(
'post_type' => 'stateleague-pos-type',
'posts_per_page' => 4,
'order_by' => 'post_date',
'order' => 'DESC'
);
$loop = new WP_Query($args);
// $counter = 0;
// $big = 1;
while ($loop->have_posts()) : $loop->the_post();
?>
<a href="<?php the_permalink(); ?>">
<h1> <?php the_title(); ?> </h1>
</a>
?>
Now I want to display the categories' names as the title instead of the posts' titles. I have searched for it but didn't find anything that works. Is it possible to display category names as titles?
<?php
$taxonomy = 'filters';
$terms = get_terms($taxonomy);
if ( $terms && !is_wp_error( $terms ) ) :
?>
<ul>
<?php foreach ( $terms as $term ) { ?>
<li><?php echo $term->name; ?></li>
<?php } ?>
</ul>
<?php endif;?>
Or in fuctions.php Put this:
function get_the_category_custompost( $id = false, $tcat = 'category' ) {
$categories = get_the_terms( $id, $tcat );
if ( ! $categories )
$categories = array();
$categories = array_values( $categories );
foreach ( array_keys( $categories ) as $key ) {
_make_cat_compat( $categories[$key] );
}
return apply_filters( 'get_the_categories', $categories );
}
and call the function as:
<?php $cat = get_the_category_custompost($post->ID, 'Your Custom Taxonomy'); ?>
Try this i hope it will help

Taxonomy archive + query attachments = duplicate results [wordpress]

I'm trying to get the attachments of a specific term (in its archive page).
But the results are showing the resulting images 5 times instead of one.
I have multiple loops in this page - one to show related posts, another to show related products (custom post), and this one to show related images. Custom posts and posts are working nicely, but I can't show the attachments in the right way. :S
<?php $queried_object = get_queried_object();
$term_id = $queried_object->term_id;
$args = array(
'post_status' => 'inherit',
'numberposts' => 0,
'post__not_in' => array_merge($do_not_duplicate,get_option( 'sticky_posts' )),
'post_type' => 'attachment',
);
$args['tax_query'] = array(
array(
'taxonomy' => 't-arte',
'terms' => $term_id,
'field' => 'id',
),
); ?>
<?php $t = $data['t-arte'];
$array = explode(" ", $t);
$array = array_unique($array);?>
<?php $media_query = array_unique($array); ?>
<?php $media_query = get_posts($args);
if( !empty( $media_query ) ) :
foreach ($media_query as $media_query) :
global $post; $post = $media_query;
setup_postdata($media_query);
?>
<div id="archivespage-media-item">
<?php $attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<div id="imagem">';
the_attachment_link( $attachment->ID, true );
echo '</div>';
}
}?>
</div>
<?php endforeach;else :?>
<p>Ainda não temos nenhuma imagem relacionada :(</p>
</div>
<?php endif; ?>
<?php wp_reset_query();?>'
I've done these and its working!
The result will show all attachments in a specific term inside term's archive page.
<?php $queried_object = get_queried_object();
$term_id = $queried_object->term_id;
global $wp_query;
$original_query['tax_query'] = array(
array(
'taxonomy' => 't-arte',
'terms' => $term_id,
'field' => 'id',
),);
$original_query = (array) $wp_query;
$attach_query = array(
'post_type'=> array( 'attachment' ),
'post_status' => array( null ));
$args = array_merge($original_query['query_vars'], $attach_query);
$media_query = new WP_Query( $args )?>
<?php if($media_query->have_posts()) :
while ($media_query->have_posts() ) : $media_query->the_post();
if( $post->ID == $do_not_duplicate ) continue; ?>
<div id="archivespage-media-item">
<div id="imagem">
<?php echo wp_get_attachment_link($attachment->ID, 'bigger-thumb');?>
</div>
</div>
<?php endwhile; else: ?>
//do stuff
</div>
https://wordpress.stackexchange.com/questions/29635/how-to-create-an-attachments-archive-with-working-pagination

Categories