Coding Hints

These are little coding hints – mostly for PHP – I write for myself when I find the search results aren’t that great (for me, at least).

  • ACF Illegal String Offset

    When using Advanced Custom Fields in WordPress, I often get and use a custom link field like this:

    <?php
    $link = get_field( 'link' );
    $link_url = $link['url'];
    ?>

    When doing this, PHP will gently remind me with a notice that I have used an illegal string offset.

    Warning: Illegal string offset ‘url’…

    The top result in Google send us to this ACF support page. I usually figure out the problem right away with these support links, but this one was a little difficult for me to follow, as it winds through some different possibilities, including a plugin conflict.

    The answer lies within the responses, though: “the field is returning false.” I often use ACF to check if a value is present on a page. If it is, something happens. The field return false if the field is NOT present on the page. That means the conditional is not true and PHP 7.1 considers this illegal for using a variable array.

    The solution is really simple and is the standard way of testing to see if the value is true or false: using a conditional.

    <?php 
    $link = get_field( 'link' );
    if ( $link) :
    $link_url = $link[ 'url' ];
    endif;
    ?>

    The code added was “if ( $link ) :” and it’s ending statement “endif;”.

    Here’s the ACF Link documentation for reference.

    This note is mostly so I can get to the answer quickly and learn it more deeply myself, but I hope it helps you if happen across it, too.