Match multiple attribute terms in Wordpress PHP loop - php

This seems like a simple enough problem but I'm a novice at PHP and I've been working on this for hours. I'm looping through posts in an archive and showing a different logo for each post based on a certain attribute. Here's my existing function in functions.php:
function show_logo() {
global $post;
$attribute_names = array( 'pa_product-type'
);
foreach ( $attribute_names as $attribute_name ) {
$taxonomy = get_taxonomy( $attribute_name );
if ( $taxonomy && ! is_wp_error( $taxonomy ) ) {
$terms = wp_get_post_terms( $post->ID, $attribute_name );
$terms_array = array();
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
if ( $term->name == 'L1' ) {
// Show L1 Logo
}
elseif ( $term->name == 'M1' ) {
// Show M1 Logo
}
elseif ( $term->name == 'H1' ) {
// Show H1 Logo
}
else {
$full_line = '<span>'. $term->name . '</span>';
}
array_push( $terms_array, $full_line );
}
echo implode( $terms_array );
}
}
}
}
All I want to do is do show a different logo if the post matches multiple terms (e.g. 'L1' AND 'M1'). I have tried many very different things but I have no idea if I'm even on the right track. Any help would be greatly appreciated.

This should be fairly easy, I'm just not exactly sure the full context of all the data involved.
Assuming you are only showing one logo per post, here is one approach:
Right before foreach ( $terms as $term ) { create three boolean variables:
$hasL1 = false;
$hasM1 = false;
$hasH1 = false;
Then when one of your term names matches, instead of just showing the logo set the appropriate variable equal to true, ie $hasL1 = true;
After the foreach is complete, either before or after echo implode( $terms_array ); depending on what makes sense, setup a new if/elseif/else block to decide what logo to show as follows:
if ($hasL1 && $hasM1 && $hasH1) { // Pick logo for all 3 }
elseif ($hasL1 && $hasM1) { // Pick logo for pair }
elseif ($hasL1 && $hasH1) { // Pick logo for pair }
elseif ($hasH1 && $hasM1) { // Pick logo for pair }
elseif ($hasL1) { // Pick logo }
elseif ($hasM1) { // Pick logo }
elseif ($hasH1) { // Pick logo }
else { // default logo }
Of course there are many other ways to implement this too.

Related

How to display multiple consecutive html elements

I'm using ACF on my wordpress site to display HTML text in the search bar next to post titles based on that posts array values.
Right now the script only displays up to 1 of the html values, but I want it to include all of the values if they exist.
add_filter( 'asp_results', 'asp_custom_field_to_results', 10, 1 );
function asp_custom_field_to_results( $results ) {
$custom_field = 'trade_status';
foreach ($results as $k=>&$r) {
if ($r->content_type != 'pagepost') continue;
if ( function_exists('get_field') )
$trade_status = get_field( $custom_field, $r->id, true ); // ACF support
else
$trade_status = get_post_meta( $r->id, $custom_field, true );
// Modify the post title to add the meta value
if ( !empty($trade_status) ) {
if ( in_array('30', $trade_status) ) {
$html = '<span class="new">New</span>';
} else if ( in_array('20', $trade_status) ) {
$html = '<span class="active">Active</span>';
} else if ( in_array('10', $trade_status) ) {
$html = '<span class="closed">Closed</span>';
} else {
$html = '';
}
$r->title = $html . $r->title;
}
}
return $results;
}
So, it looks like right now you're overwriting the value of $html for each matching iteration in the loop. My guess is that you'd want to concatenate (.=) rather than overwrite (=) when you're doing this.

How do I hide/show certain elements/divs if URL contains a specific string?

I have a large set of pages (page1/) that need to show a certain navigation bar and a second large set of pages (page2/) that need to show a different navigation bar in its place.
I have tried various jQuery to identify if the URL contains a certain word and, if it does, show the corresponding navigation bar - but with no success.
Below is the jQuery I've tried.
<script>
if(strpos($url ,'page1/') !== FALSE) {
echo '#page1-navigation-bar';
}
if(strpos($url ,'page2/') !== FALSE){
echo '#page2-navigation-bar';
}
</script>
This has no effect and I'm not sure whether this is because the coding is wrong, I've inputted it in the wrong place, I need to do something else as well as this coding or a combination of everything plus more.
Also not sure if this will hide one when showing the other?
Please help by stating any code needed and where exactly this needs inputting.
Thanks,
Michael
Maybe try like this in PHP:
<?php
$page = array("page1/" /*, "page2/", "page3/", "all other pages" */ );
if(in_array(strpos($url, $page))
{echo '#page1-navigation-bar';}
else
{echo '#page2-navigation-bar';}
?>
There are a couple ways you can go about this. You can do as WebSon has suggested but with a different approach, you can do it via page templates, or you can do it with custom post metas. Now note, while you're doing something with "ID's," I suggest you change the navigation displayed using wp_nav_menu().
One method with a suggested conditional, instead of ID's.
<?php
$first_array = [ 'page1', 'page3', 'page5' ];
$second_array = [ 'page2', 'page4', 'page6' ];
$wp_nav_args = [ //your default args ];
if ( is_page($first_array ) ) {
// Change the entire array or parts of it.
$wp_nav_args = [];
}
elseif ( is_page($second_array) ) {
// Change the entire array or parts of it.
$wp_nav_args = [];
}
wp_nav_menu($wp_nav_args);
Page Templates
<?php
$wp_nav_args = [ //your default args ];
if ( is_page_template('template-menu-a') ) {
// Change the entire array or parts of it.
$wp_nav_args = [];
}
elseif ( is_page_template('template-menu-b') {
// Change the entire array or parts of it.
$wp_nav_args = [];
}
wp_nav_menu($wp_nav_args);
More complicated way, which doesn't include templates, yet is extendable.
Just wanted to share this way, as you can use this for a few other things as well, by creating custom post metas. This example shows a checkbox in the Update/Publish box.
<?php
function add_custom_meta_field() {
$post_id = get_the_ID();
if ( get_post_type( $post_id ) !== 'page' ) {
return;
}
$value = get_post_meta( $post_id, '_navigation_b', true );
?>
<div class="misc-pub-section misc-pub-section-last">
<input type="checkbox" value="1" <?php checked( $value, true, true ); ?> name="_navigation_b" id="_navigation_b" /><label for="_navigation_b"><?php _e( 'Add To Your Calendar Icons', 'navy' ); ?></label>
</div>
<?php
}
add_action( 'post_submitbox_misc_actions', 'add_custom_meta_field' );
function save_custom_meta_field() {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( isset( $_POST['_navigation_b'] ) ) {
update_post_meta( $post_id, '_navigation_b', $_POST['_navigation_b'] );
} else {
delete_post_meta( $post_id, '_navigation_b' );
}
}
add_action( 'save_post', 'save_custom_meta_field' );

Conditional function that check if products are already in cart in Woocommerce 3

Hi solution provided here WooCommerce - Check if item's are already in cart working perfect. This is the function code:
function woo_in_cart($arr_product_id) {
global $woocommerce;
$cartarray=array();
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['product_id'];
array_push($cartarray,$_product);
}
if (!empty($cartarray)) {
$result = array_intersect($cartarray,$arr_product_id);
}
if (!empty($result)) {
return true;
} else {
return false;
};
}
Usage
$my_products_ids_array = array(22,23,465);
if (woo_in_cart($my_products_ids_array)) {
echo 'ohh yeah there some of that products in!';
}else {
echo 'no matching products :(';
}
But I need use as if(in_array) but no luck so far. What i doing wrong?
$my_products_ids_array = array("69286", "69287",);
if (in_array("69286", $my_products_ids_array)) {
echo '<p>' . the_field ( 'cart_field', 'option' ) . '</p>';
}
if (in_array("69287", $my_products_ids_array)) {
echo '<p>' . the_field ( 'cart_field-1', 'option' ) . '</p>';
}
Thank you
Your main function code is outdated.
For Advanced custom fields (ACF):
you need to use get_field() (that return the field value) instead of the_field() (that echo the field value).
You may need to add a product ID as 2nd argument in get_field('the_slug', $product_id ).
So try:
function is_in_cart( $ids ) {
// Initialise
$found = false;
// Loop Through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// For an array of product IDS
if( is_array($ids) && ( in_array( $cart_item['product_id'], $ids ) || in_array( $cart_item['variation_id'], $ids ) ) ){
$found = true;
break;
}
// For a unique product ID (integer or string value)
elseif( ! is_array($ids) && ( $ids == $cart_item['product_id'] || $ids == $cart_item['variation_id'] ) ){
$found = true;
break;
}
}
return $found;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
The custom conditional function is_in_cart( $ids ) accept a string (a unique product Id) or an array of product Ids.
Your revisited usage (ACF get_field may need a post ID (product ID)):
if ( is_in_cart( "69286" ) ) {
echo '<p>' . get_field ( 'cart_field' ) . '</p>'; // or get_field ( 'cart_field', "69286" )
}
if ( is_in_cart( "69287" ) ) {
echo '<p>' . get_field ( 'cart_field-1' ) . '</p>'; // or get_field ( 'cart_field', "69287" )
}

Pre-populate Gravity Form with multiple values from ACF

Here is a simple example of what I am trying to achieve:
I have a gravity form with different sections that will be shown conditionally by pre-populating dynamically. The thing is that I can't seem to populate them based on my ACF data (which are checkboxes as well).
If I put the values into the code it works like this:
add_filter( 'gform_pre_render_2', 'my_populate_checkbox' );
function my_populate_checkbox( $form ) {
foreach( $form['fields'] as &$field ) {
if( 11 === $field->id ) {
foreach( $field->choices as &$choice ) {
if( 'mychoice' === $choice['value'] || 'anotherchoice' === $choice['value'] ) {
$choice['isSelected'] = true;
}
}
}
}
return $form;
}
To get it to be populated dynamically I was trying something like this which didn't work (not that good with php):
add_filter( 'gform_pre_render_2', 'my_populate_checkbox' );
function my_populate_checkbox( $form ) {
foreach( $form['fields'] as &$field ) {
if( 11 === $field->id ) {
foreach( $field->choices as &$choice ) {
$addons = get_field('addons');
if( $addons === $choice['value'] ) {
$choice['isSelected'] = true;
}
}
}
}
return $form;
}
It's not working and I know I am missing something here but can't figure out what it is:/ Any help or pointers would be highly appreciated! I tried keeping it precise but if any more information is required please let me know and I will update the post accordingly.
Figured it out with some help:) In case anybody needs this functionality, here is how it works:
add_filter( 'gform_pre_render_2', 'my_populate_checkbox' );
function my_populate_checkbox( $form ) {
global $post;
$adfields = get_field( 'addons', get_the_ID() );
foreach( $form['fields'] as &$field ) {
if( 11 === $field->id ) {
foreach( $field->choices as &$choice ) {
if( in_array( $choice['value'] ,$adfields )) {
$choice['isSelected'] = true;
}
}
}
}
return $form;
}

(Wordpress) How to add a simple text to the contents of a specific category (php)

the following code in my function.php can almost do the job nice and clean to all single pages. the problem is I want it to be filtered for a specific category ID:
function wp_add_to_content( $content ) {
if( is_single() && ! empty( $GLOBALS['post'] ) ) {
if ( $GLOBALS['post']->ID == get_the_ID() ) {
$content .= 'Your new content here';
}
}
return $content;
}
add_filter('the_content', 'wp_add_to_content');
You don't need to use get_the_category and examine the results - Wordpress already has a function to check if your post is in a category: has_category. The advantage of this over get_the_category is that
you don't need the code to loop through all results to comparing the id (this is the part that is wrong in the other answer - it will only work if your post has one single category)
You can use not just the ID, but also the slug or name
You can check for multiple categories
The code you need is very simple, you just need to change one line!
function wp_add_to_content( $content ) {
if( is_single() && ! empty( $GLOBALS['post'] ) ) {
/* pass an array with the IDs/names/slugs of the categories to check for, e.g. */
if ( has_category( array(12) ) )
$content .= 'Your new content here';
}
return $content;
}
add_filter('the_content', 'wp_add_to_content');
UPDATE:
Even though it wasn't in your question, if you actually want to include the content on all posts as well, you just need to do this:
function wp_add_to_content( $content ) {
if( is_single() && ! empty( $GLOBALS['post'] ) ) {
$content .= 'Your new content here';
if ( has_category( array(12) ) )
$content .= '<br>Your new content here';
}
return $content;
}
add_filter('the_content', 'wp_add_to_content');
Modified your code idealy this condition is never making any sense because it always getting the id. $GLOBALS['post']->ID == get_the_ID()
function wp_add_to_content( $content ) {
if( is_single() && ! empty( $GLOBALS['post'] ) ) {
if ( $GLOBALS['post']->ID == get_the_ID() ) {
$content .= 'Your new content here';
}
//getting the current post
global $post;
$category_detail=get_the_category( $post->ID );
if(!empty($category_detail))
{
$catId = $category_detail[0]->term_id;
// instead of 2 put your category id
if($catId == 2 && $catId != 0 )
{
$content .= 'Your new content here';
}
}
}
return $content;
}
add_filter('the_content', 'wp_add_to_content');
Note : above code is for only default post not for custom taxonomy for custom taxonomy

Categories