Working on a Wordpress site and where I need to have a post with php content. I figured out that this is only possible with a plugin or a shortcode in the functions.php
Googled around, tried a lot but it isn't working out, so i definitely doing something wrong.
code I have in functions.php:
function anniversary_link($text) {
$url = the_permalink();
return "<a href='$url'>$text</a>";
}
add_shortcode('permalink', 'anniversary_link');
and the result I get when clicking the link:
The shortcode has to reference to the single.php page and al the static code's references to the single.php page is just:
<?php the_permalink() ;?>
Is this te 'correct' way to use href on a post (is there a better/cleaner way to get this working)?
Edit
Updated my code thanks to nathan Edit edit: in functions.php
function anniversary_link( $atts ) {
$atts = shortcode_atts( array(
'text' => '',
), $atts, 'permalink' );
$url = get_permalink();
return '<a href="' . $url . '">' . $atts['text'] . '</a>';
}
add_shortcode('permalink', 'anniversary_link');
And how I use this short code inside a post (I think that I incorrectly use the shortcode):
Edit Edit This is how I call the dynamic anniversary post:
<?php echo get_posts(array( 'category_name' => 'Anniversary' ))[0]->post_content ;?>
Reading through the code you've posted I see three issues.
The first parameter of a shortcode callback should be an array of attributes, not a single string. Naming your parameter $text
has no bearing on the value and won't pull the text attribute of your shortcode.
Change the name of your parameter from $text
to $atts
and set a default value for the text attribute. Setting a default value is a good practice with shortcodes and can be done using the shortcode_atts()
function.
The second issue is your use of the_permalink()
. the_permalink()
doesn't return a permalink but outputs it directly instead. As such you can't assign it to a variable.
function anniversary_link( $atts ) {
// Set defaults where needed
$atts = shortcode_atts( array(
'text' => '',
), $atts, 'permalink' );
// Replace the_permalink().
// Given the level of simplicity it doesn't need it's own variable.
$url = get_permalink();
// Put together a new return statement.
// Various ways this could be formatted. I went with something clear and easy to understand.
return '<a href="' . $url . '">' . $atts['text'] . '</a>';
}
In your code you're using the shortcode inside the href
attribute of a link. The shortcode returns a full link, not a URL, and therefore shouldn't be inside another a
tag.
Example:
[permalink text="My Link Text"]
// Outputs <a href="http://myurl.com/permalink-here">My Link Text</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.