phpajaxwordpressadvanced-custom-fieldsadd-filter

How to pass variable from function to acf add_filter('acf/load_field/name=marcatore


Good morning everyone, I'm new here, I'm going crazy with this problem. I need to pass a variable $sel from the func. "my_action" into to funct "get_players". The variable is always evaluated except in the "get_players" function where it is always null. Can someone help me? Thank you.


function my_action() {

    global  $selezionato;

    $selezionato = isset($_POST['selezionato']) ? $_POST['selezionato'] : '';
    echo $selezionato;  //here is evaluated  and works
     
    wp_die();
}

add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');




function get_players($field) {

    global  $selezionato;
    echo  $selezionato; // IS ALWAYS NULL !!


    $field['choices'] = array();

    $args = array(
        'numberposts'   => -1,
        'post_type'     => 'players',
        'meta_key'      => 'club',
        'meta_value'    => $selezionato // IS ALWAYS NULL !!

        //  'orderby' => 'title',
        // 'order' => 'ASC'


    );

    $the_query = new WP_Query($args);

    if ($the_query->have_posts()) {

        // global $post;
        while ($the_query->have_posts()) {
            $the_query->the_post();

            $value = get_field('numero');

            $label = get_the_title();

            // append to choices
            $field['choices'][$value] = $label;
        }

        wp_reset_postdata();
    }

    return $field;
}

add_filter('acf/load_field/name=marcatore-casa',  'get_players');

I tried to make the $selezionato variable global and I expected to pass value of var $selezionato it to the "get_players" function


Solution

  • Store the variable value in an option db using the hook 'update_option()' as shown below:

    function my_action() {
        $selezionato = isset($_POST['selezionato']) ? $_POST['selezionato'] : '';
        echo $selezionato;  // here is evaluated and works
        update_option('my_action_selezionato', $selezionato); // Store the value in an option
        wp_die();
    }
    
    add_action('wp_ajax_my_action', 'my_action');
    add_action('wp_ajax_nopriv_my_action', 'my_action');
    

    Use the hook 'get_option()' to retrieve the value of the variable in get_players function as shown below:

    function get_players($field) {
        $sel = get_option('my_action_selezionato'); // Retrieve the value from the option
        echo $sel; // Should now display the correct value
    
        // Rest of your code...
    
        return $field;
    }
    
    add_filter('acf/load_field/name=marcatore-casa',  'get_players');