The difference between wrapping a require_once inside a conditional statement and not doing so in functions.php

StackOverflow https://stackoverflow.com/questions/17188905

  •  01-06-2022
  •  | 
  •  

Question

Without the conditional statement:

require_once( dirname( __FILE__ ) . "/edit_info_check_password.php" );

works fine. But by simple adding:

if(  substr($_SERVER["REQUEST_URI"], 18, 13) == "edit-userinfo" )
require_once( dirname( __FILE__ ) . "/edit_info_check_password.php" );

inside the functions.php file, then the functions inside the required file do not work completely. But they work partially. Why can't I keep the condition if i only want to include the file for a certain page?

EDIT - additional requested info:
basically trying to add the following actions inside the required file:

add_action( 'wp_enqueue_scripts', 'admin_ajax_setup' );
add_action( 'wp_ajax_ajax-checkpasswords', 'check_info_passwords' );
add_action("wp_ajax_nopriv_ajax-checkpasswords", "check_info_passwords");

The admin ajax setup function runs perfectly, it enqueues two javascript files and localized the admin ajax for javasscript access. That's great, but my jquery ajax function returns response 0. Whereas without the conditional statement, I get the full response. Obviously adding the condition changes the way functions.php works with required files.

Was it helpful?

Solution

The reason this does not work is because your ajax admin hooks are not being called.

The reason the ajax hooks are not called is because they are not called at the "edit-userinfo" page. Those ajax calls are handled at a different page. Your require will only load on the "edit-userinfo" page.

The best solution I have is to wrap the ajax hooks in the init hook and the add an is_admin conditional check.

This means that you will need to include your file without the conditional. I don't think performance should be an issue if that file is included every time.

You setup your file like this:

if(  substr($_SERVER["REQUEST_URI"], 18, 13) == "edit-userinfo" )
    add_action( 'wp_enqueue_scripts', 'admin_ajax_setup' );

function init_admin_ajax_hooks()
{
    if (is_admin()) {
        add_action( 'wp_ajax_ajax-checkpasswords', 'check_info_passwords' );
        add_action("wp_ajax_nopriv_ajax-checkpasswords", "check_info_passwords");
    }
}
add_action('init', 'init_admin_ajax_hooks');

I left your enqueue script hook as is because I'm not sure if it's in the admin or not.

If it is in the admin you should use admin_enqueue_script hook instead:

if(  substr($_SERVER["REQUEST_URI"], 18, 13) == "edit-userinfo" )
    add_action( 'admin_enqueue_scripts', 'admin_ajax_setup' );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top