Writing a php function for advance custom field in wordpress - php

I want to implement a progress bar using elementor for WordPress website, for that I've used the widget progress bar, but I'm adding the percentage value dynamically in the progress value, for that I've created a field percentage in my Campaign Details group field in Advance custom field plugin, which have type number and added it to the dynamic tag in progress bar.
After that I've added my php code in snipped code, I'm new to php, so don't know why it is incorrect, I did take the help of chatgpt other sources to find the mistake.
I've wrote two types of function, in the first type, I've used the array to access the campaign details group field to access its fields and in another I've used this notation: get_field('group_field_name_subfield_name')
first type
function calculate_donation_percentage($post_id) {
$donation_received = get_field('Campaign Details', $post_id)['donation_received'];
$donation_required = get_field('Campaign Details', $post_id)['donation_required'];
if ($donation_required == 0) {
$percentage = 0;
} else {
$percentage = ($donation_received / $donation_required) * 100;
}
update_field('Campaign Details', array('donation_percentage'=> $percentage), $post_id);
}
add_action('save_post', 'calculate_donation_percentage');
second type
function calculate_donation_percentage($post_id) {
$donation_received = get_field('Campaign Details_donation_received', $post_id);
$donation_required = get_field('Campaign Details_donation_required', $post_id);
if ($donation_required == 0) {
$percentage = 0;
} else {
$percentage = ($donation_received / $donation_required) * 100;
}
update_field('Campaign Details_donation_percentage', $percentage, $post_id);
}
add_action('save_post', 'calculate_donation_percentage');
I've read that we can add filter method too to add the value into acf field.
add_filter('acf/update_value/key=campaign_details_donation_percentage', 'calculate_donation_percentage', 10, 3);
Please give me some ideas about how I solve this problem.

In first type, I think you typed the wrong field ID 'Campaign Details', IDs does not contain space, check your acf dashboard to find the right field ID, check the attached image.

Related

Show images in slider from acf repeater

I'm trying to show the ACF repeater image in the dynamic slider in oxygen via the PHP function from the specified page id.
ACF field: slajder
Subfield with img repeater: obraz_slajdera
Page id: 7219
I always get background-img unknown.
My code:
function get_slider() {
$image = get_field( 'img', 7219 )['sizes']['large'];
return $image;
}
Please help.
You may want to do some reading through the ACF developer documentation, your code is fragmented, and the get_field() function isn't being used properly. At any rate, I'll do my best to explain what you should be directing your solution towards. You'll first need to loop through your repeater fields, check to see if there's any "rows" in the repeater field, fetch your value, and then do whatever you need to do with your respective image.
So, technically your function should look something like this:
function fetchSliderImages() {
//Empty array for holding your slider images, assuming there's more than one
$sliderImages = array();
//Check to see if the slider even has rows
if( have_rows('slajder') ):
//Loop through all the rows of your slider
while( have_rows('slajder') ) : the_row();
//Assuming this is coming back as a URL (can be adjusted within ACF)
$imageRepeaterValue = get_sub_field('obraz_slajdera');
//Check to see that we actually got something back that isn't blank
if($imageRepeaterValue != '') {
array_push($sliderImages, $imageRepeaterValue);
}
endwhile;
endif;
return $sliderImages;
}
You can then use this function to return an array of URL's which are slider images.
Used this for reference: https://www.advancedcustomfields.com/resources/repeater/

Check if product has specific attributes set to it, then show additional div if true

