1

I'm writing ajax handling for a theme. I'm trying to get term and taxonomy slugs from a link I click. The link is being passed with jQuery to PHP for further processing.

Let's say my custom taxonomy is "tax" and term within that taxonomy is "abc":


Example:

link I click looks like this - https://localhost/test/tax/abc/.

It's being parsed with wp_parse_url(). After parsing URL and fiddling with it a little I get "abc" as my term slug and "tax" as my taxonomy slug.

Then I use get_term_by( 'slug', 'abc', 'tax' ) and get term data this way. Simple.


Problem occurs when taxonomy slug is rewritten.

Example 2:

Let's say I've rewritten my custom taxonomy slug "tax" with 'rewrite' => array( 'slug' => 'tax-rewrite' ), passed to register_taxonomy().

Now link I click looks like this: https://localhost/test/tax-rewrite/abc/.

When I pass it to get_term_by() as "tax-rewrite" it fails because get_term_by() needs original taxonomy slug which in this case is still "tax", but I can't get it from the link anymore.

Is there a way to get original taxonomy slug from rewritten link, get original taxonomy slug from rewrite slug, or any other way to get term data for my ajax handling?

Best regards, Dan.

  • What AJAX handling are you doing? Is there a reason you're trying to parse this from the URL? Why not just send the taxonomy as part of the AJAX request? – Jacob Peattie Sep 8 at 8:09
  • Yes, there is a reason, URL is readily available in website's wp_nav_menu(). Actually I could get menu item ID with jQuery and then play a bit with get_post_meta( $menu_item_id, '_menu_item_object_id', true ); to get post ID or term ID associated with that particular menu item, but I'm trying to bring down the amount of code to necessary minimum. Hence use of link URL of main nav menu seems to be a reliable option. – Daniel Sep 8 at 8:21
  • Why not just make the AJAX request directly to that URL and pull the HTML out of the response? That’s a common pattern and I believe jQuery even has helped functions for it. Then there’s no backend code at all. Otherwise you’re going to be wasting a lot of time implementing routing functionality that already exists. – Jacob Peattie Sep 8 at 9:11
  • @JacobPeattie And with pure jQuery how server would know what content to serve to the browser? – Daniel Sep 9 at 19:49
  • I don't understand the question. It will just return the HTML for the page... – Jacob Peattie Sep 10 at 0:23

Your Answer

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

Browse other questions tagged or ask your own question.