WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Quick link to a certain post (6 posts)

  1. Machi
    Member
    Posted 4 years ago #

    Hi there,
    I have a simple question...

    Is there a plugin which would allow me to create a quick link to a certain post?

    For example to link a post called "Example" I would write a shortcode [post:Example] and it will automatically create a link to it.

    Thanks a lot for your replies!

  2. vtxyzzy
    Member
    Posted 4 years ago #

    Here is a bit of code to add to your functions.php which I think will do what you want. There are probably better ways to code this, but I believe this will work.

    <?php // Shortcode is like [mm-link-to-post title='post title']
    function mm_link_to_post_func($atts) {
    	extract(shortcode_atts(array(
             'title' => '',
                                    ), $atts));
    	$output = '';
       if ($title) {
          global $wp_query, $wpdb;
          $output = '';
          $sql = "SELECT * from $wpdb->posts WHERE post_status='publish' AND post_title='$title'";
          $myrow = $wpdb->get_row($sql);
          if ($myrow) {
             $link = $myrow->guid;
             $output = "<a href='$link' title='Link to $title'>$title</a>";
          }
       }
       return $output;
    }
    add_shortcode('mm-link-to-post', 'mm_link_to_post_func');
    ?>
  3. Machi
    Member
    Posted 4 years ago #

    Hi,
    thanks a lot for this great code, works like a charm! I only have one small question, this solutions ignores permalinks and uses static links such as http://www.domain.com/?p=20, is there any way how to bypass this?

    Thanks a lot!

  4. vtxyzzy
    Member
    Posted 4 years ago #

    Sorry, I could never get the_permalink() to work. Maybe someone else can help with that.

  5. pokinwilly
    Member
    Posted 4 years ago #

    Hello,

    Not a shortcode, but a greaaat plugin you should have a look to:
    http://wordpress.org/extend/plugins/link-to-post/

    allows to include a link to a post (or a page) in 2 clicks only.

  6. vtxyzzy
    Member
    Posted 4 years ago #

    OK, I got it. If this works for you, please mark this topic 'Resolved'.

    <?php // [mm-link-to-post title='post title']
    function mm_link_to_post_func($atts) {
    	extract(shortcode_atts(array(
             'title' => '',
                                    ), $atts));
    	$output = '';
       if ($title) {
          global $wpdb;
          $output = '';
          $myid = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_title='$title' AND post_status='publish'");
          if ($myid) {
             $link = get_permalink(intval($myid[0]));
             $output .= "<a href='$link' title='Link to $title'>$title</a>";
          }
       }
       return $output;
    }
     add_shortcode('mm-link-to-post', 'mm_link_to_post_func');
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic