php - Get first URL from post content

Basically all I want to do is if the post format is "link" rather than link to the post from the blog index, l

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'];
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745578541a4634113.html

相关推荐

  • php - Get first URL from post content

    Basically all I want to do is if the post format is "link" rather than link to the post from the blog index, l

    11小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信