最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - Is it possible to create a shortcode to link to a specific postpage where the tag is just an attribute?

programmeradmin4浏览0评论

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' );
发布评论

评论列表(0)

  1. 暂无评论