wp_insert_post() not working when in loop - php

I have a script which scrapes articles from the web and saves the url to a .txt file. I've created a custom plugin which on activation, loops through the urls and creates a draft post with the content being an embedded article. I'm using the following code in my plugin
<?php
register_activation_hook(__FILE__, 'my_plugin_activate');
function my_plugin_activate(){
my_plugin_install_site();
}
function my_plugin_install_site(){
global $user_ID;
$handle = fopen("listOfURLs.txt", "r");
if ($handle) {
$count = 0;
while (($line = fgets($handle)) !== false) {
// process the line read.
PostCreator('test', 'post', '<iframe src="' . trim($line) . '" class="alumni-embeded-page"></iframe>');
}
fclose($handle);
}
// PostCreator( 'test1', 'post', '<iframe src="[link]" class="alumni-embeded-page"></iframe>' );
// PostCreator( 'test2', 'post', '<iframe src="[link]" class="alumni-embeded-page"></iframe>' );
}
function PostCreator(
$name = 'AUTO POST',
$type = 'post',
$content = 'DUMMY CONTENT',
$category = array(1,2),
$template = NULL,
$author_id = '1',
$status = 'draft'
) {
$post_data = array(
'post_title' => wp_strip_all_tags( $name ),
'post_content' => $content,
'post_status' => $status,
'post_type' => $type,
'post_author' => $author_id,
'post_category' => $category,
'page_template' => $template
);
$post_id = wp_insert_post($post_data);
}
The listOfURLs.txt file is simply a text file in the same directory with a link to an article on every line. I'm only using 5 links to test at the moment. The problem is currently the script does not create any posts when trying to use the loop. The PostCreator() method did work when I coded the method calls manually(as shown by the comments).
I'm also getting the following error when activating the plugin. Not sure it's related as it was still displayed when hard coding the method calls.
The plugin generated 205 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

Related

WP_insert_post automation does not work correct

So I am trying to automate the video upload via FTP and the insertion in the DB.
I wrote a script which is located at the server and uses the included WP funciton:
<?php
$title = $_GET["title"];
$pw = $_GET["key"];
$key = hash('sha256',$pw);
$hash = "hashfromkey";
if ($hash == $key){
$videowebm = $title . ".webm";
$videomp4 = $title . ".mp4";
$image = $title . ".jpg";
$content = "<video id=\"my-video\" class=\"video-js vjs-big-play-centered\" controls preload=\"auto\" poster='$image' data-setup=\"{}\">
<source src=\"$videomp4\" type='video/mp4'>
<source src=\"$videowebm\" type='video/webm'>
<p class=\"vjs-no-js\"> activate js</p></video> ";
include( "wp-config.php" );
// Gather post data.
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_author' => 3
);
// Insert the post into the database.
$ID = wp_insert_post( $my_post, true );
}
?>
If I open the URL in my browser (urltofile?title=jeff&key=key), everything works fine.
When using the python script
#!/usr/bin/python3
from os import listdir;
adress = 'url';
user = 'ftpuser';
PW = 'ftppw';
url = 'urltofile?title=';
url_short = 'Urltofile';
key = '&key=key';
dir = input("Choose Folder");
for file in dir:
if file.endswith(".txt"):
print(file)
urlges = url + file + key;
#data = urllib.parse.urlencode(data);
#data = data.encode('utf-8');
html_quelltext = urllib.request.urlopen(urlges).read();
I get
<video id="my-video" class="video-js vjs-big-play-centered" controls preload="auto" poster='Testscribbles.txt.jpg'>
<p class="vjs-no-js"> activate js</p></video>
So I am missing the two lines where I specify my sources. I don't understand why it happens only when using the script (I had the same script in Perl, got the same result).
I tried it with a get statement from urllib but I could not get it to work (probably a different problem).
Does anybody have an idea what the solution might be?
Thanks in advance!
By default Wordpress post status' are "Draft" which is somewhat unpublished, depending on your theme settings.
Based on your current requirements, perhaps "publish" is what you need:
// Gather post data.
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_author' => 3,
'post_status' => 'publish'
);
// Insert the post into the database.
$ID = wp_insert_post( $my_post, true );
remove_all_filters("content_save_pre");
Is the solution to my problem. Wordpress tries to sanitize the code to prevent harmful codes.

Wordpress REST API - Write to JSON File?

