0
votes

I have a URL string of images divided by "|" and I would like a php function that reading the string separate the images and divide them with "," to use a wordpress gallery component

http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5367.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5376.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_6324.jpg

I tried to create a php shortcode called get id from string

   /* ---------------------------------------------------------------------------
 * Shortcode | get_id_from_string
* --------------------------------------------------------------------------- */


add_shortcode('get_id_from_string', 'function_get_id_from_string');
function function_get_id_from_string($atts) {
  global $wpdb;
  $return_value = '';

  $url_array = explode('|', $atts['urls']);

  foreach ($url_array as &$url) {
    $return_value .= $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $url))[0] . ',';

  }

  return rtrim($return_value, ',');
}

But it does not work, has anyone already done something like that?

Thanks in advance

1
Have you echo your sql query ? - dipmala
I apologize that it was to check if it works - Luca Belletti
What is the output of your code, or is the code itself is not able to run properly. You will need to step through the debugger to identify the variables and query being generated. Will be better if you set the sql query in a separate variable to ease debugging rather than constructing inline the function call - NitinSingh
You need some debugging. f.e. guid='%s' is wrong. it should be guid=%s - without any quote. - Elvin Haci
It just does not work, I tried to debug but it does not return anything - Luca Belletti

1 Answers

0
votes

Try below cod, If URL found in database it will return ID and add in $return_value variable.

add_shortcode('get_id_from_string', 'function_get_id_from_string');
function function_get_id_from_string($atts)
{
    global $wpdb;
    //$imagestr = "http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5367.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5376.jpg|http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_6324.jpg";
    $imagestr = $atts['urls'];
    $url_array = explode("|", $imagestr);
    $return_value = [];
    foreach ($url_array as $url) {
        $query = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s'", $url);
        $result = $wpdb->get_col($wpdb->prepare($query, $url), ARRAY_A);
        if (!empty($result))
            $return_value[] = $result[0];
    }
    $images_ids = implode(",", $return_value);
    return ($images_ids);
}