首页 > 解决方案 > 从字符串 php wordpress 获取 ID

问题描述

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

http://xxxxxxxx/xxxxxxx/wp-content/uploads/2018/02/large-IMG_5367.j​​pg|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 from string 的 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, ',');
}

但它不起作用,有人已经做过类似的事情了吗?

提前致谢

标签: phphtmlwordpress

解决方案


试试下面的代码,如果在数据库中找到 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);
}

推荐阅读