I've been messing around with the Wordpress REST API, and created my custom endpoint, and getting the exact data I want. Basically I created an endpoint to receive all my post/pages/acf - Instead of calling the API on each page load, I just wanted to call the API once during my preloader.
However, when I call the API, all the logic runs, which then causes a loading time of 1 to 2 seconds. Is there a possibility that whenever I make an update on Wordpress, it will call my endpoint, and write a JSON file on the server, so data.json? This way, when I load my site, it can call that data.json, with absolutely no delay at all.
I'm not sure if this is possible but wanted to try asking here.
I found 3 different ways to address the question, all of them here on Stackoverflow, but I'll go with the one that Tanner started, just published in full:
function export_posts_in_json() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
$posts = array();
while ($query->have_posts()): $query->the_post();
$posts[] = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'author' => get_the_author(),
// any extra field you might need
);
endwhile;
wp_reset_query();
$data = json_encode($posts);
$upload_dir = wp_get_upload_dir(); // set to save in the /wp-content/uploads folder
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen($save_path, "w"); //if json file doesn't gets saved, comment this and uncomment the one below
//$f = #fopen( $save_path , "w" ) or die(print_r(error_get_last(),true)); //if json file doesn't gets saved, uncomment this to check for errors
fwrite($f, $data);
fclose($f);
}
add_action('save_post', 'export_posts_in_json');
Original snippet here: https://wordpress.stackexchange.com/questions/232708/export-all-post-from-database-to-json-only-when-the-database-gets-updated
Hope this helps.
This method allow you to write a json from and external or internal API endpoint;
it is less sofisticated than the one above (destination folder wise), but uses the REST API so you can fetch the full posts object without having to specify all the fields:
// Export API Data to JSON, another method
add_action('publish_post', function ($ID, $post) {
$wp_uri = get_site_url();
$customApiEndpoint = '/wp-json/wp/v2/posts'; // or your custom endpoint
$url = $wp_uri . $customApiEndpoint; // outputs https://your-site.com/wp-json/wp/v2/posts
// $url = 'https://your-site.com/wp-json/wp/v2/posts'; // use this full path variable in case you want to use an absolute path
$response = wp_remote_get($url);
$responseData = json_encode($response); // saved under the wp root installation, can be customized to any folder
file_put_contents('your_api_data_backup.json', $responseData);
}, 10, 2);
inspired from https://stackoverflow.com/questions/46082213/wordpress-save-api-json-after-publish-a-post
You should be able to accomplish something along those lines. Check out the code below:
function export_posts_in_json () {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
...
$data = json_encode($posts);
$folder = 'YOUR_EXPORT_PATH_HERE';
$file_name = date('Y-m-d') . '.json';
file_put_contents($folder.$file_name, $data);
}
add_action( 'save_post', 'export_posts_in_json' );
This should save a json file every time a post is made. I'm sure you can modify it to export all the data you need for your site.

How do I develop a WordPress plugin to fetch the posts and parse it as JSON on my home page?

I am trying to develop a small WordPress plugin to fetch the posts, pages from the website and parse it as json to further use in mobile apps.
Right now I am achieving the goal via this method:
1) Created a file webservice.php on my current active theme eg. twentythirteen. So the location of the file is:
http://www.example.com/wp-content/themes/twentythirteen/webservice.php
2) I am posting the parameters on that URL to get a JSON response like this
http://www.example.com/wp-content/themes/twentythirteen/webservice.php?type=page&limit=10
The thing is I want to post parameters on the home page like this:
http://www.example.com?type=page&limit=10
I don't know how to do it but I have seen the JSON API plugin which is doing the same thing but I'm not able to find in the code how it's fetching the request from the home page and parse JSON on the same page. How can I do this?
I developed a WordPress plugin and I'm using it for my PhoneGap app, but it may also help you. This is the code for the callback last posts:
header('Content-Type: application/json');
require('../../../wp-load.php');
require('../../../wp-includes/pluggable.php');
$post = "";
$elementos = 5; //Number of Post
$yaCargados = 0;
global $wpdb;
if($_POST['num_post']!=0 or $_POST['num_post']!="NULL") {
$elementos = $_POST['num_post'];
$yaCargados = $_POST['paginacion'];
}
$args = array(
'posts_per_page' => $elementos,
'offset' => $yaCargados,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args );
if(0 < $posts_array) {
foreach( $posts_array as $term) {
$res['posts'][] = $term;
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $term->ID ), 'medium' );
$res['images'][]['imagen'] = $image;
$custom_fields = get_post_custom($term->ID);
$res['custom_field'][] = $custom_fields;
}
echo json_encode($res);
}else{
}
Save archive in /wp-content/plugins/[YOUPLUGIN] and call and print post in JSON format.
Happy Coding!

How to fetch full content from RSS url?

