Search code examples
phpwordpresshyperlinkmetadatahref

PHP Output in <a> is Different from Outside of Tag


I'm filling the <a href=" with a custom URL field in Wordpress, and the "key" ("resource-link") has to be stripped from the value (URL).

The PHP code I'm using outputs the correct result when not placed in the <a> tag, but when I put the code into the tag, my result is the Wordpress site URL plus the custom URL for the post.

Why is it adding the custom URL for the post to the existing URL of the post and how can I strip everything but the custom URL?

Code:

<a href="<?php $key="resource-link"; 
echo get_post_meta($post->ID, $key, true); ?>">Learn More</a>

Actual Output NOT in <a>:
www.legalstore.com

Expected Output in <a>:
www.legalstore.com

Actual Output in <a>:
www.lawpracticeresource.com/category/www.legalstore.com


Solution

  • I recommend you use esc_url()

    <a href="<?php $key="resource-link"; 
    echo esc_url(get_post_meta($post->ID, $key, true)); ?>">Learn More</a>