0

I am trying to load posts with ajax. But I am not getting any content of the posts. I am not posting my javascript since it is pretty straight. Here is my code in inc/helper-functions.php which is included in 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:

<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. the_ID(), the_excerpt(), post_class(), etc. don't work. If I use the same code in the template, it works fine.

1

There should be a global declaration of $post at the beginning of the function. Just like this:

function get_my_posts(){
    global $post;
    // rest of the code.
}

Original answer from stackoverflow: xphan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.