Skip to content
Advertisement

WordPress redirect to ID from slug

I have a front-end editing form, where users can update specific post data (ACF custom fields). The problem is, that the users only know the post slug, not the ID.

So I need a page before, where I can convert the slug to post ID, then pass it as a url parameter, and redirect to the update page above.

I know the url_to_postid(site_url(“slug”)) function, but I don’t know how can I pass the slug (from a form or a textbox) to this function, then redirect to a url with the parameter.

Advertisement

Answer

Let me know on which of the following steps you want me to explain further.

  • create a page template in your theme, code below
  • create a page that uses that template. now you have url for ajax from your front-end.
  • if it’s on same domain you can use ajax fetch. if it’s on another domain you can use jsonp which is same idea..

sample code for template file (not tested):

<?php 
/* Template Name: My Service */ 
$slug = $_REQUEST['slug'];
$id = url_to_postid(site_url($slug))
echo $id;
exit();
// or
echo json_encode(['id'=>$id]);
// or
// redirect to url + id

Update – Non ajax solutions

First 2 steps as before. Then make a <form> around that button and <input name="slug"> that submits the to the address of the page you prepared in step 2.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement