skip to Main Content

I’m trying to create custom function in WordPress with ACF, and use it as a shortcode.

What I want to do is quite simple:

  • Get a field from ACF
  • Check if the text is "not found" or something else
  • If it’s something else, I’ll show an H2 and a sentence with field content.
  • If its "not found" I don’t want to show anything

I tried various code, here’s my last one:

// write a shortcode that creates a text if the field is not "not found"

function show_alliance() {
    $alliance = get_field('field_6383d4b46deed');

    if ($alliance !='not found'): {
        return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
    }
    else: {
        return '';}
    }

add_shortcode('alliance', 'show_alliance')

By WordPress always comes up with errors when I save my snippet. I can’t find a way to make it work.

(I use Code Snippets in WordPress)

Any ideas?
(I’m sure it’s very simple…)

Tried different syntax, but WordPress never validates the code snippet.

Last one is:

`L’extrait de code que vous essayez d’enregistrer a produit une erreur fatale à la ligne 11 :

syntax error, unexpected ‘}’`

When I delete the } to put it a the end it tells me that I should not have it there…

2

Answers


  1. Chosen as BEST ANSWER

    Here's the answer that works :

    function show_alliance() {
        $alliance = get_field('field_6383d4b46deed');
        if ($alliance !='not found') {
            return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
        }
        else {
            return '';
        }
    }
    add_shortcode('alliance', 'show_alliance');
    

  2. Please try this code I think this is working fine.

    **PHP Code**
    
    <?php if(get_field('field_6383d4b46deed')){ ?><h2>TITLE</h2><p>This is... '. $alliance .' </p>
    else ?>
    echo' ';
    <?php } ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search