0

Good afternoon,

I know I'm doing this wrong, looked at all the other questions but can't get it figured out. I have a tag list with images assigned that are displayed in a separate area of my site. I don't want to display all the tags assigned to the product, only the specific tags; they are TAG1, TAG2, and TAG3. I attempted to put the below <<< >>> in to see if it would work but to no avail. My best guess is I need to create an array to put the tag names in and inject them into the loop a different way.

Thanks in advance

    public function shortcode_custom_tags() {
    if ( is_product() || is_shop() ) {

        ob_start();

    
        global $product;
        //var_dump($product);
        $product_tags = get_the_terms( $product->get_id(), 'product_tag' );

        if ( ! is_array( $product_tags ) ) {
            return $product_tags;

        }
        ?>
    <div class="img-listings">
        <label style="font-weight: bold; font-size: 16px;">Works with</label>
        <ul>
            <?php
            foreach ( $product_tags as $product_tag ) {
        <<<<<<if ( $product_tag->slug = ["TAG1, "TAG2", "TAG3"]) {>>>>
                $img_url = get_option( 'z_taxonomy_image' . $product_tag->term_id );

                $this->format_setting( $product_tag->name, $img_url, $product_tag->term_id );
            <<<}>>>
            }
            ?>
        </ul></div>
            <?php
    } else {
        return;
    }
    return ob_get_clean();
}
1
  • Your PHP syntax is incorrect - you are reassigning $product->slug to the value ["TAG1", "TAG2", "TAG3"]. To check if a value is in an array, use in_array(). As this question seems to be about PHP rather than WordPress or it's APIs, it may be closed as off-topic for this stack.
    – bosco
    May 1, 2022 at 13:59

1 Answer 1

0

First: you're using = which assigns a value; use == to compare the values (or === to compare strictly, ie, match both the value and the type).

Second: Your code snippet shows that you've mismatched the "s in the array, which should probably result in a PHP fatal error. I'm assuming that's an error in the posted code but not in your production code.

Finally: your comparison will only work if $product_tag->slug matches the entire array shown. If you only want to check if $product_tag->slug matches one of the items in the array, you'll need to use in_array().

eg:

if ( in_array( $product_tag->slug, ["TAG1", "TAG2", "TAG3"] ) ) {
    $img_url = get_option( 'z_taxonomy_image' . $product_tag->term_id );

    $this->format_setting( $product_tag->name, $img_url, $product_tag->term_id );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.