Getting a div content of a post in wordpress?

How can I fetch a div content from a post?

Using the_content() can fetch all the data but instead of that, I need specific content from the div only. So far, all I could do was get the link of the post as the div content.

Here is was I am trying to do:

<?php while (have_posts()) : the_post(); ?>

<li style = "text-align: center; float : left;">

  <a href="https://wordpress.stackexchange.com/questions/235501/<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($id); ?></a>

  <div class="title">
    <a href="https://wordpress.stackexchange.com/questions/235501/<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
  </div>

  <div id = "result">`

    <?php echo "<script> 
      $('#result').load( '".the_permalink()." .ps_post_description' );
    </script>"; ?>

  </div>

</li>

<?php endwhile; ?>

ps_post_description is the class of the div for which I need the content.

2 Answers
2

Using DOMDocument and DOMXPath you could try this.

<?php while (have_posts()) : the_post();

ob_start();  // run the_content() through the Output Buffer
the_content();
$html = ob_get_clean(); // Store the formatted HTML
$content = new DomDocument(); // Create a new DOMDocument Object to work with our HTML
$content->loadHTML( $html ); // Load the $html into the new object
$finder = new DomXPath( $content );  // Create a new DOMXPath object with our $content object that we will evaluate
$classname="ps_post_description"; // The class we are looking for

$item_list = $finder->query("//*[contains(@class, '$classname')]"); // Evaluates our content and will return an object containing the number of items matching our query
?>

<li style = "text-align: center; float : left;">

  <a href="https://wordpress.stackexchange.com/questions/235501/<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($id); ?></a>

  <div class="title">
    <a href="https://wordpress.stackexchange.com/questions/235501/<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
  </div>

  <div id = "result">`
    <?php 
    // echo the value of each item found
    // You might want to format or wrap your $value according to your specification if necessary
    for( $i = 0; $i < $item_list->length; $i++ ){
    $value = $item_list->item( $i )->nodeValue;

      echo $value;

      // if you want the text to be a link to the post, you could use this instead 
      // echo '<a href="' . get_the_permalink() . '">' . $value . '</a>';

    } ?>
  </div>

</li>

<?php endwhile; ?>

UPDATE

Made use of Output Buffering to expand shortcodes before we try to load the HTML in DOMDocument

Note that both solutions (before and after the edit) are working, so errors/warnings should come from elsewhere in your setup.

Leave a Comment