How do you write conditional PHP based on WooCommerce attribute - php

I've search the interwebs high and low looking for a way to conditionally display WooCommerce product attribute data on certain pages.
Ex: if attribute somethingcool has a value and it's on /?filtering=1&filter_manufacturer=1648 page, display value
I'd like to display an attribute differently if they are on a specific filtered page
Ex:
http://www.colorselectcoil.com/color-match-tool/?filtering=1&filter_manufacturer=1648
Based on this filtered page, display a product attribute 'somethingcool'
<?php if ( is_product_attribute('somethingcool') ) {
echo 'Hi! This is something cool?';}
else {
echo '';
}
?>
If it were a normal WordPress page, not a filtered page I could hide and show based on body class tag but unfortunately the body class doesn't change based on query string urls.

You could use the url search string and extract from it whatever part you wanted. For example, if you only wanted to know if you were on a filtered page then you wouldn't bother checking for the manufacturer.
<?php if ( $product->get_attribute('Certainteed') && intval($_GET['filtered']) == 1 && intval($_GET['filter_manufacturer']) == 1648 ) {
echo 'Hi! This is something cool?';
}
?>
The intval() bit should be enough to prevent injects.
If you wanted to find a part of the uri you could use something like:
if( stristr( htmlspecialchars($_SERVER['REQUEST_URI']), 'color-match-tool') && is_product_attribute('somethingcool') ){
echo 'Hi! This is something cool!';
}
Check to see what echo is_product_attribute('Everlast'); as per your example returns.
$_GET... gets the variables in the search string by their names, which go in the square brackets.
<?php if( stristr( htmlspecialchars($_SERVER['REQUEST_URI']), 'color-match-tool') && intval($_GET['filtering']) == 1 && intval($_GET['filter_manufacturer']) == 1694 && is_product_attribute('Everlast') ){
echo 'Hi! This is something cool!';
} ?>
Try it with just one item at a time and build up to get the hang of it.
Loads about finding strings in strings How do I check if a string contains a specific word in PHP?
Other ways to get and echo a product attribute if need be:
Woocommerce getting custom attributes
I am not sure if this would work, but it might be adaptable enough.
You could pass the filter value $ff the filter integer value you want $ffv (might be different from 1) $fm is the $filter_manufacturer integer value $fmv - is the value you are looking for it to be - is as your example 1648 then the product array $product, your $collection variable and $aiw is the "Attribute I want" in text form but you might also pass it in a variable.
Put this function in your functions.php
function attribute_i_want( $ff,$ffv, $fm, $fmv, $prod, $coll, $aiw){
if( $ff == 1 && $fm == $fmv && $collection = $prod->get_attribute($aiw) ){
echo '<div class="attribute-titles">. $aiw . ' name: ';
echo ($coll = $prod->get_attribute($aiw) ) ? $collection : __('', 'woocommerce'); echo '</div>';
}
}
add_action( 'wp_enqueue_scripts', 'attribute_i_want' );
And call it with this little lot passed to it
<?php attribute_i_want( intval($_GET['filtering']), 1, intval($_GET['filter_manufacturer']), 1648, $product, $coll, 'Certainteed'); ?>
I have assumed that the code you posted is working as it stands.
Looking at your page I can't see how it is getting the value from the dropdown list as it has no name or ID - ideally in the onchange event onchange="setManufacturer()"; - which I also can't find but believe it to be an event listner script - you would use something like this to set a hidden variable which gets the dropdown text value and uses that for the slot in the function call where you would currently have to enter the text manually, like 'Certainteed' in the example:
<script language=JavaScript>
function setManufacturer(){
var manufacturerName = manufacturerDropdown.options[manufacturerName.selectedIndex].innerHTML;
documentGetElementById('submittedManufacturerName').value = manufacturerName;
}
</script>
This would get the text of what is selected from the select dropdown - which would need the ID "manufacturerName" and insert that text value into the hidden input's value, which PHP would be able to pick up and use in the PHP function call.
The onchange event would trigger the JavaScript and submit the page, the php would pick up the text value from the hidden input and that is what would be put into the function call:
<input type="hidden" id ="submittedManufacturerName" name="submittedManufacturerName" value = "" />
<?php attribute_i_want( intval($_GET['filtering']), 1, intval($_GET['filter_manufacturer']), $manufacturerName, $product, $coll, $submittedManufacturerName); ?>
Unless there is any other way you can get at the value for the manufacturer name in a PHP variable - which may be possible as the manufacturer name does appear elsewhere on the page in the link above your dropdown, so it may already exist as a PHP variable which you could use as it is. That way your function would be fully automatic without the need for this additional JavaScript. The value appears in the a href called "Remove filter" on your existing page.
$manufacturerName would be the submitted value from the dropdown's actual value collected as $manufacturerName = htmlspecialchars($_GET['manufacturerDropdown']);

