Count posts by ACF values in taxonomy - count

I want to modify this code to count posts only within certain taxonomy, for example 10 free apartments in building 1, 15 free apartments in building 2, where building is a term in taxonomy. How can I do that?
My code:
function get_post_count_by_meta( $meta_key, $meta_value, $post_type) {
$args = array(
'post_type' => $post_type,
'numberposts' => -1,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'apartment_category',
'field' => 'term_id',
),
)
);
if ( $meta_key && $meta_value ) {
if ( is_array($meta_value) ) {
$args['meta_query'][] = array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => 'LIKE'
);
} else {
$args['meta_query'][] = array('key' => $meta_key, 'value' => $meta_value);
}
}
$posts = get_posts($args);
$count = count($posts);
return $count;
}
while ( have_rows('floors') ) { the_row();
$post_count = get_post_count_by_meta('apartment_status', 'free', 'mieszkanie');
$floor_id = get_sub_field('floor_id');
$floor_link = esc_url(get_term_link($floor_id));
$term = get_term( $floor_id, 'apartment_category' ); ?>
<a id="floor_<?php echo $i; ?>" href="<?php echo $floor_link; ?>" class="floor-number">
<span class="build-name"><?php echo $term->name; ?></span>
<span><?php echo $post_count; ?> available apartments</span>
</a>
<?php $i++;
}

Related

How to get post using taxonomy terms in wordpress

I have a post type called "rationale" and my taxonomy name is "company_list". In taxonomy there are list of company. Each company have many rationale.
I want to get latest rationale for each company. How can i do this ?
I try below code but it show all company list but data is duplicate
<?php
//$taxonomy = 'our_work_thematic';
$myquery = array (
'post_type' => 'rationale',
'paged'=>$paged,
'posts_per_page' => -1,
);
$loop = new WP_Query($myquery);
if( $loop->have_posts() ):
while( $loop->have_posts() ):
$loop->the_post(); global $post; ?>
<?php $terms = get_the_terms( $post->ID, 'company_list' );
foreach($terms as $term) {
$termlinks = get_term_link($term);
echo '<p class="post-content--cat">';
echo '' . $term->name . '';
echo '</p>';
}?>
<?php endwhile; ?>
<?php endif; ?>
You need to get latest term and use tax_query
$args_query = array(
'post_type' => array('rationale'),
'paged' => $paged,
'posts_per_page' => -1,
);
$terms = get_terms(array(
'taxonomy' => 'post_tag',
'hide_empty' => false,
));
if (!empty($terms) && is_array($terms)) {
$args_query['tax_query'] => array(
array(
'taxonomy' => 'company_list',
'field' => 'term_id',
'terms' => array($terms['0']->term_id), // single or array with id's
),
),
}
$query = new WP_Query($args_query);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$terms = get_the_terms($post->ID, 'company_list');
foreach ($terms as $term) {
$termlinks = get_term_link($term);
echo '<p class="post-content--cat">';
echo '' . $term->name . '';
echo '</p>';
}
}
} else {
// no post found
}
wp_reset_postdata();
try this
$terms = get_terms( array(
'taxonomy' => 'your taxonomy name',
'hide_empty' => false,
'orderby' => 'term_id',
'order' => 'asc',
) );
foreach ($terms as $terms_row) {
$terms_row->slug;
echo "<pre>";
print_r($terms_row);
echo "</pre>";
}
Thanks

How can I get only those categories which has products on sale?

