【问题标题】:Get ID from string php wordpress从字符串 php wordpress 中获取 ID
【发布时间】:2018-06-20 07:45:36
【问题描述】:

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

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

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

提前致谢

【问题讨论】:

  • 你是否回显了你的 sql 查询?
  • 我很抱歉这是为了检查它是否有效
  • 你的代码的输出是什么,或者是代码本身不能正常运行。您将需要逐步通过调试器来识别正在生成的变量和查询。如果将 sql 查询设置在单独的变量中以简化调试而不是构建内联函数调用会更好
  • 你需要一些调试。 f.e. guid='%s' 错误。它应该是 guid=%s - 没有任何引号。
  • 它只是不起作用,我试图调试但它没有返回任何东西

标签: php html wordpress


【解决方案1】:

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

【讨论】:

  • 它似乎可以工作,但输出只给我留下一个图像“xxxxxxxxxxxx/xxxxxxxxxxx/uploads/2018/02/large-A.jpg”难道是他插入短代码错了吗? [gallery link="file" columns="5" ids="[get_id_from_string urls='{!{types field='galleria-immagini' separator=',' output='raw'}!}
  • 如果在数据库中找到,它将返回逗号分隔的图像列表。可能存在短代码的使用年限问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2015-08-21
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2012-02-10
相关资源
最近更新 更多