Steve hooked it up and helped me figure out how to write conditional based on filter, which fixed my issue. Thanks Steve!
<?php if( intval($_GET['filtering']) == 1 && intval($_GET['filter_manufacturer']) == 1648 && $collection == $product->get_attribute('Certainteed') ){ echo '<div class="attribute-titles">Certainteed name: '; echo ($collection == $product->get_attribute('Certainteed') ) ? $collection : __('', 'woocommerce'); echo '</div>'; } ?>

Related

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) {

ACF Advanced Custom Field Multiplication returning 0 instead of the correct math answer

I am trying to do all manner of things with the ACF Advanced Custom fields. In this case I created two custom fields
<?php
$num1 = get_field('test_one');
$num2 = get_field('test_two');
$num3 = $num1*$num2 ;
echo "</br> Value is $num3" ;
?>
test_one contains 2 as the default value, test_two contains 4
I am getting 0 as the result when clearly the field values should return something different.
What is going on here?
For multiplying Two numbers of Custom field value do as below:
1) add field in plugin page where you have to select type as "number" like this
2) Add below code in functions.php
function multiplynumber()
{
$test_one = get_field('test_one', get_the_ID());
$test_two = get_field('test_two', get_the_ID());
$num3 = $test_two*$test_one ;
echo "</br> Value is".$num3 ;
}
add_action('wp_head','multiplynumber');
You have to write post/page id where your field plugin showing in admin panel see this image where i have put condition in "page"
e.g from backend in sample-page i have write value in "test_one" = 2 and "test_two" = 4 see here then it will show multiply value in that front page see here so you have to write that page ID in get_field function or you can also use
get_the_ID()
as dynamic purpose

How to display data from cmb2 option page?

I have created a repeatable field with CMB2, and created a normal field. This is the function of https://pastebin.com/XUQgkvbi
If you use foreach for repeatable using a post or page then you can show data as: https://pastebin.com/C35vWGDs
And Call normal field without repeatable, then
<?php $ entries = get_post_meta (get_the_ID (), 'yourprefix_group_demo', true); ?>
<?php echo $ entries; ?>
also work.
But the problem is, I do not want to use the above function on any page or post. I want to use it in the Options Page. The above Function option has been added to the option page, but I can not do the data show of those files in any way.
I've tried get_post_meta () and get_option () with two functions, but in no way can I show data from the option page. How can I get the data from the above fields (option page) to the show in the frontend? Please help with a little bit.
I got solution, The options are stored in a single option field. You would loop through the news-section groups with something like this:
$settings = get_option( 'repeatable-news-options.php', array() );
if ( ! empty( $settings['news-section'] ) ) {
foreach ( $settings['news-section'] as $section ) {
echo $section['title'] . '<br/>';
}
}
that link https://wordpress.org/support/topic/how-to-display-data-from-cmb2-option-page/
problem solved.

Ninja forms - checkbox checked-value issue. Is it possible to modify? Calculation not working