I am trying to query woocommerce product categories but only those which have on sale products. Is there any possibilities? The result is hierarchy parent > child. I want to show both parent and its child. i.e. if child has product on sale print the parent category as well.
Here is the code I wrote so far
<ul class="accordion list-group sub-catalog">
<?php $terms = get_terms('product_cat', array( 'parent' => 0, 'exclude' => '15' ));
if( $terms ):
$original_query = $wp_query;
foreach ( $terms as $key => $term ):
$child = get_terms(
'product_cat',
array(
'child_of' => $term->term_id,
'hide_empty' => true
)
);
?>
<li class="accordion-card list-group-item">
<div class="acc-card-title">
<?php echo $term->name; ?>
<?php if ( ! $child ){ ?>
<?php
} else {
?>
<span class="fa fa-plus"></span>
<?php
}
?>
</div>
<ul class="accordion list-group sub-catalog">
<?php
$child_terms = get_terms(
'product_cat',
array(
'child_of' => $term->term_id,
'hide_empty' => true
)
);
foreach ( $child_terms as $child_term ) {
$re_child_terms = get_terms(
'product_cat',
array(
'child_of' => $child_term->term_id,
'hide_empty' => true
)
);
if ( ! $re_child_terms ){
?>
<li class="accordion-card list-group-item">
<div class="acc-card-title">
<?php echo $child_term->name; ?>
</div>
</li>
<?php
}
}
?>
</ul>
</li>
<?php
endforeach;
$wp_query = null;
$wp_query = $original_query;
?>
</ul>
<?php endif; ?>
Thanks in advance.
<ul class="accordion list-group sub-catalog">
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => 'rand',
'meta_query' => array(
'relation' => 'OR',
array( // Simple products type
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array( // Variable products type
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
$terms = [];
while ( $loop->have_posts() ) : $loop->the_post();
$terms = array_diff($terms,wp_get_post_terms( get_the_id(), 'product_cat',['fields'=>'ids'] ) );
$term = reset($terms);
?>
<li class="accordion-card list-group-item">
<div class="acc-card-title">
<?php echo $term->name; ?>
</div>
</li>
<?php
endwhile;
} else {
echo __( '' );
}
wp_reset_postdata();
?> </ul>
this is how I get the on sale products and get their category name . where to use array_diff function
The code below solved the problem.
<ul class="accordion list-group sub-catalog">
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => 'rand',
'meta_query' => array(
'relation' => 'OR',
array( // Simple products type
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array( // Variable products type
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
$alreadyDisplayed = [];
while ( $loop->have_posts() ) : $loop->the_post();
$term_list = wp_get_post_terms($post->ID, 'product_cat', array("all"));
foreach($term_list as $term_single) {
if ( !in_array( $term_single->name, $alreadyDisplayed) ) {
echo ' <li class="accordion-card list-group-item">
<div class="acc-card-title"><a href="'.get_term_link($term_single).'" class="salecats">';
echo $term_single->name;
echo '</a><br></div>
</li>';
$alreadyDisplayed[] = $term_single->name;
}
}
?>
<?php
endwhile;
} else {
echo __( '' );
}
wp_reset_postdata();
?> </ul>

How to retrieve posts(books) based on category(taxonomy) in wordpress?

I am trying to display posts of specific category(taxonomy) that is 'Book1'.
I tried to display it with the following code.
$args = array(
'post_type' => 'book',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'Book1',
'field' => 'id',
'terms' => 1
)
)
);
echo '<br>';
$postss = get_posts( $args );
if ( ! empty( $postss ) && is_array( $postss ) ) {
// Run a loop and print them all
$i=1;
foreach ( $postss as $termm ) {
echo ' '.$i.' '.$termm->post_title. '<br>';
$i++;
}
}
?>
In output no any item is displayed.
$custom_terms = get_terms('Book1');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array(
'post_type' => 'book',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'Book1',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h2>'.$custom_term->name.'</h2>';
while($loop->have_posts()) : $loop->the_post();
echo ''.get_the_title().'<br>';
endwhile;
}
}
try this code
$args = array(
'post_type' => 'book',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'Book1',
'field' => ''term_id', // here you are worng name too
'terms' => 1
)
)
);
echo '<br>';
$postss = get_posts( $args );
if ( ! empty( $postss ) && is_array( $postss ) ) {
// Run a loop and print them all
$i=1;
foreach ( $postss as $termm ) {
echo ' '.$i.' '.$termm->post_title. '<br>';
$i++;
}
}
?>
// best solution
<?php
$query = new WP_Query( array(
'post_type' => 'book', // name of post type.
'tax_query' => array(
array(
'taxonomy' => 'Book1', // taxonomy name
'field' => 'term_id', // term_id, slug or name
'terms' => 1, // term id, term slug or term name
)
)
) );
while ( $query->have_posts() ) : $query->the_post();
// do stuff here....
endwhile;
/**
* reset the orignal query
* we should use this to reset wp_query
*/
wp_reset_query();
?>
I did it by doing like this. Thanks all.
$args = array(
'post_type' => 'book',
'cat' => '35'
);
echo '<br>';
$postss = query_posts($args);
if ( ! empty( $postss ) && is_array( $postss ) ) {
// Run a loop and print them all
?><?php $i=1;
foreach ( $postss as $termm ) { ?>
<?php echo ' '.$i.' '.$termm->post_title. '<br>';$i++;?>
<?php
}
}

