首页 文章

从字符串php wordpress获取ID

提问于
浏览
0

我有一个图像的URL字符串除以“|”我想要一个php函数,读取字符串将图像分开并用“,”分隔它们以使用wordpress gallery组件

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

我试图从字符串创建一个名为get id的php短代码

/* ---------------------------------------------------------------------------
 * 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, ',');
}

但它没有用,有没有人做过类似的事情?

提前致谢

1 回答

  • 0

    尝试下面的cod,如果在数据库中找到URL,它将返回 ID 并添加 $return_value 变量 .

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

相关问题