0

I'm trying to get values from columns name and id. Could Anyone tell me how can I get these two values in loop, and adjust this sql for Wordpress?

function get_calendar_ids() {

    global $wpdb;
$user_id = get_current_user_id();
$sql = $wpdb->prepare( "
Select
  wp_calendars.user_id,
  wp_calendars.name,
  wp_calendars.id
From
  wp_calendars
Where
  wp_calendars.user_id = '$user_id'
");
$calendars = $wpdb->get_results( $sql );
     if ($calendars ) {
        return $calendars;
        echo $sql;
    }
}

1 Answer 1

1

You are not too far away from your goal. The get_calendar_ids must return only $calendars.

In your function $wpdb->get_results( $sql ) will return an object with the datas your asked.

function get_calendar_ids() {

    global $wpdb;
$user_id = get_current_user_id();
$sql = $wpdb->prepare( "
    Select
      wp_calendars.user_id,
      wp_calendars.name,
      wp_calendars.id
    From
      wp_calendars
    Where
      wp_calendars.user_id = '$user_id'
");
    $calendars = $wpdb->get_results( $sql );
     if ($calendars ) {
        return $calendars;          
     }
}

Your function now return an object with only user_id, name, and id, the result must in a loop to echo the result, you can grab them like this $calendar->name in a foreach loop.

an example in a shortcode,

add_shortcode('calendars', 'get_calendars');

function get_calendar($atts, $content = ""){

    // you can add $atts extract_args if need

    $calendars = get_calendar_ids();

    if($calendars){
        foreach($calendars as $calendar){
            $user_data = get_userdata(get_current_user_id());
            echo '<a href="'.get_permalink($calendar->id).'">'.$calendar->name . '</a> by '.$user_data->user_nicename.'</br>';

        }
    }
}

Hope it helps

3
  • Thank you! It works, but $wpdb->prepare needs parameter, so I made function get_calendar_ids($user_id) and got it in shortcode. Second question - most of wpdb calls are not using prefix wp_ how can I change it here?
    – Rafal
    Commented Nov 4, 2016 at 9:53
  • You can get the prefix with : $wpdb->prefix.calendars
    – Benoti
    Commented Nov 4, 2016 at 9:58
  • I mean, $table_name = $wpdb->prefix . 'calendars'; before $sql and get $table_name for the FROM.
    – Benoti
    Commented Nov 4, 2016 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.