[英]How to use get_posts() function in functions.php
I am trying to load posts with ajax. 我正在尝试用ajax加载帖子。 But I am not getting any content of the posts. 但是我没有收到任何帖子内容。 I am not posting my javascript since it is pretty straight. 我没有发布我的JavaScript,因为它很简单。 Here is my code in inc/helper-functions.php which is included in main functions.php. 这是我在inc / helper-functions.php中的代码,该代码包含在main functions.php中。
function get_my_posts(){
$posts_per_page = $_POST['posts_per_page'];
$category = $_POST['category'];
$args = array(
'posts_per_page' => $posts_per_page,
'offset' => 0,
'category' => $category,
'orderby' => 'date',
'order' => 'DESC'
);
$myposts = get_posts( $args );
if ( $myposts ) {
foreach ( $myposts as $post ) {
setup_postdata( $post );
get_template_part( 'content', get_post_format() );
}
wp_reset_postdata();
} else {
echo 'Ingen innhold';
}
wp_die();
}
add_action("wp_ajax_get_my_posts", "get_my_posts");
add_action('wp_ajax_nopriv_get_my_posts', 'get_my_posts');
Here is how content.php looks like: 这是content.php的样子:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="meta">
<?php the_time('d.m.Y') ?>
</div>
<header class="entry-header">
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
</header>
<div class="entry-content">
<?php the_excerpt(); ?>
</div>
</article>
I am getting through the loop, but don't get the contents to be printed. 我正在经历循环,但没有得到要打印的内容。 None of the functions for ex. 没有ex的功能。 the_ID(), the_excerpt(), post_class(), etc. don't work. the_ID(),the_excerpt(),post_class()等无效。 If I use the same code in the template, it works fine. 如果我在模板中使用相同的代码,则可以正常工作。
$post
is a global, so before using setup_postdata( $post );
$post
是全局的,因此在使用setup_postdata( $post );
之前setup_postdata( $post );
(it must be $post
and not $anyvar
!) you need to add it to the current scope. (必须是$post
而不是 $anyvar
!),您需要将其添加到当前作用域中。 Add the following at the beginning of the function where you use setup_postdata
: 在使用setup_postdata
的函数的开头添加以下内容:
global $post;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.