How do I go about retrieving all of the blogposts from my Wordpress blog via an external PHP script? Is this even possible? I have seen the API for creating a Wordpress plugin, but I'm not sure if that is relevant in this particular case. Any suggestions are greatly appreciated. Thank you.
Your external script can load the wordpress api with
include('blog/wp-load.php'); // change blog/ to your actual path
Then you can use get_posts or query_posts to get the posts you want.
Wordpress has a feed that your posts get published to by default. You can read the XML feed, and parse out the relevant data.
I've got a vanity site that I use to send clients to, and I also contribute occasionally to a blog. One of the things that my vanity site shows is a short list of links to the top 5 most recent posts from the blog. Here's the code I use to do it:
<ul>
<?php
//slurp latest post from Wordpress' RSS feed, and cache them for short time.
$posts = '';
$cachefile = 'my-blog-cache-file.html';
if (is_readable($cachefile) && filemtime($cachefile) > (time() - 1800)) {
readfile($cachefile);
}
else {
$doc = new DOMDocument();
$doc->load('http://my.wordpress.blog/feed');
$items = $doc->getElementsByTagName('item');
foreach($items as $i)
{
if ($i->hasChildNodes()) {
$title = $link = '';
foreach($i->childNodes as $cn) {
if ($cn->nodeName == 'title') $title = $cn->nodeValue;
if ($cn->nodeName == 'link') $link = $cn->nodeValue;
if ($cn->nodeName == 'dc:creator') $author = $cn->nodeValue;
}
if ($title != '' && $link != '' && $author == 'my name') {
$posts .= '<li>'.$title.'</li>'."\n";
}
}
}
file_put_contents($cachefile,$posts);
echo $posts;
}
?>
</ul>
Feel free to use this code. You can examine the feed of your own blog and decide what elements you want to parse out. Generally your feed will be located at your blog's URL, with /feed tacked onto the end.
The other alternative of course is to use PHP to connect to your database and read the database yourself :)
//You'll want to set your database credentials
mysql_connect($server, $username, $password);
mysql_select_db($wp_db);
// Modify the fields to pull whatever data you need for the output, even perhaps join the wp_users table for user data
// Setting the ORDER BY to DESC to mimic the Wordpress ordering with newest first
$sql = "SELECT ID, post_author, post_date, post_content, post_title, post_status, post_name, guid FROM wp_posts ORDER BY post_date DESC";
$data = mysql_query($sql);
$num = count($data);
for($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($data);
// Output your posts to something
print_r($row);
}
This should allow you to play with the data far more easily :)
You'll want to take a look at Magpie. It's a fairly straight-forward RSS client for PHP, which let's you subscribe to any feed and get the posts with just a few lines of code.
Related
I am trying to create a post-comment system, with simple php-mysqli, as simple as it is, it does not seem to give me the result in the fashion I want i.e:
---POST MESSAGE----
-----comments-----
Here is the code I used:
<?php
session_start();
include_once('php_includes/db_conx.php');
$user=$_SESSION['user'];
$o =mysqli_query($db_conx, "SELECT post.id,post.post,post.date,post_comments.poster,post_comments.comment,post_comments.date FROM post LEFT JOIN post_comments ON post.id=post_comments.post_id AND post.username='$user' ORDER BY post.date");
while($r=mysqli_fetch_array($o,MYSQLI_ASSOC)){
$status= $r['post'];
$date=$r['date'];
$com=$r['comment'];
$pid=$r['id'];
$poster=$r['poster'];
if(count($pid) > 1){
}
echo $status.'|'.$pid.'|'.$date.'<br>'.$poster.':'.$com.'<hr>';
}
?>
It seems to duplicate the post for each comment for same post.
Not sure am making sense, but i will appreciate an answer.
First, add post id to your query's ORDER BY. That will ensure that your post and all its comments appear together, and only once. (I'd recommend adding post_comments.date as well so your comments will appear in order, but that won't be necessary to get the grouping working.)
... ORDER BY post.date, post.id, post_comments.date
Then keep track of the post id as you go. Echo the post information only when the post id changes.
$id = null; // initialize to null
while ($r = mysqli_fetch_array($o, MYSQLI_ASSOC)) {
$pid = $r['id'];
$status = $r['post'];
$date = $r['date'];
$com = $r['comment'];
$poster = $r['poster'];
if ($pid !== $id) {
echo $status.'|'.$pid.'|'.$date.'<br>'; // new post, so echo post info here
$id = $pid; // $id becomes new post id
}
if ($com) {
echo $poster.':'.$com.'<br>'; // echo comment if present
}
}
One other thing that will probably cause some trouble is that you have selected both post.date and post_comments.date in your query, so I'm not sure which one will be in $r['date']. It would be a good idea to alias at least one of those columns to disambiguate them.
I know this has been done before. You can see an example of it whenever you post a new blog post/page in Wordpress, and the title is the same title as an existing page/post. Here's an example:
some-page-slug
some-page-slug-1
some-page-slug-2
How would you programmatically (using PHP) deal with someone submitting the slug of "some-page-slug" with the given list. Obviously, you should result in "some-page-slug-3", but what does that code look like? For some reason, this escapes me. I'm assuming, and hopefully I'm wrong, you would have to use jQuery (or vanilla js, whatever), correct?
Here's a possible solution like Mathew MacLeans suggested in his comment:
$slug = 'slug';
$slugs = array('slug', 'slug-1', 'slug-2', 'slug-5');
$result = $slug;
$i = 1;
while(in_array($result, $slugs)) {
$result = $slug . '-' . $i;
++$i;
}
// prints 'slug-3'
print $result;
Of course you have to replace in_array with your function that checks for existence of a slug.
Demo
Try before buy
Just some pseudo-code to get you going, but I believe this is the route you should take.
$postTitle = <WhateverTheTitleIs>;
$result = mysql_query("SELECT id FROM mytable WHERE title = '$postTitle'");
if(mysql_num_rows($result) == 0) {
// title not found, submit to database
} else {
// title exists
$postTitle = $postTitle + 1;
}
Now, obviously this isn't anywhere near 100% correct syntax, but it should more than point you in the direction that you need to go. :)
I imported a site to Wordpress that has no titles associated to posts. Each post does have h1 tags...
Can anyone tell me the best way to go into MYSQL and write some script to auto generate the titles of each post based on the h1 tags of each???
When final I need to be able to see these titles in the post section of the WordPress dashboard.
Below Is the code based on your responses Andrew. I created a file called createtiles.php and included it in my rrot directory. Not sure whats going on but when i look at my Post section in WordPress dashboard I still see (No Title).
<?php
$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$all_posts = mysql_connect("SELECT * FROM wp_posts");
while ($item = mysql_fetch_assoc($all_posts))
{ $pid = $item['post_id'];
$new_title = substr($item['post_content'],0,70);
mysql_query("UPDATE wp_posts SET post_title='".$new_title."'");
}
mysql_close($link);
?>
(Some of my post only have h1 tags with no other content. )
Well, just a quick rough draft without doing much of any of the work for you.
$title = mysql_fetch_assoc(mysql_query("SELECT post_content, post_title, post_id FROM wp_posts");
foreach($title as $final_title) {
$post_id = $final_title['post_id'];
$post_content = $final_title['post_content'];
$final_content = '<h1>'.$final_title['post_title'].'</h1><br /><br />'.$post_content;
$q = mysql_query("UPDATE wp_posts SET post_content='".$final_content."'");
}
And that's all she wrote. I didn't do much of the work for you, but it definitely is the way to go. Vote Up.
Please do not pay attention to my other answer. It is backwards to what you want.
You need to use http://us2.php.net/substr method to grab a certain amount of characters from your title. I would grab that first 26 letters from your post and then update the titles.
What you need to do is something like this.
$all_posts = mysql_query("SELECT * FROM wp_posts");
while ($item = mysql_fetch_assoc($all_posts)) {
$pid = $item['post_id'];
$new_title = substr($item['post_content'],0,26);
mysql_query("UPDATE wp_posts SET post_title='".$new_title."'");
}
Now that's all she wrote. ;)
I am building a Wordpress site with the Constructor theme. I had to add custom coding to solve my goals. There is a module, that let's the user add children elements to his profile, that will be saved to database. (create, update, delete) This functionality is done with the following files in:
wp-content\themes\constructor\crud\
destroy_user.php,
get_users.php,
save_user.php,
show_form.php,
update_user.php
These files at the moment have no includes, they are only called from a custom coded page template. So far they work.
Now I would like to develop this module to handle multiple users. For this I would need to know who is using the module. This I know at the custom page template, but not at the code in ex. get_users.php . For example I would like to use
$user_id = get_current_user_id();
in get_users.php to control the sql and redirect the user if he is not logged in. What files and how must I include, to be able to use get_current_user_id()?
(Simply include '../../../../wp-includes/user.php' does not solve it.)
Thanks for the help,
Sziro
Edit: this is wp-content\themes\constructor\crud\get_users.php
<?php
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$offset = ($page-1)*$rows;
$result = array();
include 'conn.php';
require('../../../../wp-blog-header.php');
$user_id = get_current_user_id(); //This does not work. If it would be set to = 1, it would work.
$rs = mysql_query("select count(*) from user_partner where user_id=$user_id");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$rs = mysql_query("select * from user_partner where user_id=$user_id limit $offset,$rows");
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
?>
So currently a Wordpress theme includes and uses this files. And you want to create another/use the same php file to include Wordpress' functions?
You can include Wordpress functions by:
<?php
require('/root_of_wp_installation/wp-blog-header.php');
//or require('../../../../wp-blog-header.php');
get_categories();
?>
In the end it was solved with an iframe. Not very safe, but at least presentable.
This is a basic code which I use to pull info from my affiliate product feed. I'm pulling, as you will see below, picture links...and store the urls into my databse. The problem is that I'm showing 20 products per page, and if the affiliate serves isn;'t working properly it slows donw my sites alot.
What i'd like to do is store the whole iamges somehow and hot the urls... I think that will improve my sites performance alot. Any ideeas?
$feed = 'my affiliate feed';
$xml = simplexml_load_file($feed);
foreach( $xml->productinfo as $productinfo )
{
$pic0 = $productinfo->picture[0];
$pic1 = $productinfo->picture[1];
$pic2 = $productinfo->picture[2];
mysql_query("INSERT INTO ".$table." (pic0, pic1, pic2) VALUES ('$pic0', '$pic1', '$pic2')");
}
Thank you
First change pic0, pic1 and pic2 fields to BLOB type. (You might also want to store the MIME type with getimagesize() for use with header() when delivering the images.)
$feed = 'my affiliate feed';
$xml = simplexml_load_file($feed);
foreach( $xml->productinfo as $productinfo )
{
for($i = 0; $i<=2; $i++) {
$pic[$i] = mysql_real_escape_string(file_get_contents($productinfo->picture[$i]));
}
mysql_query("INSERT INTO $table (pic0, pic1, pic2) VALUES ('$pic[0]', '$pic[1]', '$pic[2]')");
}
I presume that you have an ID field in $table. Deliver images in a new PHP script like this:
if (!isset($_GET['id'])) die('No ID');
if (!isset($_GET['pic']) || !in_array($_GET['pic'], array(0, 1, 2)))
$i='0';
else
$i=mysql_real_escape_string($_GET['pic']);
$sql = sprintf( "SELECT pic$i FROM $table WHERE id=%s", mysql_real_escape_string($_GET['id']));
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
$row=mysql_fetch_array($result);
header("Content-type: image/jpeg");
echo $row[0];
well you can also store it as base64
blobs make the website not faster, the more db requests you have the more slow is the website
if that are just a few images its ok and if you have a fast db server