I don't know if this is the correct place to ask, but I'll try. I have an ongoing project with Wordpress (Genesis framework - Agentpress PRO theme) working with Ninja Forms, and am having a slight problem. The web page is: http://www.supercastor.net/wordpress/listings/castellon-65-m2-ytong/
I have a listings page (for each house model). Each listing has metadata that is accessible via a simple function from the genesis framework:
genesis_get_custom_field( 'CUSTOM_FIELD_NAME' );
I would like to have, like the link above has, a list of checkboxes that the user can select/deselect, and the TOTAL value is finally calculated. Everything is working, except that I cannot assign the value of this "custom field" that is from the listing.
I am using Ninja Forms, and after some research, I have come up with the solution of registering a custom field in NF:
function precio_basico_calc_display( $field_id, $data ){
// Get the default_value
if( isset( $data['default_value'] ) ){
$def_value_new = genesis_get_custom_field( '_listing_precio_sort' );
$data['default_value'] = $def_value_new;
$default_value = $data['default_value'];
debug_to_console("Default_value is set to:$default_value");
}else{
$default_value = '';
debug_to_console("Default_value NOT SET");
}
$products_select = genesis_get_custom_field( '_listing_precio_sort' );
}
// Now that $products_select is populated with the listing_price, output a checkbox with the value of the price. ?>
<input type="checkbox" name="ninja_forms_field_<?php echo $field_id;?>" value="<?php echo $products_select;?>" checked="checked" class="ninja-forms-field ninja-forms-field-calc-listen" disabled="disabled">
<?php
}
I also have a small "debug_to_console" function, but this is just as a quick "debugging". I can see that the value is there, but in the calculation it is not set. I have set the default to 40.000, but it should be set to the value for each price (in the link example, should be 19.000). As:
$products_select = genesis_get_custom_field( '_listing_precio_sort' );
And I have also tried the following (field_id 33 is the checkbox in the form):
add_filter( 'ninja_forms_field', 'my_filter_function', 10, 2 );
function my_filter_function( $data, $field_id ){
if( $field_id == 33 ){
$listing_price = genesis_get_custom_field( '_listing_precio_sort' );
$data['default_value'] = $listing_price;
}
return $data;
}
But it isn't working either. I mean, it does display the value (in the console), but not making the calculation correctly.
Help! I just want the calculation (TOTAL) to update correctly for each listing. I thought changing the default_value would do, but it doesn't. I'm lost :(
Thanks!

Adding a Taxonomy Filter to a Custom Post Type

There is an amazing conversation from about two years ago on the Wordpress Answer site where a number of people came up with good solutions for adding a taxonomy filter to the admin screen for your custom post types (see URL for screen I'm referring to):
http://[yoursite.com]/wp-admin/edit.php?s&post_status=all&post_type=[post-type]
Anyway, I loved Michael's awesome contribution but in the end used Somatic's implementation with the hierarchy option from Manny. I wrapped it in a class - cuz that's how I like to do things -- and it ALMOST works. The dropdown appears but the values in the dropdown are all looking in the $_GET property for the taxonomies slug-name that you are filtering by. For some reason, I don't get anything. I looked at the HTML of the dropdown and it appears ok to me. Here's a quick screenshot for some context:
You can tell from this that my post-type is called "exercise" and that the Taxonomy I'm trying to use as a filter is "actions". Here then is the HTML surrounding the dropdown list:
<select name="actions" id="actions" class="postform">
<option value="">Show all Actions</option>
<option value="ate-dinner">Ate dinner(1)</option>
<option value="went-running">Went running(1)</option>
</select>
I have also confirmed that all of the form elements are within the part of the DOM. And yet if I choose "Went running" and click on the filter button the URL query string comes back without ANY reference to what I've picked.
More explicitly, the page first loads with the following URL:
/wp-admin/edit.php?post_type=exercise
and after pressing the filter button while having picked "Went Running" as an option from the actions filter:
/wp-admin/edit.php?s&post_status=all&post_type=exercise&action=-1&m=0&actions&paged=1&mode=list&action2=-1
actually, you can see a reference to an "actions" variable but it's set to nothing and as I now look in detail it appears that the moment I hit "filter" on the page it resets the filter drop down to the default "Show All Actions". Can anyone help me with this?
BTW, I've attached the PHP code here (although I'm now starting to lean toward it being a js issue): gist.
I was having the same issue and added a small fix, basically checking if the taxonomy $_GET parameter is set. I hope it helps:
add_action( 'restrict_manage_posts', 'my_restrict_manage_posts' );
function my_restrict_manage_posts() {
global $typenow;
$taxonomy = 'mytaxonomy'; // Change this
if( $typenow != "page" && $typenow != "post" ){
$filters = array($taxonomy);
foreach ($filters as $tax_slug) {
$tax_obj = get_taxonomy($tax_slug);
$tax_name = $tax_obj->labels->name;
$terms = get_terms($tax_slug);
echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
echo "<option value=''>Show All $tax_name</option>";
foreach ($terms as $term) {
$label = (isset($_GET[$tax_slug])) ? $_GET[$tax_slug] : ''; // Fix
echo '<option value='. $term->slug, $label == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>';
}
echo "</select>";
}
}
}
Try this class, it works wonderful

Categories