Basically all I want to do is if the post format is "link" rather than link to the post from the blog index, link to the link pasted within the post content.
In my index.php I have:
<h3>
<a href="<?php get_post_format() == 'link' ? some_function_here() : the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h3>
Obviously some_function_here() is not real. I am sure I saw a function on the Wordpress codex that does this (pulls the first link from a post) but I can not find it now.
Basically all I want to do is if the post format is "link" rather than link to the post from the blog index, link to the link pasted within the post content.
In my index.php I have:
<h3>
<a href="<?php get_post_format() == 'link' ? some_function_here() : the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h3>
Obviously some_function_here() is not real. I am sure I saw a function on the Wordpress codex that does this (pulls the first link from a post) but I can not find it now.
Share Improve this question asked Apr 17, 2019 at 15:43 caffeinehighcaffeinehigh 2051 silver badge9 bronze badges1 Answer
Reset to default 1I think this question might put you in the right direction.
In case that link is broken, here's the answer as provided by Jon Fabry in that thread.
$post_link = get_the_permalink();
if ( preg_match('/<a (.+?)>/', get_the_content(), $match) ) {
$link = array();
foreach ( wp_kses_hair($match[1], array('http')) as $attr) {
$link[$attr['name']] = $attr['value'];
}
$post_link = $link['href'];
}
This would grab EACH link provided within the content. You can add a counter or a true false condition to just snag the first one.
So the final code would be something like
$post_link = get_the_permalink();
$first = true;
if ( preg_match('/<a (.+?)>/', get_the_content(), $match) ) {
$link = array();
foreach ( wp_kses_hair($match[1], array('http')) as $attr) {
if ( $first ) {
$link[$attr['name']] = $attr['value'];
$first = false;
} else {
// ignore it
}
}
$post_link = $link['href'];
}