Shortcode attributes that query the database

时间:2019-04-17 01:24:47

标签: php wordpress

I am trying to create a shortcode that returns a list of doctors matching a specialty.

So far, I can get the base shortcode to return the contents of the entire table, but I can't get it to query based on an attribute string.

Here's what I have:

// 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' );

If I query the database directly with:

SELECT * FROM `doctors` WHERE `specialty` = 'cardiology'

I get the expected result.

I'm trying to call it with [doctors specialty="cardiology"] (I've tried double and single quotes) on the WordPress page.

Right now, I don't know what I don't know. I'm not sure if I've entered something wrong, have a typo, or am missing a line of code. Any assistance would be terrific.

2 个答案:

答案 0 :(得分:1)

假设您的表名确实为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' );

要记住的事情:-

  1. 短代码应始终返回且不直接回显。

  2. 仅查询数据库中所需的数据,而不用*

  3. 如果只需要一列,则最好在get_col上使用$wpdb方法,而不要使用get_results

答案 1 :(得分:0)

Please try with this -

function list_docs( $atts ) {

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