Search code examples
phpwordpresswordpress-themingcustom-wordpress-pageswordpress-admin

WordPres how to display the value of a variable from function.php file in my custom page?


With this chunk of JavaScript code, I add, fetch, and pass the ID of the post (like an array) to the function.php file.

  const nonRegister = document.querySelectorAll('.non-register')
  nonRegister.forEach(item=>{
  item.addEventListener('click', function(){
    let postNumber = item.getAttribute('data-post-id');
    let myFavoriteArray = JSON.parse(localStorage.getItem("favoriteItems") || "[]");
    let retrievedData = localStorage.getItem("favoriteItems");
    let retrievedDataArray = JSON.parse(retrievedData);
    if(retrievedDataArray !== null && retrievedDataArray.includes(postNumber)){
        alert('This model has already been added to favorites')
    }else{
        myFavoriteArray.push(postNumber);
        localStorage.setItem("favoriteItems", JSON.stringify(myFavoriteArray));
        let forConversion = JSON.parse(retrievedData);
        data = {
            'action': 'vicso_non_register',
            'forConversion': forConversion,
        }
            jQuery.ajax({
               type:'post',
               url: object_url.url,
               data: data,
               cache: false,
               success: function(data){
                 console.log(data)
               }
           });
         }
      })
   })

This is my code in a function.php file.

add_action( 'wp_ajax_nopriv_vicso_non_register', 'vicso_non_register' );
add_action( 'wp_ajax_vicso_non_register', 'vicso_non_register' );

function vicso_non_register(){

    $favorite_array    = $_POST['forConversion'];
    echo   $test = json_encode(array('favorite_array'=>$favorite_array));

    die;
}

But how do I get to the array that the function returns? I need a PHP array with these data on the fav_models.php for example.

If someone can suggest, please help.


Solution

  • Sending data back as the ajax response in json format:

    You could use wordpress wp_send_json_success and wp_send_json_error functions.

    add_action( 'wp_ajax_nopriv_vicso_non_register', 'vicso_non_register' );
    add_action( 'wp_ajax_vicso_non_register', 'vicso_non_register' );
    
    function vicso_non_register(){
    
        $favorite_array    = sanitize_text_field($_POST['forConversion']);
      
        wp_send_json_success($favorite_array); 
    
       // or you could send it via  "wp_send_json_error", if you need to!
    }
    

    And on the front end, you could console.log the response returned from function.php.

    You could read more about these two functions on the documentation page.

    WordPress wp_send_json_success function
    WordPress wp_send_json_error function


    Sending data to another page:

    There are multiple ways to do it, you could localize your script or I'd prefer to send it as a query_var/query string.

    add_action( 'wp_ajax_nopriv_vicso_non_register', 'vicso_non_register' );
    add_action( 'wp_ajax_vicso_non_register', 'vicso_non_register' );
    
    function vicso_non_register(){
    
        $favorite_array    = sanitize_text_field($_POST['forConversion']);
    
        wp_send_json_success($favorite_array); // send the data back to the ajax call
      
        if(!empty($favorite_array)){
          wp_safe_redirect(site_url('/fav_models.php/?favorite='.$favorite_array));
          exit;
        }
        
    }
    

    Then on the "fav_models.php" you could access that value by using this:

    $new_page_variable = isset($_GET["favorite"]) ? sanitize_text_field($_GET["favorite"]) : ""