PHP Getting Random Gives Blank Results - php

This is part of a WordPress plugin script. I am trying to edit it to get my own custom title. The code below returns the text:
random_phrase
The 'post_title' => line does not get a random line from the quotes.txt file. Any idea on why this is not working ?
function random_phrase ()
{
$quotes = file ("quotes.txt");
$num = rand (0, intval (count ($quotes) / 3)) * 3;
echo $quotes[$num] . "<br>" . $quotes[$num + 1];
}
// and create a post
$wpvt_post = array(
'post_title' => random_phrase,
'post_content' => $post_content,
'post_author' => $item['item']['post_author'],
'post_status' => $item['item']['post_status'],
);

Try
'post_title' => random_phrase(),
It also shouldn't be echo but return.
And be warned that your random index generation will bug.

Related

Name keys within array from WordPress meta fields

i am trying to code a calendar script within wordpress and custom post types. works fine so far. I use several custom fields (ACF) to call my desired parameters (event title, start_date, end_date, etc.)
I call the results by get_posts().
but I have a problem with naming my keys within the array. after the foreach operation I can get the desired values e.g. event_title by typing $posts[0] or start_date by $posts['1'].
how can I achieve that I can name the keys so that I can use $posts[title] or $posts['start_date'] in my output?
I have tried to build a second array an use array_combine, but this fails.
<?php
$args = array( 'post_type' => 'cpt_kalender', 'post_status' => 'publish', 'numberposts' => '-1', 'meta_key' => 'cf_termin_start', 'orderby' => 'meta_value_num', 'order' => 'ASC' );
$posts = get_posts( $args );
$group_posts = array();
foreach ( $posts as $post ) : setup_postdata( $post );
/*
Hole die Termine der einzelnen Startdaten
- Schreibe das Datumsformat yyyymmdd in yyyy-mm-dd um
*/
$titel = get_the_title();
$termin_datum_start = get_field('cf_termin_start');
$termin_datum_start = new DateTime($termin_datum_start);
$termin_datum_ende = get_field('cf_termin_ende');
$termin_datum_ende = new DateTime($termin_datum_ende);
$termin_jahr = $termin_datum_start->format('Y');
$termin_monat = $termin_datum_start->format('F');
$termin_tag = $termin_datum_start->format('d');
$post_id = get_the_ID();
$termin_start_uhrzeit_stunde = get_field('cf_termin_start_uhrzeit_stunde');
$termin_start_uhrzeit_minute = get_field('cf_termin_start_uhrzeit_minute');
$termin_ende_uhrzeit_stunde = get_field('cf_termin_ende_uhrzeit_stunde');
$termin_ende_uhrzeit_minute = get_field('cf_termin_ende_uhrzeit_minute');
$termin_schulfrei = get_field('cf_termin_schulfrei');
$termin_intern = get_field('cf_termin_intern');
/*
Fülle das Array mit den Werten
*/
$group_posts[$termin_jahr][$termin_monat][] = array(
$titel,
$termin_datum_start,
$termin_datum_ende,
$post_id,
$termin_start_uhrzeit_stunde,
$termin_start_uhrzeit_minute,
$termin_ende_uhrzeit_stunde,
$termin_ende_uhrzeit_minute,
$termin_schulfrei,
$termin_intern
);
endforeach; ?>
Is there any way to tell the array listed above the desired key names in the same foreach operation?
i am thankful for every hint. thx a lot. I am just learning php and this drives me nuts. :(
The part where you are adding the values to the $group_posts array. You can add keys to each item.
$group_posts[$termin_jahr][$termin_monat][] = array(
'title' => $titel,
'termin_datum_start' => $termin_datum_start,
'termin_datum_ende' => $termin_datum_ende,
'post_id' => $post_id,
'termin_start_uhrzeit_stunde' => $termin_start_uhrzeit_stunde,
'termin_start_uhrzeit_minute' => $termin_start_uhrzeit_minute,
'termin_ende_uhrzeit_stunde' => $termin_ende_uhrzeit_stunde,
'termin_ende_uhrzeit_minute' => $termin_ende_uhrzeit_minute,
'termin_schulfrei' => $termin_schulfrei,
'termin_intern' => $termin_intern
);
Then you can access a value like $group_posts['termin_jahr']['termin_monat']['title']
Since you are adding each item with termin_jahr and termin_monat You will need to provide those first to access the correct item's title.
Alternatively you can just add those variables inside of the array and access it later like below:
$group_posts = array(
'title' => $titel,
'termin_datum_start' => $termin_datum_start,
'termin_datum_ende' => $termin_datum_ende,
'post_id' => $post_id,
'termin_start_uhrzeit_stunde' => $termin_start_uhrzeit_stunde,
'termin_start_uhrzeit_minute' => $termin_start_uhrzeit_minute,
'termin_ende_uhrzeit_stunde' => $termin_ende_uhrzeit_stunde,
'termin_ende_uhrzeit_minute' => $termin_ende_uhrzeit_minute,
'termin_schulfrei' => $termin_schulfrei,
'termin_intern' => $termin_intern,
'termin_jahr' => $termin_jahr,
'termin_monat' => $termin_monat,
);
You can do a foreach loop on the $group_posts array and then access each item like below:
foreach($group_posts as $group_post) {
// Outputs $titel variable which you added to array above
echo $group_post['title'];
}

Wordpress - Update post by meta information

I'm looking for a solution, where I can update posts by meta information and not by id.
I got my content from an external resource via jsonp. I save the content into the database.
The only way I have found is, to update a post by id - but I have no id. What I have, is an article ID from the other resource. I save this article id to every wp post as meta information.
So, is there any way, to update a post by it's meta information?
Ok,
here is some code and what I have done right now:
public function saveArticleInWpDatabase($json_data){
for ($i = 0; $i < count($json_data); $i++) {
$articleId = $json_data[$i]['articleId'];
$img = $json_data[$i]['img'];
$articleHeadline = $json_data[$i]['articleContent']['headline'];
$articleContent = $json_data[$i]['articleContent']['content'];
$termsInput = $json_data[$i]['articleContent']['terms'];
$terms = explode(',',$termsInput);
$creationDate = $json_data[$i]['articleCreationDate'];
$modifiedDate = $json_data[$i]['articleModifiedDate'];
//Check if post with article ID in postmeta exists
$existingId = $this->wpdb->get_var("SELECT post_id FROM ".$this->wpdb->postmeta." WHERE (meta_key = 'article_id' AND meta_value = '".$articleId."')");
//Posts doesn't exist
if ($existingId == null) {
$my_post = array(
'post_date' => $creationDate,
'post_modified' => $modifiedDate,
'post_title' => $articleHeadline,
'post_content' => $articleContent,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(0, $categoryId)
);
$last_id = wp_insert_post($my_post);
add_post_meta($last_id, 'article_id', $articleId, true);
wp_set_post_categories($last_id, array(0,$categoryId), true);
wp_set_post_terms( $last_id,$terms, 'post_tag', true );
//$this->_import_photo($last_id, $img);
}
//Post exists
else{
$my_post = array(
'ID' => $existingId,
'post_date' => $creationDate,
'post_modified' => $modifiedDate,
'post_title' => $articleHeadline,
'post_content' => $articleContent,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(0, $categoryId)
);
//Get last modified date and compare it with the new one
$lastUpdate = $this->wpdb->get_var("SELECT post_modified FROM " . $this->wpdb->posts . " WHERE ID = ".$existingId);
if(strcmp($lastUpdate, $modifiedDate) != 0){
var_dump("Update article with id: " . $existingId);
$last_id = wp_update_post($my_post);
}
else{
var_dump("Article: " . $existingId . " Nothing changed");
}
}
}
}
As you can see, I save the unique article number from the other CMS if the article doesn't exists.
If the article with the meta_key: article_id and the current value exist, I check if the modified date is the same or not. If not, I will update the posts.
I call this function via a unix cron job every minute. But I think, that this is not the best way (performance)(too many db requests?).
The other think is, that the post_modified value is always the same as post_date, but I got two different values in my json.
e.g.
"articleCreationDate": "2012-05-21 14:38:29", "articleModifiedDate": "2016-02-11 14:52:01"
But it only saved the articleCreationDate in both columns(post_date, post_modified).
So, did anyone has a better solution or idea? And did anyone know, why it doesn't save the modified date value from my json?
Cheers

Trying to wrap a php variable in single quotes

I am trying to wrap a variable in single quotes in PHP. This is my code:
$my_post = array(
'post_title' => $orderRequestCode.' - ' . $customerName,
'post_content' => $orderContent,
'post_status' => 'draft',
'post_author' => "'".$user_ID."'",
'post_type' => 'orders'
);
Currently var_dump($my_post) outputs:
array (size=5)
'post_title' => string '2014-06-13-15-13-52 - xxxxxxx' (length=35)
'post_content' => string 'Order Code: 2014-06-13-15-13-52
Customer Name: xxxxxxxxxxxx
Customer Email: xxx#xxxx.xx
Order Items:
Stock Code: Q20-50-6101 Quantity: 12
Comments:
' (length=162)
'post_status' => string 'draft' (length=5)
'post_author' => string ''1'' (length=3) <--------------- should be '1'
'post_type' => string 'orders' (length=6)
This line:
'post_author' => string ''1'' (length=3)
Needs to be:
'post_author' => string '1' (length=3)
The outside quotes in your var_dump aren't really part of the string, hence the length being 3, not 5. If you echo your string it will be '1'
No, you're telling PHP to create a 3-character string:
$x = 1;
$y = "'" . $x . "'";
$y = ' 1 '
1 2 3
Since it's a string, it will get wrapped by OTHER ' as well when you do your dump. If your ID is an integer, and you want it to be treated as a string, then you could something as simple as:
'post_author' => (string)$user_ID // cast to string
or
'post_author' => '' . $user_ID; // concatentate with empty string

Wordpress JSON API

Hey guys i have been so far in luck with the JSON API i love it but i encouter this little problem with it comes to making multiple query in the same custom function.
global $json_api;
$result = array();
$category = $json_api->introspector->get_categories();
foreach($category as $value){
if($value->id !== 1 && $value->id !== 69 && $value->id !== 68 && $value->id !== 66){
$search_args = array(
'cat' => $value->id,
'order' => 'DESC',
'post_status' => 'publish'
);
$search_limits = array(
10 => array(
'limit' => 4
),
5 => array(
'limit' => 2
),
3 => array(
'limit' => 3
)
);
$json_api->query->count = ($search_limits[$value->id]['limit'] === null ? 1 : $search_limits[$v$
$result['posts'][$value->id] = $json_api->introspector->get_posts($search_args,true);
}
}
return $result;
i hardcoded some of the values just to make it more straight foward, the issue is that when i make one query i get value ID lets say [10330][10218][10202] according to the category im looking for. Then i make this same query but with another category ID. But same result happens. So i was wondering is due to some sort of caching in the API if so can i turn it off for this query ?
Thanks in advance :D
Well what do you expect the issue is that i was not reseting my queries apparently.
wp_reset_query();
did the trick.

PhotosDuplicateTagInBatch error when uploading / tagging photos in Facebook!

I am writing an application that allows users to upload multiple photos at once to facebook and it will automatically tag themselves (no one else) in the photo when this happens.
If I run the script once, it works fine, if I try to upload and tag multiple photos then it complains with a PhotosDuplicateTagInBatch error and I can't find ANY information as to why this is happening!
Here is my code:
for ($i = 5; $i >= 1; $i--)
{
$img = GetImage($i);
$tag = array(
'tag_uid' => $facebook->getUser(),
'x' => rand (0,100),
'y' => rand (0,100)
);
$tags[] = json_encode($tag);
$args = array(
'message' => $i,
'image' => '#'.realpath($img),
'tags' => $tags,
);
$data = $facebook->api('/me/photos', 'post', $args);
}
}
If I output my arguments they come out as:
Code:
Array
(
[message] => 4
[image] => #imagepathhere
[tags] => Array
(
[0] => {"tag_uid":"100002493436028","x":13,"y":68}
[1] => {"tag_uid":"100002493436028","x":60,"y":57}
)
)
So essentially, from what I can tell, you cannot upload and tag multiple photos like this. What I had to do was upload the photo, then tag it separately and rinse and repeat

Categories