Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
Closed 4 years ago.
Improve this questionHow should I add php code within a return statement. My following code does not work:
function read_more() {
return '<a href="<?php the_permalink(); ?>">Read More</a>';
}
Closed. This question is off-topic. It is not currently accepting answers.
Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
Closed 4 years ago.
Improve this questionHow should I add php code within a return statement. My following code does not work:
function read_more() {
return '<a href="<?php the_permalink(); ?>">Read More</a>';
}
Share
Improve this question
asked May 14, 2020 at 19:19
GustoGusto
871 gold badge2 silver badges6 bronze badges
2
- Where is this being called, and why? – vancoder Commented May 14, 2020 at 21:49
- Where is this being called: functions.php. Why: so I can have a custom "read more" button in post excerpts. – Gusto Commented May 14, 2020 at 22:31
1 Answer
Reset to default 1You can just call PHP functions directly. In this case however we possibly don't want to call the_permalink()
since it echoes out the link:
function the_permalink( $post = 0 ) {
/* ... */
echo esc_url( apply_filters( 'the_permalink', get_permalink( $post ), $post ) );
}
whereas we want to return the link in a string. So your options are:
do use the_permalink(), but capture the output buffer to get the echoed link URL:
function read_more() { ob_start(); the_permalink(); $permalink = ob_get_clean(); return '<a href="' . $permalink . '">Read More</a>'; }
or replicate the filter and escaping from the_permalink in your own code, saving it in a variable to use:
function read_more() { $permalink = esc_url( apply_filters( 'the_permalink', get_permalink(), 0 ) ); return '<a href="' . $permalink . '">Read More</a>'; }
or just use get_permalink() instead, unfiltered, which is what a lot of WordPress's own code does (sometimes without escaping too):
function read_more() { return '<a href="' . esc_url( get_permalink() ) . '">Read More</a>'; }
(As an aside, if you were doing this in a plugin or theme you were distributing you'd also want to make 'Read More' translatable, e.g. '<a href="' . $permalink . '">' . __( 'Read More' ) . '</a>';
)