Total count of advanced custom field values in WordPress - php

I'm trying to get the total count of a value of a custom field for WooCommerce products. My products are stock of shoes, so for each product I create a custom field for the total pairs quantity. Now I need to display in a new page the total count of pairs.
I tried with this code but the result is always 0
<?php
$pair_total = 0; //my main variable
$posts = get_posts(array(
'posts_per_page' => -1, //get all post
'post_type' => 'product' //my custom post type
));
if( $posts ) {
foreach( $posts as $post ){
setup_postdata( $post );
if (get_field('n_totale')) {
echo get_field('n_totale'); //show individual field(not needed)
$pair_total = get_field('n_totale') + $pair_total; //sum all fields
}
}
wp_reset_postdata();
}?>
<?php echo '<h1>'.$pair_total.'</h1>'//showing the total value;
?>
What can I try next?

check get_field() Try below code.
<?php
$pair_total = 0; //my main variable
$posts = get_posts(array(
'posts_per_page' => -1, //get all post
'post_type' => 'product' //my custom post type
));
if( $posts ) {
foreach( $posts as $post ){
setup_postdata( $post );
if ( get_field( 'n_totale', get_the_ID() ) ) {
$pair_total = $pair_total + (int) get_field('n_totale', get_the_ID() ); //sum all fields
}
}
wp_reset_postdata();
}
echo '<h1>'.$pair_total.'</h1>'//showing the total value;
?>

I solved with this code:
$pair_total_1 = 0; //my main variable
$posts = get_posts(array(
'numberposts' => -1, //get all post, previously was post_per_page
'post_type' => 'product', //my custom post type
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
)
) //I add a query to count only in stock product
));
if( $posts ) {
global $post;
foreach( $posts as $post ){
setup_postdata( $post);
if ( get_field( 'n_totale', get_the_ID() ) ) {
$pair_total_1 = $pair_total_1 + (int) get_field('n_totale', get_the_ID() );
//sum all fields
}
}
wp_reset_postdata();
}
echo '<p>Totale paia disponibili: '.$pair_total_1.'</p>';}//showing the total value
Thanks to all

Related

How to auto update an acf field based on the condition?

I have two custom post types with acf fields.
Custom Post_A, which has 2 fields - title / submitted
Custom Post_B, which has 2 fields - title / percent
Both Post_A and B have the same title (which is the logged in user's name) and they already exist.
When a field ‘submitted’ has the value ‘done’ in Post_A, I need to automatically update a ‘percent’ field with a value ‘50’ in Post_B.
I tried the following code but it doesn't update ‘50’ to Post_B.
Would you please correct my code?
$posts = get_posts(array(
'author' => get_current_user_id(),
'posts_per_page' => -1,
'post_type' => 'post_a',
'meta_key' => 'submitted',
'meta_value' => 'done'
));
$the_query = new WP_Query( $posts );
$the_count = count($the_query);
if($the_count>0) {
foreach ($the_query as $is_done){
$my_post = array();
$my_post['post_type'] = 'post_b';
$my_post['post_title'] = the_title();
// Update the post into the database
$field_key = "field_606cb546456343";
$value = "50";
update_field( $field_key, $value);
}
}
Thank you.
You can use save_post_{$post->post_type} action hook that will trigger on specific post type. check the below code.
function update_post_b( $post_id, $post, $update ){
$post_a_title = get_the_title( $post_id );
$posts = array(
'author' => get_current_user_id(),
'posts_per_page' => -1,
'post_type' => 'post_b'
);
$post_b = new WP_Query( $posts );
if( $post_b->have_posts() ){ while ( $post_b->have_posts() ) { $post_b->the_post();
if( $post_a_title == get_the_title() ){
update_post_meta( get_the_ID(), 'percent', 50 );
}
} }
}
add_action( 'save_post_post_a', 'update_post_b', 10, 3 );
USEFUL LINKS
save_post_{$post->post_type}

Filter WooCommerce related products by Polylang language

I'm using polylang plugin to having multi-languages website.
Using WooCommerce with polylang demands duplicating each product for each language, so assuming I have Hebrew and English, that means 2 duplications for each products.
It works fine with WooCommerce plugin, but when I'm displaying "related products" at the end of the product page, it's mixing products in English and Hebrew together.
I expect to filter the related product by website current language (if(get_locale() == 'en_US') - to check website current locale state, else will represent Hebrew).
Polylang functions
Here is what I have tried, but I got stuck on the part of filtering the product by language:
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
How can I filter Woocommerce related product section by language?
Edit
So after a little bit of research and help in the comments I found out that 'lang' => 'en' argument does exist, but even when I use it, there is no change on related products language display.
Any ideas?
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'suppress_filters' => false
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
suppress_filters There is a way to make get_posts cache the results however, the suppress_filters option is true by default, but if you set it to false, the caching mechanisms inside WordPress will do their work, and results will be saved for later.
You can try this code:
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'meta_query' => $meta_query,
'lang' => 'en'
) );
if ($related_posts) {
foreach ($related_posts as $post) {
setup_postdata($post);
// something like <li><?php the_title(); ?></li>
}
}
wp_reset_postdata();
This code correctly returns code in selected language on my site
While working on a custom WordPress REST Api end point to fetch post by selected language or device language, this worked. See if it can help you out.
function mycustomplugin_posts($params) {
// get the url params
$page = $params->get_param('page') ? $params->get_param('page') : 0;
$per_page = $params->get_param('per_page') ? $params->get_param('per_page') : 10;
$offset = $params->get_param('offset') ? $params->get_param('offset') : 0;
$order = $params->get_param('order') ? $params->get_param('order') : 'desc';
$order_by = $params->get_param('order_by') ? $params->get_param('order_by') : 'date';
$lang = array_search($params->get_param('lang'),polylang_json_api_languages(), true) ? $params->get_param('lang') : pll_default_language();
$args = [
'post_type' => 'post',
'page' => $page,
'numberposts' => $per_page,
'offset' => $offset,
'order' => $order,
'orderby' => $order_by,
'tax_query' => [
[
'taxonomy' => 'language',
'field' => 'slug',
'terms' => $lang
]
]
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
// Extract the post data
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['excerpt'] = e42_the_short_content($post->post_content, 300);
$data[$i]['slug'] = $post->post_name;
$data[$i]['date'] = $post->post_date;
$data[$i]['link'] = get_permalink($post->ID);
$data[$i]['author'] = get_the_author_meta('display_name', $post->post_author);
$data[$i]['categories'] = array();
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
foreach(get_the_category($post->ID) as $category){
array_push($data[$i]['categories'],$category->term_id);
}
$i++;
}
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom status code
$response->set_status( 200 );
return $response;
}
/plugins/woocommerce/templates/single-product/related.php
Move this to child theme
yourtheme/woocommerce/single-product/related.php
And add the following line to the foreach loop
if (pll_current_language()!=pll_get_post_language($post_object->ID)) {
continue;
}
Basically if current language does not match product language we skip over it.

