Execute php function only when clicked (wordpress)

后端 未结 3 1759
自闭症患者
自闭症患者 2021-01-17 02:17

For one of my wordpress site php files, I have the following code:

  
Items
3条回答
  •  攒了一身酷
    2021-01-17 02:56

    Though the idea behind is already illustrated by Raphael in his answer, I intervene to add some details.

    the best way to use AJAX with Wordpress is to use its built-in way of handling it, and that by sending requests to wp-admin/admin-ajax.php( I know the “admin” part of the file name is a bit misleading. but all requests in the front-end (the viewing side) as well as the admin can be processed in admin-ajax.php, with a lot of benefits, especially for security. And for the server-side code php that will be executed, it should be placed in functions.php.

    Your jQuery code will look something like:

     $(document).ready(function() {
            $('.tabs a').click(function(e) {
                e.preventDefault();
    
                var tab_id = $(this).attr('id'); 
    
    
                $.ajax({
                    type: "GET",
                    url: "wp-admin/admin-ajax.php", 
                    dataType: 'html',
                    data: ({ action: 'yourFunction', id: tab_id}),
                    success: function(data){
                              $('#tab'+tab_id).html(data);
                    },
                    error: function(data)  
                    {  
                    alert("Error!");
                    return false;
                    }  
    
                }); 
    
        }); 
    }); 
    

    infunctions.php of your theme (or directly in your plugin file), add:

    add_action('wp_ajax_yourFunction', 'yourFunction');
    add_action('wp_ajax_nopriv_yourFunction', 'yourFunction');
    

    and define in the same file yourFunction callback function like this:

        function yourFunction() {
    
    // get id
        // your php code
    
        die();
    
        }
    

    For the javascript part, take a look at ajax() and its shorthand get(). And for the best practices using AJAX with Wordpress, there are many tutorials on the web (I will be back to give one). Good luck

    Edit:

    As it is mentionned by Karl, you can use .load() instead of ajax(), It should be noted that .load() is just a wrapper for $.ajax(). It adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...) which internally calls .ajax().

    But my original answer is on how to organize php code respecting Wordpress best practices.

提交回复
热议问题