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; ?>" />
0 Comments
1 Pingback
[…] to http://www.tech-otaku.com/blogging/posts-id-posts-url-wordpress/ for posting it […]