I'm trying to think of the best way to phrase this. I want to create a single shortcode to link to any post, page, or custom post type but I don't want to have to use the post ID. Ideally I'd like to use the post name or slug, but I also want the shortcode to be simple where the tag itself is just the attribute. The shortcode function would contain the anchor link html.
So like instead of doing something like [link-to-post id=1] or [link-to-post post="Hello World"], I'd like the shortcode to be [$post_title] where the content within the tag is just the post title and it links to that specific post permalink. So [Hello World] would link to the post with that title. Same for pages, [About] will link to the About Page.
I feel like this should be possible but perhaps not.
My starting point is the following shortcode function that uses the post ID.
function post_link_sc( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'id' => '',
),
$atts,
'link-to-post'
);
// Return only if has ID attribute
if ( isset( $atts['id'] ) ) {
return '<a href="' . get_permalink( $atts['id'] ) . '">' . get_the_title( $atts['id'] ) . '</a>';
}
}
add_shortcode( 'link-to-post', 'post_link_sc' );