I run a few side blogs that I sort of aggregate into my main blog.
I use simplepie to parse the feeds from my other blogs, so the posts are being created automatically.
My typical post is layed out like this:
- IMAGE
- CONTENT/TEXT
- HYPERLINK
What I'm looking to do is automatically grab the hyperlink, and insert it into a Custom Field. The custom field already exists in the post, but I need to insert the hyperlink contained in the post content as the value.
I would need just the link, without the html, so the value would be just a straight link - http://domain.com/fsdds
I know there are a number of plugins that accomplish this with images, but I haven't seen anything that will do it with anything else, like hyperlinks.
I posted this question over at the Wordpress forums and was told I'd have to parse the entire post content looking for the links, which I knew, the problem is I'm not too sure how to do that.
Thanks
Building on Anthony's answer, use the UPDATE POST META once you have your link...
Put this in your functions.php file:
function catch_that_link() {
global $post, $posts;
$first_link = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/(https?://)?(www.)?([a-zA-Z0-9_%]*)\b.[a-z]{2,4}(.[a-z]{2})?((/[a-zA-Z0-9_%])+)?(.[a-z])?/', $post->post_content, $matches);
$first_link = $matches [1] [0];
if(empty($first_link)){ //Defines a default image
return 'no link found';
}
return $first_link;
}
Then in your query loop, category file or whatever php file you would do the following
<?php
$post_id = 13; //replace the number with the specific post
$meta_key = 'key_example' //replace with your custom field name
$meta_value = catch_that_link();
update_post_meta($post_id, $meta_key, $meta_value);
?>
This is the function that grabs the first image in a post:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
you would just need to replace the first preg_match_all parameter to:
'/(https?://)?(www.)?([a-zA-Z0-9_%])\b.[a-z]{2,4}(.[a-z]{2})?((/[a-zA-Z0-9_%])+)?(.[a-z]*)?/'
Add the whole function to your functions.php, and call that function from your script.
It should return the first link it finds in the post content.
I've been thinking about this myself and the solution has to be to run a function on the save_post action hook. Unfortunately this is undocumented in the Wordpress Codex and I haven't had time to look further afield yet.
Just stumbled upon this Function Reference/add post meta
Still need a way to grab the hyperlink from the post and and insert it as the $metavalue though.