【问题标题】:can't seem to access to $wpdb after calling a php function to display my posts via ajax在调用 php 函数以通过 ajax 显示我的帖子后,似乎无法访问 $wpdb
【发布时间】:2023-04-09 03:47:01
【问题描述】:

您好,我想要一个列表,按年份显示帖子存档 当用户点击年份时,将显示帖子

我正在使用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>";
}
}
?>

【问题讨论】:

    标签: php javascript ajax wordpress


    【解决方案1】:

    此外,您不应该这样做:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 顺便说一句,为什么 $wpdb 在函数中不可用。php 本身也不是 wordpress 的一部分?
      • 如果您直接调用它(通过 AJAX)则不会。
      • 感谢您推荐的任何其他链接或阅读您建议的内容?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多