我正在尝试创建一个短代码,返回匹配专业的医生列表。
到目前为止,我可以获得基本短代码以返回整个表的内容,但我无法根据属性字符串进行查询。
这是我所拥有的:
// Add Shortcode
function list_docs( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'specialty' => '',
),
$atts,
'doctors'
);
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare("SELECT * FROM doctors WHERE specialty = '%s'", $specialty);
$specresults = $wpdb->get_results($specget);
foreach($specresults as $details) {
echo $details;
}
}
add_shortcode( 'doctors', 'list_docs' );
如果我直接查询数据库:
SELECT * FROM `doctors` WHERE `specialty` = 'cardiology'
我得到了预期的结果。
我试图[doctors specialty="cardiology"]
在 WordPress 页面上用(我试过双引号和单引号)来调用它。
现在,我不知道我不知道什么。我不确定我是否输入错误、有错字或遗漏了一行代码。任何帮助都会很棒。
假设您的表名确实是doctors
(& 不是wp_doctors
或类似的东西),则问题可能根本不在于查询
$specresults
将包含一个对象数组。假设您的doctors
表有name
列,那么下面的更改可能对您有用。
function list_docs( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'specialty' => '',
),
$atts,
'doctors'
);
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare( 'SELECT * FROM doctors WHERE specialty = %s', $specialty );
$specresults = $wpdb->get_results( $specget );
if ( $specresults ) {
$doctor_names = array_map(
function( $doctor_object ) {
return $doctor_object->name;
},
$specresults
);
return implode( ', ', $doctor_names );
}
return '';
}
add_shortcode( 'doctors', 'list_docs' );
要记住的几件事:-
短代码应始终返回而不是直接回显。
尽量只从数据库中查询需要的数据,而不是做*
get_col
方法 on$wpdb
而不是get_results
。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句