您可能想阅读$wpdb 课程。它是一个非常强大的类,可让您获取、更新、删除数据,甚至创建和更新新表。它为您处理很多繁琐的 sql 连接和卫生废话。
最相关的事情很可能是$wpdb::get_results() 方法。如果您需要更具体的内容,可以阅读其他 get_ 函数,但 get_results() 通常是 <jgwentworth>"It's MY data and I want it NOW!"</jgwentworth> 的一个很好的起点。
注意:$wpdb->update() 等基于参数的方法会为您清理数据(您应该仍然确保它是正确的数据,但它们可以防止 SQL 注入攻击和其他讨厌的东西。任何接受 SQL 查询的方法都应该准备$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 );
}
在那个例子中,因为你只得到一个对象,你可以说如果你想array_shift()返回值。
现在,关于输出该数据、方式/位置/挂钩等。简短回答:视情况而定!。
我会解释:
如果您在标题中输出元标记,您可能需要使用wp_head hook:
add_action( 'wp_head', function(){
echo get_thing_from_my_custom_table( 123, 'something' );
});
如果您要在特定页面上的the_content 末尾添加内容,您可以使用the_content 过滤器 和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' );(这有时称为模板标签)
如果您需要在更多选择位置输出它,或者允许用户添加自己的参数,或者希望它出现在某些内容位置,您可能需要阅读 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 网站的任何位置(或几乎)显示自定义数据库表中的任何内容提供一定的基础。