I’m trying to do an ajax request from my themes header.php file. I’ve read that I have to use the admin-ajax.php file to achieve this. So I looked for examples and found this one.

My code in the header.php file looks like this:

    $('.test a').click(function(){
        var className = $(this).attr('class');

            url: "<?php echo admin_url('admin-ajax.php'); ?>",
            data: {
                'action': 'myFunc',
                'id': className
            success: function(res){
            error: function(err){
                alert("Error: " + err);

And my PHP code looks like this:

function myFunc() {
    echo "hello";

add_action('wp_ajax_nopriv_myFunc', 'myFunc');

I’m not sure where I should put this PHP code. Should I put this in my functions.php file or directly to the admin-ajax.php file? It doesn’t matter where I put the PHP code, the output is always 0 (the last line in admin-ajax.php is die('0')). Or is it because of my url parameter?

Read more here: doing an ajax request always outputs 0


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: