Don H
Don H

Reputation: 901

Dataobject in Silverstripe: Getting data from a Wordpress database

Apologies if this is a simple one, I'm getting my head round how data objects work in Silverstripe.

My task is to obtain a list of posts from a wordpress blog (currently on /blog) on our site, and display the most recent post in the footer, and in another case, display posts by certain editors on their page.

I've seen the manual page for SqlQuery, but whenever I try anything from it I get an error. The code I'm using is based on the example, and looks like this:

    $sqlQuery = new SQLQuery();
    $sqlQuery->select = array(
      'post_title',
      'post_content',
      'post_name'
    );
    $sqlQuery->from = array("
      wp_posts
    ");
    $sqlQuery->where =  array("
        post_status = 'publish'
    ");
    $sqlQuery->orderby = "
        post_date DESC
    ";
    // $sqlQuery->groupby = "";
    // $sqlQuery->having = "";
    // $sqlQuery->limit = "";
    // $sqlQuery->distinct = true;

    // get the raw SQL
    $rawSQL = $sqlQuery->sql();

    // execute and return a Query-object
    $result = $sqlQuery->execute();
    $myDataObjectSet = singleton('wp_posts')->buildDataObjectSet($result);
    var_dump($myDataObjectSet->First()); // DataObject

The error I'm getting is:

[User Error] Bad class to singleton() - wp_posts

Upvotes: 0

Views: 990

Answers (1)

ryanwachtl
ryanwachtl

Reputation: 381

This will return you a DataObjectSet of your WordPress posts (latest 3 in this case). Assuming WordPress resides in the same database as SilverStripe.

function LatestPosts() {
    $sqlQuery = new SQLQuery();
    $sqlQuery->select("post_title", "post_content");
    $sqlQuery->from("wp_posts");
    $sqlQuery->where("post_status = 'publish'");
    $sqlQuery->orderby("post_date DESC");
    $sqlQuery->limit(3);

    if ($result = $sqlQuery->execute()) {
        $wp_posts = new DataObjectSet();
        foreach($result as $row) {
            $wp_posts->push(new ArrayData($row));
        }
        return $wp_posts;
    }

    return;
}

You can then iterate over your DataObjectSet in your template.

<% if LatestPosts %>
    <% control LatestPosts %>
        <h3>$post_title</h3>
        <div>$post_content</div>
    <% end_control %>
<% end_if %>

Upvotes: 1

Related Questions