Dataobject in Silverstripe: Getting data from a Wordpress database - silverstripe

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

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 %>

Related

Cron Job In Custom Plugin Not Working In Wordpress

I have added this cronjob in my WordPress custom plugin but when I run the function manually it is working but through cronjob, it is not working. Here is my code! All the plugin files are loaded correctly not showing any error.
Can anybody help me to sort this out! I have tried a lot but still, it is not working.
<?php
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
// Getting all used cars with all data
function generate_used_car_feed(){
try{
// for opening the csv file
$file = fopen('all-cars-feed.csv', 'r');
fwrite($file, '');
$loop = new WP_Query($args);
chmod('all-cars-feed.csv', 0777);
// for creating array from csv file
$file="all-cars-feed.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json_csv_arr = json_encode($array);
$my_array_csv = json_decode($json_csv_arr, true);
// for getting used car list from databse, only take publish used car
global $wpdb;
$query = "SELECT wp_postmeta.post_id, wp_postmeta.meta_value FROM wp_postmeta
INNER JOIN wp_posts ON wp_posts.id = wp_postmeta.post_id WHERE meta_key = 'car_registration_number'
AND post_status = 'publish'";
$result = $wpdb->get_results($query);
$json_reg_num = json_encode($result);
$my_array = json_decode($json_reg_num, true);
print_r($my_array);
foreach ($my_array as $value) {
$car_reg_array = $value['meta_value'];
$Post_id= $value['post_id'];
$isTrue=true;
$ch = fopen("all-cars-feed.csv", "r");
while($row = fgetcsv($ch)) {
if (in_array($car_reg_array, $row)) {
echo 'found</hr>';
$isTrue=false;
}
}
if($isTrue)
{
$wpdb->query(
'UPDATE '.$wpdb->prefix.'posts SET post_status = "trash"
WHERE ID = "'.$Post_id.'"');
}
}
//fclose($file);
}
catch(\Exception $e)
{
$txt = 'Message: ' . $e->getMessage();
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($fileLoger, $txt);
fclose($fileLoger);
}
}
I wonder if this 5mins interval really exists in your setup. Try adding this code to make sure this actually exists (if it does already, it won't break stuff):
function add_custom_cron_schedules($schedules){
if (!isset($schedules["5mins"])) {
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Every 5 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','add_custom_cron_schedules');
If you want to retrieve currently available schedules, you can also use wp_get_schedules() and check out if a certain key (like '5mins') exists.

Wordpress XML-RPC post success but don't work with long body

I use code below to post via XML-RPC, it does success. But when I send a long string $bodypost, my post doesn't have body content. I test it with html code, it's working, then I remove all space, my $bodypost just have 1 line with about 4000 words, it's not working.
How can I fix it?
<?php
function send_post($titlepost, $bodypost, $categorypost, $keywordspost )
{
require_once("IXR_Library.php.inc");
$encoding='UTF-8';
$client->debug = false; //Set it to false in Production Environment
$title= $titlepost; // $title variable will insert your blog title
$body= $bodypost; // $body will insert your blog content (article content)
$category=$categorypost; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords=$keywordspost;
$customfields=array('key'=>'Author-bio', 'value'=>'Autor Bio Here'); // Insert your custom values like this in Key, Value format
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category),
'custom_fields' => array($customfields)
);
// Create the client object
$client = new IXR_Client('http://www.domain.com/xmlrpc.php');
$username = "abc";
$password = "abc";
$params = array(0,$username,$password,$content,true); // Last parameter is 'true' which means post immideately, to save as draft set it as 'false'
// Run a query for PHP
if (!$client->query('metaWeblog.newPost', $params)) {
die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
}
else
echo "Article Posted Successfully";
}
?>
I found how to fix it. This code does not work if my body code is give by source code of default Wordpress editor, but if I change it to CkEditor it's working!

Drupal - 2 seperate feeds updating the same set of nodes (feeds module)

I'm using the feeds module to pull in a set of publications into a Drupal content type. They are set to run at regular intervals using cron. I have two separate feeds, which should work as follows:
Feed 1 (pure_feed) - pulls in the bulk of the fields
Feed 2 (harvard_format) - accesses a separate url source and updates one field on the content type.
The problem I have is that feed 2 always creates a new set of nodes rather than updating the existing nodes (that were created using feed 1). I have used the debug options at /import and can see that the GUIDs for feed 2 match the GUIDs for feed 1, but it still creates 2 sets of nodes rather than updating the 1 set of nodes.
Here is an excerpt from the feeds_items database table:
As you can see they both have the same GUID but they are mapped to separate nodes. Is there any way to have the second feed map to the same nodes as the first feed?
I knocked something together that allows my second feed to update the nodes from my first feed. Not sure if this is the right way of doing things but it works. Here's what I did in case it helps someone else in future:
Created a custom processor that extends FeedsNodeProcessor
Copied across all of FeedsNodeProcessor's functions to the new class.
Overrided the existingEntityId function as follows (harvard_format is my secondary feed and pure_feed is my primary feed):
protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {
if($source->id == 'harvard_format') {
$query = db_select('feeds_item')
->fields('feeds_item', array('entity_id'))
->condition('feed_nid', $source->feed_nid)
->condition('entity_type', $this->entityType())
->condition('id', 'pure_feed');
// Iterate through all unique targets and test whether they do already
// exist in the database.
foreach ($this->uniqueTargets($source, $result) as $target => $value) {
switch ($target) {
case 'url':
$entity_id = $query->condition('url', $value)->execute()->fetchField();
break;
case 'guid':
$entity_id = $query->condition('guid', $value)->execute()->fetchField();
break;
}
if (isset($entity_id)) {
// Return with the content id found.
return $entity_id;
}
}
return 0;
}
elseif ($nid = parent::existingEntityId($source, $result)) {
return $nid;
} else {
// Iterate through all unique targets and test whether they do already
// exist in the database.
foreach ($this->uniqueTargets($source, $result) as $target => $value) {
switch ($target) {
case 'nid':
$nid = db_query("SELECT nid FROM {node} WHERE nid = :nid", array(':nid' => $value))->fetchField();
break;
case 'title':
$nid = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(':title' => $value, ':type' => $this->config['content_type']))->fetchField();
break;
case 'feeds_source':
if ($id = feeds_get_importer_id($this->config['content_type'])) {
$nid = db_query("SELECT fs.feed_nid FROM {node} n JOIN {feeds_source} fs ON n.nid = fs.feed_nid WHERE fs.id = :id AND fs.source = :source", array(':id' => $id, ':source' => $value))->fetchField();
}
break;
}
if ($nid) {
// Return with the first nid found.
return $nid;
}
}
return 0;
}
}
Copied across the the Process and newItemInfo functions from FeedsProcessor.
Overrided newItemInfo as follows:
protected function newItemInfo($entity, $feed_nid, $hash = '') {
$entity->feeds_item = new stdClass();
$entity->feeds_item->entity_id = 0;
$entity->feeds_item->entity_type = $this->entityType();
// Specify the feed id, otherwise pure_feed's entries in the feeds_item table will be changed to harvard_format
$entity->feeds_item->id = ($this->id == "harvard_format") ? "pure_feed" : $this->id;
$entity->feeds_item->feed_nid = $feed_nid;
$entity->feeds_item->imported = REQUEST_TIME;
$entity->feeds_item->hash = $hash;
$entity->feeds_item->url = '';
$entity->feeds_item->guid = '';
}

wordpress contact form 7 unique id

i am currently using contact form 7 for wordpress. i would like a unique id for every form filled in and sent.
i have had a look around the internet but cant find anything, although i did find the following:
http://contactform7.com/special-mail-tags/
would there be any easy way to make my own function to do something similar to the above tags? i would need it to be a function to go into my themes function file, so that plugin updates wont affect it.
Cheers Dan
[_serial_number] field is an auto-incremented form submission ID. You just have to have Flamingo plugin installed as well. See http://contactform7.com/special-mail-tags/
(It's the same link as in the question, I guess the field wasn't there when the question was asked).
To generate ID for the Contactform7 you need to hook the 'wpcf7_posted_data'.
However, to generate incremental ID you need to save the forms in database so you can retrieve which ID should be next on next Form submit. For this you will need CFDB plugin (https://cfdbplugin.com/).
If you dont want to put the code inside theme functions.php file, you can use this plugin instead: https://wordpress.org/plugins/add-actions-and-filters/
Example code:
function pk_generate_ID($formName, $fieldName) {
//Retrieve highest ID from all records for given form stored by CFDB, increment by 1 and return.
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$start = '001';
$exp = new CFDBFormIterator();
$atts = array();
$atts['show'] = $fieldName;
$atts['filter'] = "$fieldName>=$start&&$fieldName<999999999999"; //is_numeric() is not permitted by default for CFDB filter
$atts['limit'] = '1';
$atts['orderby'] = "$fieldName DESC";
$atts['unbuffered'] = 'true';
$exp->export($formName, $atts);
$found = $start;
while ($row = $exp->nextRow()) {
$row2 = $row[$fieldName];
$row2 += 1;
$found = max($found,$row2);
}
return $found;
}
function pk_modify_data( $posted_data){
$formName = 'Form1'; // change this to your form's name
$fieldName = 'ID-1'; // change this to your field ID name
//Get title of the form from private property.
$cf_sub = (array) WPCF7_Submission::get_instance();
$cf = (array) $cf_sub["\0WPCF7_Submission\0contact_form"];
$title = (string) $cf["\0WPCF7_ContactForm\0title"];
if ( $posted_data && $title == $formName) ) { //formName match
$posted_data[$fieldName] = pk_generate_ID($formName, $fieldName);
}
return $posted_data;
}
add_filter('wpcf7_posted_data', 'pk_modify_data');

How to get drupal custom profile values?

There is a checkbox added in user profile form, subscribe to daily newsletter. I want to get list of users who have subscribed (checkbox ON) and send them daily newsletter. How can I do this in drupal-6. (1) to get list of all subscribed users (2) Send them Email.
If you can explain at code level, I 'll really appreciate that.
If your profile field is profile_newsletter, your :
<?php
function mymodule_get_subscribers() {
$query = 'select * from {profile_fields} where `name`="%s";';
$result = db_query($query,'profile_newsletter');
$field = db_fetch_object($result);
$user_query = 'select * from {profile_values} where `fid`=%d and `value`=1;';
$result = db_query($user_query,$field->fid);
$subscribers = array();
while($subscriber = db_fetch_object($result)) {
$subscribers[] = $subscriber->uid;
}
return $subscribers; // Your array of subscriber user IDs
}
?>
This code was quick, is untested and should probably contain a few sanity-checks. But it should work.
For the sending of newsletters and such I'd recommend using a pre-rolled module. I haven't tried any for Drupal, but Simplenews seems to do the trick. http://drupal.org/project/simplenews
If nothing else it probably contains a good sending-function. Otherwise just use PHP mail()-function.
function your_custom_function ($user_id, "Field you want to get") {
$result = db_query("SELECT t2.value FROM profile_fields t1, profile_values t2 where
t1.title='Field you want to get' and t2.uid=".$user_id." and t1.fid=t2.fid");
$field = db_fetch_object($result);
$profile_type =$field->value;
return $profile_type;
}

Resources