在调用php函数通过ajax显示我的帖子之后似乎无法访问$ wpdb

时间:2011-10-07 01:01:25

标签: php javascript ajax wpdb

嗨我希望有一个列表,按年显示帖子档案 当用户点击年份时,将显示帖子

我使用ajax来调用functions.php,并且在其中有一个函数 会抓住帖子,但我似乎无法访问$ wpdb?

非常感谢!

HTML:

<ul id="years">
<?php
$months = $wpdb->get_results("SELECT DISTINCT YEAR( post_date ) AS year,post_title as     title, ID as post_id, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status =     'publish' and post_date <= now( ) and post_type = 'post' GROUP BY year ORDER BY post_date   DESC");
foreach($months as $month) : ?>
<li>
<a href="" onClick="year_to_post_titles(<?php echo $month->year; ?>)">
<?php if(in_category("photography",$month->post_id)){
echo $month->year;
} ?>
</a>
</li>
<?php endforeach; ?>
</ul>

AJAX:

<script>

function year_to_post_titles(year){
var find_titles="find_titles";
//request ajax
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//state change
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&& xmlhttp.status==200){
document.getElementById("work_items").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php bloginfo(template_directory) ?>/functions.php?func=find_titles&y="+year,true);
xmlhttp.send()
}

</script>

的functions.php:

 <?php
$which_func=$_GET["func"];
if(function_exists($which_func)){
    find_titles();
};

function find_titles(){
global $wpdb;
$which_year=$_GET["y"];
$titles = $wpdb->get_results("SELECT DISTINCT YEAR( post_date ) AS year,post_title as title, ID as post_id, COUNT( id ) as post_count FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY year ORDER BY post_date DESC");
foreach($titles as $var_title){
echo "<li><a href=''>";
if(in_category("photography",$var_title->post_id)){
    echo $var_title->title;
    } 
echo "</a></li>";
}
}
?>

2 个答案:

答案 0 :(得分:2)

此外,你不应该这样做:

<?php
$which_func=$_GET["func"];
if(function_exists($which_func)){
    $which_func();
};
?>

如果你这样做,用户将可以调用任何现有的函数(例如phpinfo()例如,但它可能是最糟糕的一点点的想象力)。这是一个巨大的安全漏洞。

答案 1 :(得分:0)

当您通过AJAX调用functions.php时,该文件没有名为$wpdb的全局变量。这也就不足为奇了,因为通常functions.php并不关心这一点。相反,您应该注册an AJAX PHP callback function within wordpress。然后$wpdb可用。