我的目标是获取一个现有WP主题的页面并自定义一个全宽页面,以使每1秒钟重新加载一个MySQL SELECT查询并显示结果。
从this片段开始,我做了以下编辑/新文件:
- template-fullwidth.php
- functions.php
- my.js(新文件)
- GetPostDate.php(新文件)
我做了什么
我从主题的template-fullwidth.php
开始,并在帖子的DIV
之间添加了以下代码。我想显示结果的地方是<div id="MaxPostDate">
标记之间。
</div><!-- .post -->
<!-- START CUSTOM PAGE CODE -->
<?php
if ( is_user_logged_in() ) {
// --- START IF USER LOGGED IN --- //
// Get the current user name and id
?>
<div id="MaxPostDate"></div>
<?php
// --- END IF USER LOGGED IN --- //
} else {
// --- START IF USER NOT LOGGED IN --- //
echo "<p>You have to log-in to see this content</p>";
// --- END IF USER NOT LOGGED IN --- //
}
?>
<div class="result"></div>
<!-- END CUSTOM PAGE CODE -->
<?php comments_template( '',true ); ?>
</div><!-- .posts -->
然后我编辑了主题的functions.php
文件,最后添加了该文件:
function add_myjavascript(){
wp_enqueue_script( 'ajax-implementation.js',get_bloginfo('template_directory') . "/js/my.js",array( 'jquery' ) );
}
add_action( 'init','add_myjavascript' );
function MyAjaxFunction(){
//get the data from ajax() call
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){echo "<h1>" . $Content->MaxDate . "</h1>";}
// Return the String
die($results);
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction','MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction','MyAjaxFunction' );
?>
然后,将这个my.js
放在主题的js
文件夹中:
jQuery(document).ready(function refresh_div() {
jQuery.ajax({
url:'/MySite/wp-content/themes/hemingway/GetPostDate.php',type:'POST',success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000););
最后创建另一个文件GetPostDate.php
<?php
$TableContent = $wpdb->get_results("
SELECT MAX(`post_date`) AS MaxDate FROM wp_posts"
);
foreach($TableContent as $Content){echo "<h1>" . $Content->MaxDate . "</h1>";
?>
问题
- 在DIV id =“ MaxPostDate”中什么都没有出现
- 我在同一查询中写过两次(
SELECT MAX(
post_date) AS MaxDate FROM wp_posts
),而我只被写过一次!