Getting a Post’s ID from the Post’s URL in WordPress

G

I’ve just implemented a new AJAX contact form on my blog. In the submission confirmation I wanted to show a link back to the post the user was viewing when they requested the contact form.

It was simple enough to get the post’s URL by querying the HTTP_REFERER string in the form and then passing the value to the PHP file that processes it using a hidden form element:

Dummy Content
<?php $url = getenv('HTTP_REFERER'); ?>

<div id="contact">

	<div id="message"></div>
     			
	<form method="post" action="/wp-content/ajax-contact-form/contact.php" name="contactform" id="contactform">
	
		<fieldset>
		
			<input name="referring_page" type="hidden" id="referring_page" size="30" value="<?php echo $url; ?>" />

 

 

This allowed me to create a link to the referring post with some generic link-text: Return to previous post. Ideally though, I wanted to be able to use the post’s title as the link-text. Simple enough I guess, but it took a fair bit of Googling to find reference to a perhaps not-so-well documented WordPress function that would allow me to do this: url_to_postid().

Now, by passing the post’s URL to url_to_postid() I was able to get the post’s ID and subsequently its title:

Dummy Content
<?php $url = getenv('HTTP_REFERER'); ?>
<?php $title = get_the_title(url_to_postid($url)); ?>

<div id="contact">

	<div id="message"></div>
     			
	<form method="post" action="/wp-content/ajax-contact-form/contact.php" name="contactform" id="contactform">
	
		<fieldset>
		
			<input name="referring_page" type="hidden" id="referring_page" size="30" value="<?php echo $url; ?>" />
			<input name="post_title" type="hidden" id="post_title" size="30" value="<?php echo $title; ?>" />

 

 

About the author

A native Brit exiled in Japan, Steve spends too much of his time struggling with the Japanese language, dreaming of fish & chips and writing the occasional blog post he hopes others will find helpful.

1 response

0 Comments

1 Pingback

Steve

Recent Comments

Recent Posts