I am trying to create a function to show additional product information if requirements are met dependent on whether some attributes are set or not on specific products. For this I am using two attributes called 'pa_storlek' and 'pa_djurart'. Seems to me everything should be working but no matter what I do I just keep getting the else value (Inte X-Small).
I need to check the two attributes together, meaning that if I get both attributes values at the same time the statement should be valid, and - if not, it should show the else output.
Anyone has an idea? Been looking around alot but can't seem to find another question like mine..
// X-Small dogs list
add_action( 'woocommerce_single_product_summary', 'x_small_dogs', 90 );
function x_small_dogs() {
global $product;
$product_attributes = $product->get_attributes();
// Get the product attribute value
$size = $product->get_attribute('pa_storlek');
$animal = $product->get_attribute('pa_djurart');
// If product has attribute 'size = x-small' and 'animal = hund'
if( strpos($size, 'x-small') && strpos($animal, 'hund') ) {
echo '<div class="">X-Small</div>';
} else {
echo '<div class="">Inte X-small</div>';
}
}
If strpos find the string starting at the first character, return 0 (index position) and it is evaluated like false.
So try
if( strpos($size, 'x-small')!==false && strpos($animal, 'hund')!==false) {

Finding sum of ACF custom field value for comments

I have created a few custom fields for comments to allow reviews on a Wordpress site built for listing hotels with user reviews as comments. One of these custom fields is a 'star_rating' field. I need to find a way to fetch the total sum of all values in order to find the average 'star_rating' value for each post to be displayed in search results and on the listing profile.
I have been trying for a long time to find the total sum for the star_rating field values. I have last used the following code but it does not work although I cannot see why. Any help would be much appreciated.
$ratings_sum = 0;
// Arguments for the query
$args = array();
// The comment query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// The comment loop
if ( !empty( $comments ) ) {
foreach ( $comments as $comment ) {
$ratings_sum+= $comment->star_rating;
}
} else {
// echo 'No comments found.';
}
echo $ratings_sum;
Many thanks in advance.
If you are using ACF custom field plugin, try to use get_field() function. You can't access your custom field $comment->star_rating like this.
Try below custom query for fetch star rating:
SELECT SUM(meta_value) FROM wp_commentmeta WHERE comment_id IN (SELECT comment_ID FROM wp_comments WHERE comment_post_ID = '//your post id') and meta_key='star_rating';

How to add icon next to WP post title based on custom field

I am trying to add a little icon (jpg) next to every WordPress posts' titles that have a specifc custom field. Anyone would know how to do it?
I have defined a custom field for some posts like this: $custom = 2 and i want these posts' titles to include an icon.
So to access the specific custom field, use this:
get_post_meta($post_id, $key, $single);
Where $post_id = the id of the post (use
$post->ID
to get a post's ID)
Where $key = the name of the custom field (ie. "custom")
where $single = If set to true then the function will return a single result, as a string
So you'd use something like:
$key = 'custom';
if (get_post_meta($post->ID, $key, true) == 2){
//echo icon here
}
You can also check out Wordpress's article on it: http://codex.wordpress.org/Custom_Fields

Getting Input Fields from Gravity Forms on Woocommerce

Gravity Forms Product Add-ons for Woocommerce displays the form inputs of a user in the cart and checkout. I want to display these form fields in the user's Account page with their orders. I've been trying for a week and can't seem to get the right php code put together. How can I do this?
My code as it stands is like so:
$form_id = RGFormsModel::get_form_id('Domains');
$form = GFFormsModel::get_form_meta($form_id);
$field = GFFormsModel::get_field($form, 1);
$leads = RGFormsModel::get_leads($form['id']);
foreach($leads as $lead)
{
foreach($field as $field_id)
{
$value = rgar($lead, (string) $field_id);
echo $value;
}
}
This returns all entries for the field I want, however, I only want to return the entry that was submitted with that particular product. Help?
Here's a quick example for clarity on what I'm looking for. A user buys a shirt and selects size large from a Gravity Form that was attached to the product. On the cart and checkout pages, it says beneath the product title "Size: Large". I want to add that same text to the "My Account" page with their order.
The way I solved a similar problem may not be the best in coding practices but it works. It takes custom data associated with the order from Gravity Forms and displays it under the shipping address in WooCommerce individual order page:
<?php
add_action('woocommerce_admin_order_data_after_shipping_address', 'ips_show_signs_in_admin_under_shipping', 10, 1);
/*
function to put in functions.php of the theme to add custom gravityforms data to customer order page in admin area.
*/
function ips_show_signs_in_admin_under_shipping($order)
{
global $woocommerce, $post;
$order_items = $order->get_items(apply_filters('woocommerce_admin_order_item_types', array( 'line_item')));
foreach($order_items as $item_id => $item)
{
if ($metadata = $order->has_meta($item_id)) //not a comparison, so one equal sign. so if there is any data in there it would assign it and thus making it true, if no data it would be false
{
foreach($metadata as $meta)
{
// Skip hidden woocommerce core fields just in case
if (in_array($meta['meta_key'], apply_filters('woocommerce_hidden_order_itemmeta', array(
'_qty',
'_tax_class',
'_product_id',
'_variation_id',
'_line_subtotal',
'_line_subtotal_tax',
'_line_total',
'_line_tax',
)))) continue;
if (is_serialized($meta['meta_value'])) continue; // Skip serialised meta since we dont need it incase its in there
$meta['meta_key'] = esc_attr($meta['meta_key']); //just to make sure there is no surprises in there
$meta['meta_value'] = esc_textarea($meta['meta_value']); // using a textarea check for surprises (sql injection)
if ("Signpost Address" === $meta['meta_key']) //here comes the custom data from gravity forms
{
echo $meta['meta_value']; //this is what i was after from gravity forms collected with order
}
} //closes --- foreach($metadata as $meta)
} //closes --- if ($metadata = $order->has_meta($item_id))
} //closes --- foreach($order_items as $item_id => $item)
} //closes --- function
?>
Edit: This code searches the order meta data
I have added the above code in my functions.php file and unfortunately this hasn't worked for me. I have looked all over for a solution to this and this seems to exactly be what I'm after. Do i simply replace "Signpost Address" with say "Blanket Size" if that were one of my gravity form options?

Categories