0

I want to show my new post published live in page without refresh. something like breaking news in blog websites.

How can i do this? anybody knows?

2
  • You could use an ajax request with a setTimeOut Nov 11 '17 at 9:23
  • @Jim-miraidev could you send me ex? Nov 11 '17 at 9:46
0

You can create a function for your ajax request, and set a timeout so it repeats. You will also need to send the ids of the current news articles being displayed so you can exclude them from your new WP_Query in your PHP

UPDATED - This now uses a data attribute to create an array of post ids to exclude off the next ajax request.

live.php

<div class="latest-news">
      <?php 
        $current_posts_ids = array();
        $args = array(
          'post_type' => 'post',
          'post_status' => 'publish',
        );
        $my_posts = new WP_Query( $args );

        if ( $my_posts->have_posts() ) : ?>
          <div class="posts">
            <?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
              <?php array_push($current_posts_ids, get_the_ID() );?>
              <article data-id="<?php echo get_the_ID()?>">
                <h2><?php the_title() ?></h2>
                <p><?php the_excerpt() ?><p>
              </article>
            <?php endwhile ?>
          </div>
        <?php endif ?>
 </div>

 <script>
  $(document).ready(function(){

      var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";   
      var dataArray =  <?php echo json_encode($current_posts_ids) ?>;

      function getMyPosts() {

            data = { action: "update_news", data: dataArray};
            $.post(ajaxurl, data, function(response) {
                // reset array
                dataArray = [];
                // append the new news posts                
                $('.latest-news .posts').append(response);
                // create new array of ids to exclude
                $('article').each(function(){
                    dataArray.push($(this).data('id'));  
                }); 
                // repeat function after 5 seconds
                setTimeout(function () {
                    getMyPosts();
                }, 5000)
            });

     }
     //run the function first time
     getMyPosts();   

});
</script>

function.php

add_action( 'wp_ajax_update_news', 'update_news' );
add_action('wp_ajax_nopriv_update_news', 'update_news');
function update_news() {
    global $wpdb;
    $data = $_POST['data'];

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'post__not_in' => $data,
    );
    $my_posts = new WP_Query( $args );

    if($my_posts->have_posts()) :
    while($my_posts->have_posts()) : $my_posts->the_post();          
        echo "<article data-id='".get_the_ID()."'>";
        echo "<h2>" . get_the_title() . "</h2>";
        echo "<p>" . get_the_excerpt() . "</p>";
        echo "</article>";
    endwhile;
    endif;

 wp_die();

}
19
  • just put it on my page? Nov 11 '17 at 11:16
  • Put the JS in a JavaScript file that is included on the page you are showing the posts. The php then goes into your function.php file. The 'action': 'update_news' in the ajax direct to the function 'wp_ajax_update_news'. Nov 11 '17 at 11:22
  • i put it but nothing show still Nov 11 '17 at 11:42
  • i put my code on second answer Nov 11 '17 at 11:46
  • can you update the question instead of the answer please and i will update the answer Nov 11 '17 at 11:50
0

my live.php page :

<!DOCTYPE html>
<html lang="fa">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php wp_head(); ?>

  </head>
  <body>

    <script type="text/javascript">
    var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";

    function getMyPosts() {
            // get the current ids of the post on that page using a
            var $current_posts = [1,2,3] //example of id array

            var data = {
                'action': 'update_news',
                'posts': 1,
                'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
            };

            $.post(ajaxurl, data, function(response) {
                // append the new news posts
                $('.latest-news').append(response);
                // repeat function after 5 seconds
                setTimeout(function () {
                    getMyPosts();
                }, 5000)
            });
     }
     //run the function first time
     getMyPosts();
    </script>

  </body>
</html>

and my function code:

function live_post() {

  global $wpdb; // this is how you get access to the database

  $data = $_POST['data'];
  $current_posts = $_POST['posts'];
  $args = array(
      'post_type' => 'post', // add post type
      'post_status' => 'publish',
      'posts_per_page' => '-1',
      'post__not_in' => array( $current_posts )
  );
  //Query the posts
  $my_posts = new WP_Query( $args );
  if ( $my_posts->have_posts() ) :
      ?>
      <?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
          <h2><?php the_title() ?></h2>
          <?php the_excerpt() ?>
      <?php endwhile ?>
      <?php
  endif;
  wp_die();
  }


add_action( 'wp_ajax_update_news', 'live_post' );
2
  • first you need to add you original loop to get the post on load Nov 11 '17 at 11:48
  • could you do this things for me? Nov 11 '17 at 11:51

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.