Quantcast
Viewing all articles
Browse latest Browse all 10

Retrieving a post from WordPress and displaying it in your site

Image may be NSFW.
Clik here to view.
wordpress-blog-extract-post-to-website

Yeah, I know… It sounds like a simple thing to do. And yeah, that’s exactly what I though when I decided to do it, but I was wrong Image may be NSFW.
Clik here to view.
:)

Once I got the body of the wanted post, I found some troubles when printing it out. It was not well formatted, the paragraphs breaks were not shown…

I almost had it fixed by using a couple of PHP functions like `nl2br` and `utf8_encode`, but I still had problems with some “weird” characters such as long dashes:

$query = $conn->prepare("select * from wp_posts where post_title = :title and post_status = 'publish'");
$query->bindParam(':title', "myDemo");
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

echo nl2br(utf8_encode($results['post_content']));

Then I just decided to take a look the wordpress template files and figure out how it really worked inside.
And… I might be wrong, but I found it quite crazy and chaotic to understand for newbies in WordPress insides like me.

After some time researching on wordpress docs and reading what the mysterious functions were really doing (like `setup_postdata` which sets global variables…), I found out that the way of displaying the content was just by calling another function called `the_content()`, which prints the result (and doesn’t return it…).

This is the way I ended up doing it:

<?php
//including the needed wordpress files
require_once ('blog/wp-load.php');

//connecting the with DB
$conn = $this->_db->getConn();

//querying the DB looking for our post
$query = $conn->prepare("select * from wp_posts where post_title = :title and post_status = 'publish'");
$query->bindParam(':title', "myDemo");
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

//getting the Post WordPress object by its ID
$post = get_post($texto['ID']);

//calling the funny mysterious function
setup_postdata($post);

//printing the content with this funny echo
the_content();

?>

Viewing all articles
Browse latest Browse all 10

Trending Articles