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
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
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);
}