I have added a custom field to my site called "dansk_url", to which a link to the version in Danish (different domain) will be entered. I would like to be able to output this as a shortcode to add anywhere within the post, and it should appear as a link (anchor text will always be "Dansk" and whichever url has been entered in the custom field for that post.
Is this possible? I prefer a non-plugin solution.
I have added a custom field to my site called "dansk_url", to which a link to the version in Danish (different domain) will be entered. I would like to be able to output this as a shortcode to add anywhere within the post, and it should appear as a link (anchor text will always be "Dansk" and whichever url has been entered in the custom field for that post.
Is this possible? I prefer a non-plugin solution.
Share Improve this question asked Apr 26, 2019 at 1:40 auntieauntie 351 silver badge5 bronze badges 3- 1 How did you add the custom field? Using custom code? If so, what's your code? – Sally CJ Commented Apr 26, 2019 at 3:36
- 1 post some code so that other developers could see where you stuck at. – maverick Commented Apr 26, 2019 at 3:45
- Sorry, I didn't add any code. I used the instructions here link – auntie Commented Apr 26, 2019 at 3:49
2 Answers
Reset to default 0Put this in functions.php
of your theme.
add_shortcode( 'dansk_url', 'dansk_url' );
function dansk_url() {
$output='';
$the_url= get_post_meta( get_the_ID(), 'dansk_url', true );
if ( $the_url) $output .= '<a href="' . esc_url( $the_url) . '">Dansk</a>';
return $output;
}
and use shortcode [dansk_url]
in the post.
I would like to be able to output this as a shortcode to add anywhere within the post
So since you said, "I prefer a non-plugin solution", then you can use this (which you'd add to the theme functions.php
file) to create the shortcode:
add_shortcode( 'dansk_link', 'dansk_link_shortcode' );
function dansk_link_shortcode() {
ob_start();
$url = get_post_meta( get_the_ID(), 'dansk_url', true );
if ( $url ) : ?>
<a href="<?php echo esc_url( $url ); ?>">Dansk</a>
<?php
endif; // end $url
return ob_get_clean();
}
And in the post content, add [dansk_link]
anywhere you like.
The above PHP code is still considered a plugin, but it's basically "your own" plugin. :)
PS: For the function reference, you can check add_shortcode()
and get_post_meta()
.
UPDATE
I changed the shortcode name to
dansk_link
because that seems better thandansk_url
for what the shortcode is for (i.e. outputting a link).In my original answer, I used output buffering (i.e. those
ob_start()
andob_get_clean()
) so that's it's easier for you (the question author) to edit the HTML output.
Having said the point #2 above, you could also use:
add_shortcode( 'dansk_link', 'dansk_link_shortcode' );
function dansk_link_shortcode() {
if ( $url = get_post_meta( get_the_ID(), 'dansk_url', true ) ) {
return '<a href="' . esc_url( $url ) . '">Dansk</a>';
}
return '';
}