最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Get first URL from post content

programmeradmin1浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

I 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'];
}
发布评论

评论列表(0)

  1. 暂无评论