PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to check for an array of product Ids in WooCommerce

 May 09, 2022     arrays, php, product, woocommerce, wordpress     No comments   

Issue

I am changing the text of the Add to cart button on shop pages in WooCommerce for specific products:

add_filter( 'woocommerce_product_add_to_cart_text', 'add_to_cart_text' );
function add_to_cart_text( $default ) {
    if ( get_the_ID() == 1 ) {
        return __( 'Text1', 'your-slug' );
    } elseif ( get_the_ID() == 2 ) {
        return __( 'Text2', 'your-slug' );
    } elseif ( get_the_ID() == 3) {
        return __( 'Text3', 'your-slug' );
    } else {
        return $default;
    }
}

If I have two or more IDs that need to have the same button text, how can I add an array of these ids into my function?


Solution

You can use in_array() PHP conditional function like:

add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text', 10, 2 );
function custom_add_to_cart_text( $text, $product ) {
    if ( in_array( $product->get_id(), array(1) ) ) {
        $text = __( 'Text1', 'text-domain' );
    } elseif ( in_array( $product->get_id(), array(2) ) ) {
        $text = __( 'Text2', 'text-domain' );
    } elseif ( in_array( $product->get_id(), array(3, 4) ) ) {
        $text = __( 'Text3', 'text-domain' );
    }
    return $text;
}

It should work.

Also you should use $product missing arguments in your hooked function.



Answered By - LoicTheAztec
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing