【发布时间】:2015-11-03 22:59:10
【问题描述】:
尝试使用 jQuery 显示内容给我带来了一些麻烦。我创建了三个按钮,当点击它们时,它们会从我服务器上的 php 文件中加载数据。一切正常,除非我尝试发送加载 Wordpress 帖子的请求。出现以下致命错误:调用未定义函数 get_posts()。我从 https://perishablepress.com/slide-fade-content/ 那里学到了如何做到这一点。
对于脚本,我有这个:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://example.com/slide-fade-content/jquery.colorfade.min.js"></script>
<script type="text/javascript">
// slide & fade content @ http://m0n.co/r
$(document).ready(function() {
$('.more').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href');
if ($('#ajax').is(':visible')) {
$('#ajax').css({ display:'block' }).animate({ height:'0' }).empty();
}
$('#ajax').css({ display:'block' }).animate({ height:'200px' },function() {
$('#ajax').html('<img id="loader" src="loader.gif">');
$('#loader').css({ border:'none', position:'relative', top:'24px', left:'48px', boxShadow:'none' });
$('#ajax').load('slide-fade-content.php ' + href, function() {
$('#ajax').hide().fadeIn('slow').colorFade({ 'fadeColor': 'rgb(253,253,175)' });
});
});
});
});
</script>
这是我的三个按钮:
<ul>
<li><a class="more" href="#first-item">First Item</a></li>
<li><a class="more" href="#second-item">Second Item</a></li>
<li><a class="more" href="#third-item">Third Item</a></li>
</ul>
这是内容出现的地方
<div id="ajax"></div>
这就是内容
<div id="load">
<div id="first-item">
<?php
$args = array(
'posts_per_page' => 5,
'offset'=> 0,
'category' => '2,3,4',
'orderby' => 'meta_value_num',
'meta_key' => 'views',
'order' => 'DESC',
'suppress_filters' => true,
'date_query' => array(
'after' => date("jS F, Y", strtotime('-24 hours'))
)
);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div>
<li>
<ul><?php $categories = get_the_category(); $separator = ' '; $output = '';
if($categories){
foreach($categories as $category) {
$output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
}
echo trim($output, $separator) ;
}
?>
</ul>
<a href="<?php the_permalink(); ?>"><?php echo get_the_post_thumbnail( $post_id, array(300, 160), $attr ); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?>
</li>
</div>
<?php endforeach;
wp_reset_postdata();?>
</div>
<div id="second-item">
Test2
</div>
<div id="third-item">
Test3
</div>
</div>
我想我必须定义一个函数,但经过数小时的反复试验后,我迷失了方向。我不知道该怎么做或在哪里定义它。
【问题讨论】:
-
这是slide-fade-content.php的全部内容吗?您的脚本是在 WordPress 架构中还是单独存在?
get_posts()是 WordPress API 的一部分,因此如果 WordPress 已实例化,您可以调用该函数。
标签: javascript php jquery ajax wordpress