1

I want to show some simple things on homepage with ajax. The problem is I want to load everything when is_home() is true. Php, js, everything.

In funtions.php:

add_action('init', 'pint_functions_separation_test');
function pint_functions_separation_test(){
     if ( is_home() ) {
          require_once('functions_hometest.php');
     }
}

functions_hometest.php:

<?php
if (file_exists("./wp-load.php") && file_exists("./wp-blog-header.php")){
    define('WP_USE_THEMES', false);
    require_once("./wp-load.php");
    require_once("./wp-blog-header.php");
}

add_action( 'wp_ajax_nopriv_ajaxtest', 'ajaxajaxtest_handle_request' );
add_action( 'wp_ajax_ajaxtest', 'ajaxajaxtest_handle_request' );

function ajaxajaxtest_handle_request() {

  echo json_encode("evo me");

  die();

}
?>

JS:

<script>
jQuery(document).ready(function () {
    jQuery.ajax({
        url: '<?php echo admin_url( 'admin-ajax.php'); ?>',
        data: ({
            'action': 'ajaxtest',
        }),
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            jQuery("#test_div_id").html(data);
        }
    });
});
</script>

Wordpress on homepage loads functions_hometest.php but ajax returns 0.

And if I call php file just with

 require_once('functions_hometest.php');

everything works great, but I wan't to keep loading of functions on bare minimum. Does that make any sense?

PS. I tried to call with

add_action('get_header', 'pint_functions_separation_login');

but i get the same results.

Thank you

2

Use:

if ( is_home() or ( defined( 'DOING_AJAX' ) && DOING_AJAX ) )

is_home() returns TRUE on the front-end only, admin-ajax.php on the other hand is an admin page. So you need to check both conditions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.