WordPress短代码返回完整XML而非图书价格的修复咨询
解决你的WordPress短代码图书价格返回问题
咱们先拆解下问题出在哪:
- 你代码里的
print_r($sxml);会直接把整个SimpleXMLElement对象输出到页面上,这就是你看到完整对象内容的核心原因——短代码执行时先print了对象,再return价格,导致两者混在一起显示。 - 另外,你返回的
$sxml->price路径完全不对,从你贴的XML结构来看,价格实际藏在items->item->pricing->price->selling节点里,对应的货币属性则在price节点的currency属性上。
下面是修复后的完整代码:
function get_book_price() { $isbn13 = 9783899735215; $url = 'https://api.bookdepository.com/search/lookup?isbn13='.$isbn13.'&clientId={redact}&authenticationKey={redact}&IP={redact}&currencies=GBP'; $sxml = simplexml_load_file($url); // 先检查API是否返回了有效数据 if (isset($sxml->items->item->pricing->price)) { // 强制转换为字符串,避免返回SimpleXMLElement对象 $currency = (string)$sxml->items->item->pricing->price['currency']; $selling_price = (string)$sxml->items->item->pricing->price->selling; return "{$selling_price} {$currency}"; } else { return "价格获取失败"; } } add_shortcode('book_price_gbp', 'get_book_price');
关键修复细节:
- 移除
print_r:短代码的核心是通过return返回内容,直接print会破坏WordPress的输出流程,导致内容提前渲染。 - 修正节点路径:严格按照API返回的XML层级定位到价格和货币属性,并且用
(string)强制转换为字符串(SimpleXMLElement节点直接返回的是对象,转成字符串才能正常显示)。 - 增加异常处理:如果API返回异常(比如ISBN不存在、请求失败),会返回友好提示,避免页面出现空白或错误。
现在你用[book_price_gbp]短代码就能得到类似50.27 GBP的结果了。如果之后要扩展成[currency_isbn13]动态短代码,只需要给函数添加属性参数,比如:
function get_book_price($atts) { // 提取短代码参数,设置默认值 $atts = shortcode_atts( array( 'isbn13' => '9783899735215', 'currency' => 'GBP' ), $atts ); // 后续调整URL的currencies参数和ISBN即可 } add_shortcode('currency_isbn13', 'get_book_price');
内容的提问来源于stack exchange,提问作者Italicus
相关产品推荐
相关产品推荐