I’m developing an RSS fetcher API which can fetch the full RSS content from RSS URL. I have searched a lot but I am unable to make it work. Now my API gets only short content (description) from RSS feed URL.
The code used by me:
$rss = fetch_feed($entry->rss_link);
$number_of_post=2;
$iCount=0;
foreach ($rss->get_items() as $item)
{
$content= $item->get_description();
if($entry->remove_link){
$content=strip_tags($content, '<p><div><i><b><u><img>');
}
$iCount++;
$sfp_page = array(
'post_title' => $item->get_title(),
'post_status' => 'publish',
'post_content' =>$content,
'post_type' => 'sfp_forum',
'post_author' => $entry->author_id,
'post_date' => current_time('mysql')
);
$rss_id = wp_insert_post($sfp_page);
}
$content doesn’t have the full content.
Any suggestions?
You probably need to do something like the following because you are overwriting your $content on each iteration so you only get the last item.
$rss = fetch_feed($entry->rss_link);
$number_of_post=2;
$iCount=0;
$content = array();
foreach ($rss->get_items() as $item){
$content[$iCount] = $item->get_description();
if($entry->remove_link){
$content[$iCount] = strip_tags($content[$iCount], '<p><div><i><b><u><img>');
}
$iCount++;
}
var_dump($content);

How to attach an image to a post using wordpress and xml-rpc? [duplicate]

