Soil relative url's in ajax action

Hi there,

On my site I’m using jQuery ajax to load more posts:

$.ajax({
	url : window.wp.ajax_url,
	type: 'post',
	data: {
		action: 'load_more_work',
		skip,
		load,
		pageId,
		lang
	},
	success: (response) => {
		// show new posts
	}
	error: (jqXHR, error) => {
		console.log(jqXHR.responseText, error);
	}
});

In my functions.php:

add_action('wp_ajax_nopriv_load_more_work', 'loadMoreWork');
add_action('wp_ajax_load_more_work',        'loadMoreWork');

public function loadMoreWork() {
	if (isset($_REQUEST['pageId'])) {
		$id = $_REQUEST['pageId'];

		// What should I call here to re-init soil root_relative_url?
		// do_action('after_setup_theme', '\\Roots\\Soil\\load_modules', 100);

		$work_ids   = get_field('featured_work', $id);
		$work_cases = getWorkCases($work_ids);
		$data       = Timber::compile('partials/blocks/b-cases.twig', ['work' => $work_cases['cases']]));

		echo wp_send_json_success($data);
		wp_die();
	}
}

function getWorkCases($ids = []) {
	$cases  = [];
	if ($ids) {
		foreach ($ids as $id) {
			$cases[] = array(
				// permalink is not relative?
				'permalink' => apply_filters('the_permalink', get_permalink($id))
			);
		}
	}

	return $cases;
}

However the returned permalinks are not relative in my ajax action. They are relative when I call my getWorkCases function normally.

Should I somehow re-init any filters or actions in order to make Soil’s relative url’s work with ajax?

Thanks!

I think the reason may be due to this line here:

Try changing it to this:

if ((is_admin() && ! wp_doing_ajax()) || isset($_GET['sitemap']) || in_array($GLOBALS['pagenow'], ['wp-login.php', 'wp-register.php'])) {

If that works then you’ll need to open the issue on the GitHub repo.

Thanks!
Gonna try that first thing in the morning, but that is_admin call is probably the issue indeed!

Unfortunately, this didn’t fix it.

If I log the booleans is_admin() and wp_doing_ajax() in my loadMoreWork ajax action, they’re both true so I understand why the Soil relative url’s wouldn’t work, but that conditional is only exectued once it seems. Even if I remove the whole is_admin check, it still doesn’t work.

I think the Soil module needs to be re-initialized somehow in Ajax?

However, if I use the root_relative_url function directly in my getWorkCases function, it does return the relative url in my ajax action:

'permalink' => \Roots\Soil\Utils\root_relative_url(get_permalink($id))

This fixes it for now, but I guess this should be wrapped in a conditional to check if Soil relative url’s are activated…

There’s another is_admin check here:

Does removing that or including ! wp_doing_ajax() help?

Yup that did the trick!
Wherever is_admin is checked, wp_doing_ajax should be excluded!

Do you want me to make a PR on Github?
Thanks for your help!

No problem.

Definitely worth submitting and issue and PR for that :slight_smile:

This topic was automatically closed after 42 days. New replies are no longer allowed.