duanjia2772 2011-10-07 01:01
浏览 35
已采纳

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

hi I wanted to have a list that displays archives of posts group by year when users click on the years, the posts will be displayed

I am using ajax to call a functions.php, and within there's a function will grab the posts, but I can't seem to access the $wpdb ?

Thanks a lot!

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条回答 默认 最新

  • dswsl2016 2011-10-07 01:05
    关注

    When you call functions.php via AJAX, the file does not have a global variable called $wpdb. That's no wonder, because normally functions.php does not care about this. Instead you should register an AJAX PHP callback function within wordpress. Then $wpdb is available.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面