Jono Thorne
Jono Thorne

Reputation: 51

Cannot set variable within IF Statement for some reason

Really not sure what's going on here, but this just isn't working! Anyone have any ideas on this?

I've tried this:

if(article_custom_field('product-type') !== '') {
    if(article_custom_field('product-type') == 'cd') return $productType = 'cd'; 
    if(article_custom_field('product-type') == 'audio') return $productType = 'headphones'; 
    if(article_custom_field('product-type') == 'video') return $productType = 'facetime-video'; 
    if(article_custom_field('product-type') == 'download') return $productType = 'save'; 
    if(article_custom_field('product-type') == 'book') return $productType = 'book'; 

} else {
    $productType = 'eye-open';
}

And this:

if(article_custom_field('product-type') === 'cd') {
    $productType = 'cd';
} elseif(article_custom_field('product-type') === 'video') {
    $productType = 'facetime-video';
} elseif(article_custom_field('product-type') === 'audio') {
    $productType = 'headphones';
} elseif(article_custom_field('product-type') === 'download') {
    $productType = 'save';
} elseif(article_custom_field('product-type') === 'book') {
    $productType = 'book';
} else {
    $productType = 'eye-open';
}

The aim to to change this:

<span class="product-type">
   <img src="<?php echo theme_url('/assets/glyphicon-' . $productType . '.png'); ?>" width="25" alt="Product Type" class="img-responsive">
   <?php echo article_custom_field('product-type'); ?>
</span>

Any ideas as to what I am doing wrong and why this code just isn't working for me? Whatever I set the 'article_custom_field('product-type') to, I still get 'eye-open'. What's the deal?

Here is the 'article_custom_field()' function:

function article_custom_field($key, $default = '') {
    $id = Registry::prop('article', 'id');

    if($extend = Extend::field('post', $key, $id)) {
        return Extend::value($extend, $default);
    }

    return $default;
}

Upvotes: 1

Views: 54

Answers (2)

Jono Thorne
Jono Thorne

Reputation: 51

Spent ages trying to figure out what this was,

and then it just occurred to me.

I FORGOT to put the switch/if statement inside the while loop. DUH - Rookie mistake!

Upvotes: 0

Alex Andrei
Alex Andrei

Reputation: 7283

Your initial if clause is testing whether the value is blank, else it will return 'eye-open', so you will always get the 'eye-open' value.

Try to use a switch-case structure and return at the end of the function.

$cField = article_custom_field('product-type');
switch (trim($cField)){
    case 'cd':
        $productType = 'cd';
    break;
    case 'audio':
        $productType = 'headphones';
    break;
    case 'video':
        $productType = 'facetime-video';
    break;
    case 'download':
        $productType = 'save';
    break;
    case 'book':
        $productType = 'book';
    break;      
    default:
        $productType = 'eye-open';
    break;
}
return $productType;

Upvotes: 2

Related Questions