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
Related
I have 3 tables and I'm working with wordpress too: wp7s_g_bookings, wp7s_g_tests and wp7s_g_clients. This is a study project, not to sell.
I want to be able to save 1 booking with X clients and Y tests.
I read about LAST_INSERT_ID() but I don't think it will work in this case and I'm lost.
Possible scenarios:
You are a partner, then the data is beeing pulled, so we have the ID because it exist already;
In this case we are adding other users data inside repeatable fields like name="client_birth[]" ... // client_vat only show/exist if the partner don't exist.
You are a normal client, in this case you fill the same client data plus client_vat (so I'm sure when adding into database that only the guy that have client_vat is the booking_client)
if (!empty($_POST)) {
$wpdb->query('START TRANSACTION');
//All this fields are repeatable inputs, except client_vat that can only be the 1st record. I think it's missing a foreach
$default = array(
'client_name' => $_POST['client_name'],
'client_birth' => $_POST['client_birth'],
'client_sns' => $_POST['client_sns'],
'client_vat' => $_POST['client_vat'],
'client_city' => $_POST['client_city'],
'client_email' => $_POST['client_email'],
'client_phone' => $_POST['client_phone']
);
$item = shortcode_atts( $default, $_REQUEST );
$addClients = $wpdb->insert( 'wp7s_g_clients', $item );
$default = array(
'test_client' => ???, //ID of previous client that have client_vat filled [0]
);
$item = shortcode_atts( $default, $_REQUEST );
$addTests = $wpdb->insert( 'wp7s_g_tests', $item );
$collectDate = date('Y-m-d H:i:s', strtotime($_POST['booking_collect_date']));
$default = array(
'booking_status' => 1,
'booking_partner' => $_POST['booking_partner'], //ID of the partner, if not empty
'booking_client' => ???, //If partner don't exist -> ID of client that have client_vat filled
'booking_type' => $_POST['booking_type'],
'booking_clients' => ???, //Array of all IDs previously added in wp7s_g_clients table
'booking_city' => $_POST['booking_city'],
'booking_address' => $_POST['booking_address'],
'booking_collect_date' => $collectDate,
'booking_payment' => $_POST['booking_payment'],
'booking_amount' => $_POST['booking_amount'],
'booking_obs' => nl2br($_POST['booking_obs']),
);
$item = shortcode_atts( $default, $_REQUEST );
$addBookings = $wpdb->insert( 'wp7s_g_bookings', $item );
if($addClients && $addTests && $addBookings) {
$wpdb->query('COMMIT');
$msg = "Success";
wp_redirect( esc_url( get_page_link( 6 ) ) );
exit;
}
else {
$wpdb->query('ROLLBACK');
$msg = "Error";
}
}
My issues are adding this properly into database the repeatable fields and using a previous created ID(s).
I tried to explain everything and comment so it's better to understand.
After you perform a query with $wpdb you can access the $wpdb->insert_id to get the last inserted id. You can find more details on the documentation page of wpdb
If you need more ids because u have more $wpdb->insert all you need to do is store $wpdb->insert_id after each insert, like:
...
$item = shortcode_atts( $default, $_REQUEST );
$addClients = $wpdb->insert( 'wp7s_g_clients', $item );
$clientId = $wpdb->insert_id;
....
$default = array(
'test_client' => ???, //ID of previous client that have client_vat filled [0]
);
$item = shortcode_atts( $default, $_REQUEST );
$addTests = $wpdb->insert( 'wp7s_g_tests', $item );
$testId = $wpdb->insert_id;
...
rest of your code
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'];
}
I can't seem to find any information online, but what I am trying to do is to get an array of all users based on a value in a serialised meta_key, for example:
$get_users = get_users(array(
'meta_key' => 'value_one_of_array'
));
Then in the db, the meta_value columns would have two stored values such as:
meta_key
value_one_of_array , value_two_of_array
Is this possible?
May be it's help you.
$args = array();
if($values_of_array){
foreach($values_of_array as $key=>$val){
$args['meta_query'][] = array(
'key' => '#your_meta_key',
'value' => $val
);
}
$get_users = get_users($args);
}
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.
Hello All,
I know how to fetch record with the help of podscms,
But I would like to update the record fetched by podscms.
like
$somePod = pods('somepod')->update($my_array);
Anybody have some suggestion,
This is available in pods()->save() - http://pods.io/docs/save/
<?php
// Get the book item with an ID of 5
$pod = pods( 'book', 5 );
// Set the author (a user relationship field)
// to a user with an ID of 2
$pod->save( 'author', 2 );
// Set a group of fields to specific values
$data = array(
'name' => 'New book name',
'author' => 2,
'description' => 'Awesome book, read worthy!'
);
// Save the data as set above
$pod->save( $data );
// Or the shorthand
$id = pods( 'yourpod', $id )->save( $data );
Also available is add() - http://pods.io/docs/add/