1
votes

I'm trying to create a PHP while loop for WordPress that populates content to some Gravity Forms fields. I'm using Advanced Custom Fields with a repeater field to get the content and then trying to use eval() to create functions inside the while loop, like this:

if( have_rows( 'tickets', 'option' ) ) :

    while( have_rows( 'tickets', 'option' ) ) : the_row();

        $shortname = get_sub_field('short_name');
        $image = get_sub_field('image');

        add_filter( 'gform_field_value_' . $shortname . '_img', 'populate_' . $shortname . '_img' );
        eval("
            function populate_{$shortname}_img( $value ) {
                return $image;
            }
        ");

    endwhile;

endif;

The problem is that I'm getting this error:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'populate_test_img' not found or invalid function name in /srv/www/nordstan/htdocs/wp-includes/plugin.php on line 235

(I'm getting multiples of these, of course, and one of the $shortname variables are "test".)

However, if I'm changing "return $image" to "return 'test'", no error message is printed and the whole thing is executed correctly, so the functions are created.

What am I doing wrong?

Thanks in advance!

1
Why not just change , 'populate_' . $shortname . '_img' to a closure? , function ( $value ) { return $image }); Btw, you're returning $image, which is undefined in the scope of that function.Magnus Eriksson
Because it has to be the same name as the one used in add_filter? Or am I missing something out?Erik Blomqvist

1 Answers

1
votes

Change the order...because your eval doesn't run until after the add_filter, add_filter is failing to find the function (that doesn't exist until run time).

    $shortname = get_sub_field('short_name');
    $image = get_sub_field('image');

    eval("
        function populate_{$shortname}_img( $value ) {
            return '$image';
        }
    ");
    add_filter( 'gform_field_value_' . $shortname . '_img', 'populate_' . $shortname . '_img' );

also note that $image is a string and needs to be treated as such in the context of that eval'd code.