Ad

Display Pretty Links In Shortcode

- 1 answer

I am making a shortcode to display all the pretty links on front page. So Far I have succeeded in displaying all except the links missing

// Display Pretty-Links
function custom_budurl() {

    $links = new WP_Query(array(
        'post_type' => 'pretty-link',
        'orderby' => 'meta_value',
        'order' => 'ASC',
    ));

    if ($links -> have_posts()) :
        // Start The Loop
        while ($links -> have_posts()) : $links -> the_post();
            echo '<li><a target="_blank" rel="nofollow noreferrer" href="' . . '">' . get_the_title() . '</a></li>';
        endwhile;
    endif;

}
add_shortcode( 'budurl', 'custom_budurl' );

But I'm unable to figure out what to write in the target="_blank" rel="nofollow noreferrer" href="" option to print the link created as shown in the image. enter image description here

It would be great if anyone can help. Thanks

Ad

Answer

Pretty links uses a custom table. Below I use a custom select to get the slug for the pretty link then build the url using home_url(). Tested on the WP 5.3.2 with Pretty Links 3.1.0 running PHP 7.4.

// Display Pretty-Links
function custom_budurl()
{

  $links = new WP_Query(array(
    'post_type' => 'pretty-link',
    'orderby' => 'meta_value',
    'order' => 'ASC',
  ));

  if ($links->have_posts()) :
    // Start The Loop
    while ($links->have_posts()) : $links->the_post();
      global $wpdb;

      // get current post id
      $pid = get_the_ID();

      // custom select to get pretty link slug from custom table
      $sql = $wpdb->prepare("SELECT slug from {$wpdb->prefix}prli_links where link_cpt_id = %d", $pid);

      // run the query
      $results = $wpdb->get_row($sql);

      // build url
      $url = home_url($results->slug);

      // print html to browser
      echo '<li><a target="_blank" rel="nofollow noreferrer" href="' . $url . '">' . get_the_title() . '</a></li>';

    endwhile;

    wp_reset_postdata();

  endif;
}
add_shortcode('budurl', 'custom_budurl');
Ad
source: stackoverflow.com
Ad