How to add woocommerce-pagination and woocommerce-ordering dropdown to custom shortcode

I've created a custom shortcode to display products with a minimum stock amount and would like to add pagination to the results as well as calling the woocommerce-ordering dropdown to be displayed on the page.
Here's the shortcode:
// Minimum Stock Shortcode
add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );
function minimum_stock_shortcode( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'limit' => '40',
'columns' => '5',
'orderby' => 'title',
'order' => 'asc',
'category' => '',
'cat_operator' => 'IN',
'stock' => '',
),
$atts, 'minimum_stock'
);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'meta_query' => array(
array(
'key' => '_stock',
'value' => $atts['stock'],
'compare' => '>='
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)
)
);
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $atts['columns'];
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
Any help would be very much appreciated!
Kind regards,
JP
Okay, so I've got pagination working and tidied things up a bit (it was throwing some errors in the debug log), the code now looks like this:
// Minimum Stock Shortcode
add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );
function minimum_stock_shortcode( $atts ) {
global $product, $woocommerce, $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'limit' => '40',
'columns' => '5',
'orderby' => 'title',
'order' => 'asc',
'category' => '',
'cat_operator' => 'IN',
'stock' => '',
),
$atts, 'minimum_stock'
);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_stock',
'value' => $atts['stock'],
'compare' => '>='
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $atts['columns'];
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
if($products->max_num_pages>1){
?>
<nav class="woocommerce-pagination">
<?php echo paginate_links( apply_filters(
'woocommerce_pagination_args', array(
'base' => esc_url( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ),
'format' => '',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $products->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
)
)
);
?>
</nav>
<?php }
woocommerce_reset_loop();
wp_reset_postdata();
$return = '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
// Remove ordering query arguments
WC()->query->remove_ordering_args();
return $return;
}
Does anyone know how I can now call the woocommerce-ordering dropdown?
I've tried adding:
<?php do_action( 'woocommerce_before_shop_loop' ); ?>
But this doesn't seem to work, when I check the page it does have the 'woocommerce-notices-wrapper' but there's no sign of the 'woocommerce_catalog_ordering' that I thought should also be called with 'woocommerce_before_shop_loop'.
Any and all help will be very much appreciated :)
Update:
I found this question Adding 'sort by' drop down on custom page using woocommerce short code which gave me the answer I needed to add the woocommerce-ordering dropdown.
Here's my updated code:
// Minimum Stock Shortcode
add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );
function minimum_stock_shortcode( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'limit' => '40',
'columns' => '5',
'orderby' => 'date',
'order' => 'desc',
'category' => '',
'cat_operator' => 'IN',
'stock' => '',
), $atts );
if ( ! $atts['category'] ) {
return '';
}
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// Default ordering args
$ordering_args = WC()->query->get_catalog_ordering_args( $atts['orderby'],
$atts['order'] );
$orderby = 'date';
$order = 'desc';
if ( isset( $_GET['orderby'] ) ) {
$getorderby = $_GET['orderby'];
}
if ($getorderby == 'date') {
$orderby = 'date';
$order = 'desc';
} elseif ($getorderby == 'sku_desc') {
$orderby = 'meta_value';
$order = 'desc';
$meta_key = '_sku';
} elseif ($getorderby == 'sku_asc') {
$orderby = 'meta_value';
$order = 'asc';
$meta_key = '_sku';
}
$args = array(
'post_type' => array( 'product', 'product_variation' ),
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $atts['limit'],
'orderby' => $orderby, // $ordering_args['orderby'],
'order' => $order, // $ordering_args['order'],
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_stock',
'value' => $atts['stock'],
'compare' => '>='
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $atts['columns'];
if ( $products->have_posts() ) : ?>
<div style="width:100%;">
<div style="float:right">
<form class="woocommerce-ordering" method="get">
<select name="orderby" class="orderby">
<?php
$catalog_orderby = apply_filters( 'woocommerce_catalog_orderby', array(
'date' => __( 'Sort by latest', 'woocommerce' ),
'sku_asc' => __( 'A-Z / Low to High Numbers', 'woocommerce' ),
'sku_desc' => __( 'Z-A / High to Low Numbers', 'woocommerce' )
) );
foreach ( $catalog_orderby as $id => $name )
echo '<option value="' . esc_attr( $id ) . '" ' . selected( $getorderby, $id, false ) . '>' . esc_attr( $name ) . '</option>';
?>
</select>
<?php
// Keep query string vars intact
foreach ( $_GET as $key => $val ) {
if ( 'orderby' === $key || 'submit' === $key )
continue;
if ( is_array( $val ) ) {
foreach( $val as $innerVal ) {
echo '<input type="hidden" name="' . esc_attr( $key ) . '[]" value="' . esc_attr( $innerVal ) . '" />';
}
} else {
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $val ) . '" />';
}
}
?>
</form>
</div>
</div>
<div style="clear:both;"></div>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
if($products->max_num_pages>1){
?>
<nav class="woocommerce-pagination">
<?php echo paginate_links( apply_filters(
'woocommerce_pagination_args', array(
'base' => esc_url( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ),
'format' => '',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $products->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
)
)
);
?>
</nav>
<?php }
woocommerce_reset_loop();
wp_reset_postdata();
$return = '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
// Remove ordering query arguments
WC()->query->remove_ordering_args();
return $return;
}
I hope someone might find this helpful :)
Kind regards,
JP

How to call category in dashboard if mine posted is attached to them only?

I am making user dashboard and I create a dashboard widget for category. Now I want to show category if current user's post is attached to them.
Currently I am able to see all categories.
Here is my function
function user_categories() {
wp_add_dashboard_widget(
'wp_widget_category', // Widget slug.
'Categories', // Title.
'my_dashboard_category' // Display function.
);
function my_dashboard_category() {
if ( is_user_logged_in() ):
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
?>
<?php
$args = array(
'type' => 'recipes',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'author' => $current_user->ID,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'recipe_categories',
'pad_counts' => false );
$categories = get_categories($args);
foreach ($categories as $category) {
$url = get_term_link($category);?>
<div class="submitted_recipe">
<a href="<?php echo $url;?>"><?php echo do_shortcode(sprintf('[wp_custom_image_category size="large_blog" term_id="%s"]',$category->term_id)); ?>
<h2><?php echo $category->name; ?></h2>
</a>
</div>
<?php
}
?>
<?php
}
endif;
}
}
add_action( 'wp_dashboard_setup', 'user_categories' );
You need to query all user posts in each categorie, if it's not empty then include this category. try this revised code
function user_categories() {
wp_add_dashboard_widget(
'wp_widget_category', // Widget slug.
'Categories', // Title.
'my_dashboard_category' // Display function.
);
function my_dashboard_category() {
if ( is_user_logged_in() ):
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
?>
<?php
$args = array(
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'recipe_categories',
'pad_counts' => false );
$categories = get_categories($args);
foreach ($categories as $category) {
$posts_query = new WP_Query( array(
'post_type' => 'recipes',
'author' => $current_user->ID,
'tax_query' => array(
array('taxonomy' => 'recipe_categories',
'field' => 'slug',
'terms' => $category->slug)
),
'fields' => 'ids'
) );
$ids = $posts_query->posts;
if (!empty ($ids)) {
$url = get_term_link($category);?>
<div class="submitted_recipe">
<a href="<?php echo $url;?>"><?php echo do_shortcode(sprintf('[wp_custom_image_category size="large_blog" term_id="%s"]',$category->term_id)); ?>
<h2><?php echo $category->name; ?></h2>
</a>
</div>
<?php
}
}
?>
<?php
}
endif;
}
}
add_action( 'wp_dashboard_setup', 'user_categories' );

Resources