dongyuan1870 2018-06-20 07:45
浏览 66

从字符串php wordpress获取ID

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条回答 默认 最新

  • dsqtl335227 2018-06-20 08:09
    关注

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

报告相同问题?

悬赏问题

  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离