可以'在调用php函数以通过ajax显示我的帖子后,我似乎访问了$wpdb
can't seem to access to $wpdb after calling a php function to display my posts via ajax
hi我想有一个按年份显示帖子档案的列表当用户点击年份时,帖子将显示
我正在使用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.hp:
<?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>";
}
}
?>
此外,您不应该这样做:
<?php
$which_func=$_GET["func"];
if(function_exists($which_func)){
$which_func();
};
?>
如果你这样做,用户将能够调用任何现有的函数(例如phpinfo((,但如果有一点想象力,这可能是最糟糕的(。这是一个巨大的安全漏洞。
通过AJAX调用functions.php
时,文件没有名为$wpdb
的全局变量。这也就不足为奇了,因为通常functions.php
并不关心这个问题。相反,您应该在wordpress中注册一个AJAX PHP回调函数。则$wpdb
可用。
相关文章:
- 访问布局信息是否也会导致浏览器重排
- Javascript,访问一个主要对象模块模式中的每个对象
- 如何访问声音管理器2创建的声音对象
- 在Twitter上用ie9中的空白src访问iframe的contentWindow
- JavaScript Pub/Sub属性访问问题
- 从JavaScript访问struts操作中的属性
- 是否可以从父类访问子类的属性
- 如何访问fastOpt.js
- 访问JSON对象内部的数组元素
- 从模块内部访问Express装载路径
- 难以访问的JS环境中的语法错误
- 如何从对象的原型方法访问JavaScript对象属性
- 访问json数组中的对象
- 通过javascript/html访问twitter共享iframe
- Dojo:访问dijit.form.Select中单击的项目
- 为什么在这个网站上不能通过JS访问元素
- 从ng模板访问作用域
- 如何访问UIWebView'的子窗口上下文
- 在新的Wordpress PHP文件中访问$wpdb,需要wp-load. PHP;不工作
- 可以'在调用php函数以通过ajax显示我的帖子后,我似乎访问了$wpdb