sajjad aslam
sajjad aslam

Reputation: 47

Display Pretty links In Shortcode

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 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 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

Upvotes: 0

Views: 379

Answers (1)

mikerojas
mikerojas

Reputation: 2338

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 href="' . $url . '">' . get_the_title() . '</a></li>';

    endwhile;

    wp_reset_postdata();

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

Upvotes: 1

Related Questions