Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
Show random post in Wordpress and update content without refreshing page

I'm building a Wordpress website where I need to display a random post (via WP_Query) and reload its content with a click of a button without refreshing the whole page.

This is my HTML

<div id="randompost"></div>
<button type="button" id="reloadpost">Reload post</button>

And this is my WP_Query

<?php

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'orderby' => 'rand',
    );

    $arr_posts = new WP_Query( $args );
        if ( $arr_posts->have_posts() ) : while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?>

                <h2><?php the_title();?></h2>
                <p><?php the_content();?></p>

    <?php endwhile; endif; ?>

I've read online about AJAX but I'm not that great at JS development and I could't find a way to make it work.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

For me the easiest way is to add jQuery reload function. So below your HTML with button, you will add

<script>
$(document).on('click', '#reloadpost', function(){ 
    $("#randompost").load(location.href + " #randompost");
});
</script>

(You also must use jQuery, so if you don't have it on your page, add <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda