WordPress post values into new class object

I’m trying to put WordPress post values into a new class object so I can return back to my Ajax post

What i’ve currently got:

Read More

Ajax

$(document).ready(function() 
{
  GetLatestBlogPost();
});

function GetLatestBlogPost()
{
  $.ajax(
  {
      url: "IsosecWeb/php/getLatestBlogPost.php",
      type: 'POST',
      beforeSend: function()
      {
          console.log("Before send...");
      },
      success: function (successData) 
      {
         console.log(successData);
         console.log("successful send...");
      },
      error: function(errorData)
      {
          // Loading data loader
          console.log("Error send...");
      }
  });
}

PHP (Get WordPress post values)

require('../../blog/wp-blog-header.php'); 

// Create an object to store the data to be returned in
$returnObject = new stdClass();

function GetFirstLastestBlogPost()
{

    $args = array( 'numberposts' => 1, 'offset' => 0, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
    $postslist = get_posts( $args );
    foreach ($postslist as $post) :  setup_postdata($post); 

    $returnObject->getFirstImage = getTheFirstImage();
    $returnObject->getBlogDate = the_date();
    $returnObject->getTitle = the_title();
    $returnObject->getContent = wp_trim_words(preg_replace("/< *[img][^>]*[.]*>/i","", get_the_content(), 80), 80);
    $returnObject->getAuthorLink = the_author_posts_link();

    endforeach;  

    return $returnObject;
}

function getTheFirstImage() 
{
    $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
    if($files) :
        $keys = array_reverse(array_keys($files));
        $j=0; $num = $keys[$j];
        $image=wp_get_attachment_image($num, 'large', false);
        $imagepieces = explode('"', $image);
        $imagepath = $imagepieces[1];
        $thumb=wp_get_attachment_thumb_url($num);
        echo "<img src='$thumb' class='thumbnail' />";
    endif;
}

echo json_encode(GetFirstLastestBlogPost());

Returned console message

Before send...

<img src='http://isosec.co.uk/blog/wp-content/uploads/2015/07/CJ9WINoWEAARSPW-150x150.jpg' class='thumbnail' />July 22, 2015EHI Awards: Finalists Announced<a href="http://isosec.co.uk/blog/?author=7" title="Posts by Jo Flynn" rel="author">Jo Flynn</a>{"getFirstImage":null,"getBlogDate":null,"getTitle":null,"getContent":"You may have read in our blog some weeks ago that we had been shortlisted for the EHI Awards 2015 in the Excellence in Mobile Healthcare category. At the time we didnu2019t know a lot about who else was involved or the overall process but we have a lot more to share as we are nowu2026 Finalists! As you can imagine we are very excited about this, so in this blog we thought it would share a little more about&hellip;","getAuthorLink":null}

successful send...

It’s not returning the message with the key values. Does anyone know why this is happening?

expected outcome

  • KEY: getFirstImage Value: Image
  • KEY: getBlogDate Value: Date
  • KEY: getTitle Value: Title
  • KEY: getContent Value: Content
  • KEY: getAuthor Value: Author

Output given from Tomasz Struczyński’s answer:

Before send...
getBlogPost.js:26 Error... 
getBlogPost.js:27 {"readyState":4,"responseText":"July 22, 2015EHI Awards: Finalists Announced<a href="http://isosec.co.uk/blog/?author=7" title="Posts by Jo Flynn" rel="author">Jo Flynn</a>{"getFirstImage":"http:\/\/isosec.co.uk\/blog\/wp-content\/uploads\/2015\/07\/CJ9WINoWEAARSPW-150x150.jpg","getBlogDate":null,"getTitle":null,"getContent":"You may have read in our blog some weeks ago that we had been shortlisted for the EHI Awards 2015 in the Excellence in Mobile Healthcare category. At the time we didn\u2019t know a lot about who else was involved or the overall process but we have a lot more to share as we are now\u2026 Finalists! As you can imagine we are very excited about this, so in this blog we thought it would share a little more about&hellip;","getAuthorLink":null}","status":200,"statusText":"OK"}

Related posts

1 comment

  1. UPDATE – added content-type header set

    First of all, you should consider using standard WordPress AJAX hooks as described here: https://codex.wordpress.org/AJAX_in_Plugins

    As for your approach:

    In plain PHP you have to print your return value. Simply returning it from function doesn’t cause it to be sent back to client. You have to echo it somehow. I suggest JSON format, as it will be quite easy to program.

    For frontend – add dataType: ‘json’ to your request like that:

    $.ajax(
      {
          url: "IsosecWeb/php/getLatestBlogPost.php",
          type: 'POST',
          dataType: 'json',
          beforeSend: function()
          {
              console.log("Before send...");
          },
         success: function (successData) 
         {
            console.log(successData);
            console.log("successful send...");
         },
         error: function(errorData)
         {
              // Loading data loader
             console.log("Error send...");
         }
      });
    

    And then the backend:

    header('Content-Type: application/json');
    
    require('../../blog/wp-blog-header.php'); 
    
    // Create an object to store the data to be returned in
    
    function GetFirstLastestBlogPost()
    {
        $returnObject = new stdClass();
    
        $args = array( 'numberposts' => 1, 'offset' => 0, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
        $postslist = get_posts( $args );
        foreach ($postslist as $post) {
            setup_postdata($post); 
    
            $returnObject->getFirstImage = getTheFirstImage();
            $returnObject->getBlogDate = the_date();
            $returnObject->getTitle = the_title();
            $returnObject->getContent = wp_trim_words(preg_replace("/< *[img][^>]*[.]*>/i","", get_the_content(), 80), 80);
            $returnObject->getAuthorLink = the_author_posts_link();
        }
    
        return $returnObject;
    }
    
    function getTheFirstImage() 
    {
        $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
        if($files) {
            $keys = array_reverse(array_keys($files));
            $j=0; $num = $keys[$j];
            $image=wp_get_attachment_image($num, 'large', false);
            $imagepieces = explode('"', $image);
            $imagepath = $imagepieces[1];
            $thumb=wp_get_attachment_thumb_url($num);
            return $thumb;
        }
        return null;
    }
    
    echo json_encode(GetFirstLastestBlogPost());
    

    I have changed code styling to standards (PSR-0 and following), as the notation without curled braces is used mainly in teplates, not in functions.

Comments are closed.