Blog
Next Post »

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

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:

<?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:

<?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; ?>" />
  Was this post helpful?  

1 Star2 Stars3 Stars4 Stars5 Stars 3 votes | 5.00 average

Loading ...  Loading ...
Email This Post

One Comment

Trackbacks / Pingbacks

Leave a Reply

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.

« Previous Post

Calendar