php - 从字符串 php wordpress 获取 ID
问题描述
我有一个图像的 URL 字符串,除以“|” 我想要一个 php 函数来读取字符串分隔图像并用“,”划分它们以使用 wordpress 库组件
我试图创建一个名为 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, ',');
}
但它不起作用,有人已经做过类似的事情了吗?
提前致谢
解决方案
试试下面的代码,如果在数据库中找到 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);
}
推荐阅读
- python - Pandas - 基于某些列的 shift()
- javascript - jquery-ui 按钮看起来已禁用
- css - 在 Firefox 中以轻量模式查看纯文本文件
- android - 如何在android中的同一应用程序的最近任务中显示两个不同的活动?
- deep-learning - 用于 RNN 的最有效张量格式(填充与打包、时间主要与批处理主要)
- rpa - UiPath 在测试任何活动时反序列化当前 JSON 对象错误
- javascript - 如何在计算重复时删除数组中的重复值?
- java - 一个系统上的 RestTemplate/FeignClient SSL 异常
- reactjs - 如何向 React FlatPickr 添加名称和 ID 属性?
- c - 表达式中的严格别名