Anyone knows how to create new post with photo attached in WordPress using XMLRPC?
I am able to create new post and upload new picture separately, but looks like there is no way to attach the uploaded photo to the created post?
Below is the codes I'm currently using.
<?php
DEFINE('WP_XMLRPC_URL', 'http://www.blog.com/xmlrpc.php');
DEFINE('WP_USERNAME', 'username');
DEFINE('WP_PASSWORD', 'password');
require_once("./IXR_Library.php");
$rpc = new IXR_Client(WP_XMLRPC_URL);
$status = $rpc->query("system.listMethods"); // method name
if(!$status){
print "Error (".$rpc->getErrorCode().") : ";
print $rpc->getErrorMessage()."\n";
exit;
}
$content['post_type'] = 'post'; // post title
$content['title'] = 'Post Title '.date("F j, Y, g:i a"); // post title
$content['categories'] = array($response[1]['categoryName']); // psot categories
$content['description'] = '<p>Hello World!</p>'; // post body
$content['mt_keywords'] = 'tag keyword 1, tag keyword 2, tag keyword 3'; // post tags
$content['mt_allow_comments'] = 1; // allow comments
$content['mt_allow_pings'] = 1; // allow pings
$content['custom_fields'] = array(array('key'=>'Key Name', 'value'=>'Value One')); // custom fields
$publishBool = true;
if(!$rpc->query('metaWeblog.newPost', '', WP_USERNAME, WP_PASSWORD, $content, $publishBool)){
die('An error occurred - '.$rpc->getErrorCode().":".$rpc->getErrorMessage());
}
$postID = $rpc->getResponse();
echo 'POST ID: '.$postID.'<br/>';
if($postID){ // if post has successfully created
$fs = filesize(dirname(__FILE__).'/image.jpg');
$file = fopen(dirname(__FILE__).'/image.jpg', 'rb');
$filedata = fread($file, $fs);
fclose($file);
$data = array(
'name' => 'image.jpg',
'type' => 'image/jpg',
'bits' => new IXR_Base64($filedata),
false // overwrite
);
$status = $rpc->query(
'metaWeblog.newMediaObject',
$postID,
WP_USERNAME,
WP_PASSWORD,
$data
);
echo print_r($rpc->getResponse()); // Array ( [file] => image.jpg [url] => http://www.blog.com/wp-content/uploads/2011/09/image.jpg [type] => image/jpg )
}
?>
I've been involved in WordPress sites (my current employer uses 3 of these) and posting stuff daily and by the bulk has forced me to use what I do best-- scripts!
They're PHP-based and are quick and easy to use and deploy. And security? Just use .htaccess to secure it.
As per research, XMLRPC when it comes to files is one thing wordpress really sucks at. Once you upload a file, you can't associate that attachment to a particular post! I know, it's annoying.
So I decided to figure it out for myself. It took me a week to sort it out. You will need 100% control over your publishing client that is XMLRPC compliant or this won't mean anything to you!
You will need, from your WordPress installation:
class-IXR.php, located in /wp-admin/includes
class-wp-xmlrpc-server.php, located in /wp-includes
class-IXR.php will be needed if you craft your own posting tool, like me. They have the correctly-working base64 encoder. Don't trust the one that comes with PHP.
You also need to be somewhat experienced in programming to be able to relate to this. I will try to be clearer.
Modify class-wp-xmlrpc-server.php
Download this to your computer, through ftp. Backup a copy, just in case.
Open the file in a text editor. If it doesn't come formatted, (typically it should, else, it's unix-type carriage breaks they are using) open it elsewhere or use something like ultraedit.
Pay attention to the mw_newMediaObject function. This is our target. A little note here; WordPress borrows functionality from blogger and movabletype. Although WordPress also has a unique class sets for xmlrpc, they choose to keep functionality common so that they work no matter what platform is in use.
Look for the function mw_newMediaObject($args). Typically, this should be in line 2948. Pay attention to your text editor's status bar to find what line number you are in. If you can't find it still, look for it using the search/find function of your text editor.
Scroll down a little and you should have something that looks like this:
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
After the $name variable, we will add something. See below.
$name = sanitize_file_name( $data['name'] );
$post = $data['post']; //the post ID to attach to.
$type = $data['type'];
$bits = $data['bits'];
Note the new $post variable. This means whenever you will make a new file upload request, a 'post' argument will now be available for you to attach.
How to find your post number depends on how you add posts with an xmlrpc-compliant client. Typically, you should obtain this as a result from posting. It is a numeric value.
Once you've edited the above, it's time to move on to line 3000.
// Construct the attachment array
// attach to post_id 0
$post_id = 0;
$attachment = array(
'post_title' => $name,
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => $post_id,
'post_mime_type' => $type,
'guid' => $upload[ 'url' ]
);
So here's why no image is associated to any post! It is always defaulted to 0 for the post_parent argument!
That's not gonna be the case anymore.
// Construct the attachment array
// attach to post_id 0
$post_id = $post;
$attachment = array(
'post_title' => $name,
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => $post_id,
'post_mime_type' => $type,
'guid' => $upload[ 'url' ]
);
$post_id now takes up the value of $post, which comes from the xmlrpc request. Once this is committed to the attachment, it will be associated to whatever post you desire!
This can be improved. A default value can be assigned so things don't get broken if no value is entered. Although in my side, I put the default value on my client, and no one else is accessing the XMLRPC interface but me.
With the changes done, save your file and re-upload it in the same path where you found it. Again, make sure to make backups.
Be wary of WordPress updates that affects this module. If that happens, you need to reapply this edit again!
Include class-IXR.php in your PHP-type editor. If you're using something else, well, I can't help you there. :(
Hope this helps some people.
When you post, WordPress will scan at the post for IMG tags.
If WP finds the image, it's loaded in it's media library. If there's an image in the body, it will automatically attached it to the post.
Basically you have to:
post the media (image) first
Grab its URL
include the URL of the image with a IMG tag in the body of your post.
then create the post
Here is some sample code. It needs error handling, and some more documentation.
$admin ="***";
$userid ="****";
$xmlrpc = 'http://localhost/web/blog/xmlrpc.php';
include '../blog/wp-includes/class-IXR.php';
$client = new IXR_Client($xmlrpc);
$author = "test";
$title = "Test Posting";
$categories = "chess,coolbeans";
$body = "This is only a test disregard </br>";
$tempImagesfolder = "tempImages";
$img = "1338494719chessBoard.jpg";
$attachImage = uploadImage($tempImagesfolder,$img);
$body .= "<img src='$attachImage' width='256' height='256' /></a>";
createPost($title,$body,$categories,$author);
/*
*/
function createPost($title,$body,$categories,$author){
global $username, $password,$client;
$authorID = findAuthor($author); //lookup id of author
/*$categories is a list seperated by ,*/
$cats = preg_split('/,/', $categories, -1, PREG_SPLIT_NO_EMPTY);
foreach ($cats as $key => $data){
createCategory($data,"","");
}
//$time = time();
//$time += 86400;
$data = array(
'title' => $title,
'description' => $body,
'dateCreated' => (new IXR_Date(time())),
//'dateCreated' => (new IXR_Date($time)), //publish in the future
'mt_allow_comments' => 0, // 1 to allow comments
'mt_allow_pings' => 0,// 1 to allow trackbacks
'categories' => $cats,
'wp_author_id' => $authorID //id of the author if set
);
$published = 0; // 0 - draft, 1 - published
$res = $client->query('metaWeblog.newPost', '', $username, $password, $data, $published);
}
/*
*/
function uploadImage($tempImagesfolder,$img){
global $username, $password,$client;
$filename = $tempImagesfolder ."/" . $img;
$fs = filesize($filename);
$file = fopen($filename, 'rb');
$filedata = fread($file, $fs);
fclose($file);
$data = array(
'name' => $img,
'type' => 'image/jpg',
'bits' => new IXR_Base64($filedata),
false //overwrite
);
$res = $client->query('wp.uploadFile',1,$username, $password,$data);
$returnInfo = $client->getResponse();
return $returnInfo['url']; //return the url of the posted Image
}
/*
*/
function findAuthor($author){
global $username, $password,$client;
$client->query('wp.getAuthors ', 0, $username, $password);
$authors = $client->getResponse();
foreach ($authors as $key => $data){
// echo $authors[$key]['user_login'] . $authors[$key]['user_id'] ."</br>";
if($authors[$key]['user_login'] == $author){
return $authors[$key]['user_id'];
}
}
return "not found";
}
/*
*/
function createCategory($catName,$catSlug,$catDescription){
global $username, $password,$client;
$res = $client->query('wp.newCategory', '', $username, $password,
array(
'name' => $catName,
'slug' => $catSlug,
'parent_id' => 0,
'description' => $catDescription
)
);
}
After calling the method metaWeblog.newMediaObject, we need to edit the image entry on the database to add a parent (the previously created post with metaWeblog.newPost).
If we try with metaWeblog.editPost, it throws an error 401, which indicates that
// Use wp.editPost to edit post types other than post and page.
if ( ! in_array( $postdata[ 'post_type' ], array( 'post', 'page' ) ) )
return new IXR_Error( 401, __( 'Invalid post type' ) );
The solution is to call wp.editPost, which takes the following arguments:
$blog_id = (int) $args[0];
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$content_struct = $args[4];
So, just after newMediaObject, we do:
$status = $rpc->query(
'metaWeblog.newMediaObject',
$postID,
WP_USERNAME,
WP_PASSWORD,
$data
);
$response = $rpc->getResponse();
if( isset($response['id']) ) {
// ATTACH IMAGE TO POST
$image['post_parent'] = $postID;
if( !$rpc->query('wp.editPost', '1', WP_USERNAME, WP_PASSWORD, $response['id'], $image)) {
die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
}
echo 'image: ' . $rpc->getResponse();
// SET FEATURED IMAGE
$updatePost['custom_fields'] = array( array( 'key' => '_thumbnail_id', 'value' => $response['id'] ) );
if( !$rpc->query( 'metaWeblog.editPost', $postID, WP_USERNAME, WP_PASSWORD, $updatePost, $publishBool ) ) {
die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
}
echo 'update: ' . $rpc->getResponse();
}
I've used the Incutio XML-RPC Library for PHP to test and the rest of the code is exactly as in the question.
Here's some sample code to attach an image from a path not supported by WordPress (wp-content)
<?php
function attach_wordpress_images($productpicture,$newid)
{
include('../../../../wp-load.php');
$upload_dir = wp_upload_dir();
$dirr = $upload_dir['path'].'/';
$filename = $dirr . $productpicture;
# print "the path is : $filename \n";
# print "Filnamn: $filename \n";
$uploads = wp_upload_dir(); // Array of key => value pairs
# echo $uploads['basedir'] . '<br />';
$productpicture = str_replace('/uploads','',$productpicture);
$localfile = $uploads['basedir'] .'/' .$productpicture;
# echo "Local path = $localfile \n";
if (!file_exists($filename))
{
echo "hittade inte $filename !";
die ("no image for flaska $id $newid !");
}
if (!copy($filename, $localfile))
{
wp_delete_post($newid);
echo "Failed to copy the file $filename to $localfile ";
die("Failed to copy the file $filename to $localfile ");
}
$wp_filetype = wp_check_filetype(basename($localfile), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($localfile)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $localfile, $newid );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $localfile );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
?>
I had to do this several months ago. It is possible but not only is it hacky and undocumented I had to dig through wordpress source to figure it out. What I wrote up way back then:
One thing that was absolutely un-documented was a method to attach an image to a post. After some digging I found attach_uploads() which is a function that wordpress calls every time a post is created or edited over xml-rpc. What it does is search through the list of un-attached media objects and see if the new/edited post contains a link to them. Since I was trying to attach images so that the theme’s gallery would use them I didn’t necessarily want to link to the images within the post, nor did I want to edit wordpress. So what I ended up doing was including the image url within an html comment. -- danieru.com
Like I said messy but I searched high and low for a better method and I'm reasonably sure that none exists.
As of Wordpress 3.5, newmediaobject now recognizes the hack semi-natively.
it is no longer necessary to hack class-wp-xmlrpc-server.php.
Instead, your xml-rpc client needs to send the post number to a variable called post_id. (Previously it was just the variable 'post')
Hope that helps someone out.

Categories