如何在 Wordpress 中呈现来自自定义 table 的信息?

How to render information from a custom table in Wordpress?

早上好,

我目前想在我的页面上开发一个部分,我可以在其中显示和编辑我在 Wordpress 数据库中以个性化方式创建的 table 的信息。

例如,我在我网站的这个页面上定义了加载评论 table 中所有信息的地方。

我的问题是 classes 和 hooks 适合用来呈现和更新信息或我使用的部分 wordpress 文档应该复习以获得更好的想法。

我已经使用这个 guide and also check this link 在与我的 Wordpress 关联的 bd 中创建了 table 并且知道我可以使用 WPDB class 但我仍然不明白我应该使用的 wordpress 前端侧面的钩子。

备注:我不想使用任何插件

谢谢。

您可能想继续阅读 $wpdb class。这是一个非常强大的 class,可让您获取、更新、删除数据,甚至创建和更新新的 table。它为您处理 很多 繁琐的 sql 连接和卫生废话。

最适合您入手的可能是 $wpdb::get_results() 方法。如果您需要更具体的内容,您可以阅读其他 get_ 函数,但 get_results() 通常是 <jgwentworth>"It's MY data and I want it NOW!"</jgwentworth>.

的良好起点

Note: The argument based methods like $wpdb->update() sanitize your data for you (you should still make sure it's the right kind of data, but they prevent SQL injection attacks and other nasties. Any of the methods that take an SQL Query should be prepared with $wpdb::prepare()!

这是一个简单的小示例函数:

function get_thing_from_my_custom_table( $thing_id, $something_else ){
    global $wpdb; 

    $sql = "
        SELECT thing_id, thing_value
        FROM   {$wpdb->prefix}my_custom_table
        WHERE  company_id = %d
        AND    something_else = %s
        LIMIT  0, 1
    ";

    $prepared = $wpdb->prepare( $sql, array($thing_id, $something_else) );

    return $wpdb->get_results( $prepared );
}

在那个例子中,因为你只得到一个 object,你可以说 array_shift() return 值,如果你愿意的话。

现在,关于输出那个数据,how/where/hooks,等等。简短的回答:这取决于!.

我来解释一下:

如果您要在 header 中输出元标记,您可能需要使用 wp_head 挂钩 :

add_action( 'wp_head', function(){
    echo get_thing_from_my_custom_table( 123, 'something' );
});

如果您要在特定页面上的 the_content 末尾添加内容,您可以使用 the_content filter and the is_page() 函数 :

add_filter( 'the_content', function( $content ){
    if( is_page( 'my-special-page') )
        $content .= sprintf( '<div class="from-database">%s</div>', get_thing_from_my_custom_table( 123, 'something' ) );

    return $content;
});

如果您需要在主题的任意位置输出数据库内容,您可以在任何需要的地方调用 echo get_thing_from_my_custom_table( 123, 'something' );(有时称为模板标签)

如果您需要在更多 select 位置输出它,或允许用户添加自己的参数,或希望它出现在某些内容位置,您可能需要阅读 Shortcode API 并将其转换为简码:

add_shortcode( 'get-my-custom-thing', 'get_thing_from_my_custom_table_shortcode_func' );
function get_thing_from_my_custom_table_shortcode_func( $atts ){
    extract( shortcode_atts( array(
        'thing_id' => '',
        'something' => null
    ), $atts, 'get-my-custom-thing' ) );

    if( !is_numeric($thing_id) )
        return false; // We need a number!

    if( $something == null )
        return false; // We need a thing!

    return get_thing_from_my_custom_table( absint($thing_id), sanitize_text_field($something) );
}

这样做可以让您将 [get-my-custom-thing thing_id="123" something="some value"] 放在解析短代码的任何地方(页面内容、短代码块、小部件等)并显示它。

这些是基础知识,但应该为您提供一些基础,让您可以在 WordPress 网站的任何地方(或几乎)显示您的自定义数据库中的任何内容 table。