WordPress post count : X out of Y?

I'm working on a theme with CPT.
In single-cpt.php, I want to show the post number out of the total posts.
I managed to show the total ok posts using :
<?php $args = array(
'post_type' => 'cpt_type',
'post_status' => 'published',
'numberposts' => -1
);
echo $num = count( get_posts( $args ) ); ?>
and it returns the total of posts for that CPT type. So, on each single cpt, I got the total number.
What I would like, is to have "post number" / "total posts". Example : 7/21, and when I go o the following post : 8/21 and so on...
So, how could I get each single post to have a "number"?
Thanks!
Paste this in functions.php:
function get_total_number_of_posts( $post ) {
$posts = get_posts( array(
'post_type' => $post->post_type,
'posts_per_page' => -1
) );
return count( $posts );
}
function get_current_post_index( $post ) {
$posts = get_posts( array(
'post_type' => $post->post_type,
'posts_per_page' => -1
) );
$index = 0;
foreach ( $posts as $p ) {
$index++;
if ( $p->ID === $post->ID ) {
break;
}
}
return $index;
}
and then in your single.php file:
global $post;
$total_posts = get_total_number_of_posts( $post );
$current_post = get_current_post_index( $post );
echo "You are viewing {$current_post} out of {$total_posts}";

WordPress count custom post type Advanced Custom Field

I have WordPress site and the plugin Advanced Custom Fields, I have created a custom post for testimonials, inside is custom field called 'ratings' where you in put a number e.g. 1, 3.5, 5 etc.
I want to take all the number from the field for each post and add them up to a total or average out of 5.
However I'm struggling I can get it to populate the ratings e.g. 5, 5
But I can't get them to add up, can any one help please?
This is what I have below so far...
<?php
$args = array( 'post_type' => 'testimonial', 'posts_per_page' => 9999 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<?php
$count = (get_field('rating'));
print_r($count);
$add = count($count);
return $add;
echo $add;
?>
<?php
endwhile;
?>
He almost got it right. Just replace count() with array_sum()
global $post;
$count = array(); // define $count as array variable
$args = array( 'post_type' => 'testimonial' 'posts_per_page' => -1, 'offset'=> 1);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
// push rating value inside the $count array
$count[] = get_post_meta($post->ID, 'rating', true);
endforeach;
wp_reset_postdata();
$add = array_sum($count); // You can use this variable outside also.
echo $add; // print total rating.
echo $add/count($count) // Print average
Try using this code. changed posts_per_page => -1
global $post;
$count = array(); // define $count as array variable
$args = array( 'post_type' => 'testimonial' 'posts_per_page' => -1, 'offset'=> 1);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
// push rating value inside the $count array
$count[] = get_post_meta($post->ID, 'rating', true);
endforeach;
wp_reset_postdata();
$add = count($count); // You can use this variable outside also.
echo $add; // print total rating.
Hope, This will helpful for you. Thanks.

How to get all post from a post type in Wordpress

I try to get all product from database with function get_post_types,but i get an empty array:
<?php
$list=mysql_query("SELECT * FROM wp_posts where post_type='product'");
if (empty($list)) {
echo "NONE";
}
?>
Try with:
$products = get_posts(array(
'numberposts' => -1,
'post_type' => 'product',
));
Check that post_type name is correct.
This query will get all the post with type product, for get only the published ones, add:
'post_status' => 'publish'
To the array arguments.
From a post you can get a lot of information:
To get the post image:
$img = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
To get the category of a post:
$cats = get_the_category( $post->ID );
$cats is an array of terms.
you may use the standard WP_Query method instead:
$args = array( 'post_type' => 'product', 'posts_per_page' => -1 );
$product_query = new WP_Query( $args );
if( $product_query->have_posts() ){
while( $product_query->have_posts() ){
$product_query->the_post();
if( has_post_thumbnail() ){
the_post_thumbnail();
}
}
}

Categories