这是一个相当模糊和广泛的问题,但我会试一试。您可以将以下代码添加到功能插件中,或者如果您正在运行主题,可以将其放置在主题的functions.php
文件(显然,您必须更改SQL、属性等-这只是概念证明)
add_shortcode( \'wpse_weather_data\', \'wpse_weather_data_shortcode_cb\' );
function wpse_weather_data_shortcode_cb( $atts ) {
$atts = shortcode_atts( array(
\'fallbackValue\' => \'\',
\'sensor\' => 0
), $atts );
extract( $atts );
// Make the connection to a separate database using PHP.
// You might want to store these credentials as constants in wp-config.php
// to keep all the db credentials in one place.
$db = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if ( !$db ) {
return $fallbackValue;
}
// Make the query
$query = "SELECT * FROM table_name WHERE sensor = {$sensor}";
$result = mysqli_query($db, $query);
if ( !$result ) {
return $fallbackValue;
}
$row = mysqli_fetch_array($result);
// Put the data on the page... FYI you have to return the data from a shortcode, not echo it.
}
构建选项页面、将过去的值存储在数据库中等超出了本论坛的范围,但这将为您提供一种入门的方法。您可以通过向快捷码添加不同的属性来自定义它(根据#3)。例如,您可以在此处添加其他传感器并指定回退值,方法是将短代码放置在内容中的某个位置并这样调用:
[wpse_weather_data sensor="0" fallbackValue="Could not fetch sensor data"]
希望这能引导你朝着正确的方向前进。