Here is the code I am using. It creates duplicate post every time I refresh. Also, how can I add custom field to my post?
My array looks like this:
[{
"featured":"",
"exclusive":"",
"promo_id":"XXX",
"offer_id":"1",
"title" : "Super Cars"
}]
My php code:
<?php
$json = "url";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 10; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->title);
$id = $mydecode[$i]->offer_id;
$link = $mydecode[$i]->link;
if( $id === "x" ) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
$post_id = wp_insert_post($new_post);
}
}
?>
The code successfully inserts posts but duplicate every time I refresh.
If anyone can contribute a bit, it would be great!
Update your code to following,
<?php
$json = "http://tools.vcommission.com/api/coupons.php?apikey=xxxxxxxxxx";
$response = file_get_contents($json);
$mydecode = json_decode($response);
for ($i = 0; $i < 15; $i++) {
$title = str_replace("&", "&", $mydecode[$i]->coupon_title);
$description = str_replace("&", "&", $mydecode[$i]->coupon_description);
$store_name = $mydecode[$i]->offer_name;
$coupon_type = $mydecode[$i]->coupon_type;
$coupon_code = $mydecode[$i]->coupon_code;
$link = $mydecode[$i]->link;
$expiry_date = $mydecode[$i]->coupon_expiry;
if( $coupon_type === "Coupon" ) {
// Check if already exists
$get_page = get_page_by_title( $title );
if ($get_page == NULL){
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'coupon'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}
?>
I hope this helps.
Related
I used the below snippet to display a product view counter on the shop page based on the ip address and it worked fine.
add_action('wp', 'product_view_counter');
function product_view_counter() {
global $post;
$userip = $_SERVER['REMOTE_ADDR'];
if ( is_product() ){
$meta = get_post_meta( $post->ID, '_total_views_count', TRUE );
$meta = (!$meta) ? array() : explode( ',', $meta );
$meta = array_filter( array_unique( $meta ) );
if( ! in_array( $userip, $meta ) ) {
array_push( $meta, $userip );
update_post_meta( $post->ID, '_total_views_count', implode(',', $meta) );
}
}
}
Show on Shop page,
add_filter( 'woocommerce_loop_add_to_cart_link','show_product_view_counter_on_product_page',5);
function show_product_view_counter_on_product_page() {
global $product;
$id = $product->id;
$meta = get_post_meta( $id, '_total_views_count', true);
if(!$meta) {
$count = 0;
} else {
$count = count(explode(',',$meta));
}
echo '<div class="custom-visitor-count"><i class="fa fa-eye"></i><span class="counter-value">'.$count.' Views</span></div>';
}
The new idea is i want to display which 5 attributes or product categories have the most views on another page.
What I've done so far:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
);
$get_data = get_posts($args);
foreach ($get_data as $gd){
$product = wc_get_product($gd);
$color = $product->get_attribute('pa_color');
$args_color = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'pa_color',
'field' => 'slug',
'terms' => $color,
)),
'fields' => 'ids',
);
$att_color = get_posts($args_color);
$att_color_sum = 0;
foreach($att_color as $ac){
$color = $product->get_attribute('pa_color');
$count_total_color = count($att_color);
$productid_color = $product->get_id();
$meta_color = get_post_meta( $productid_color, '_total_views_count', true);
$count_meta = count(explode(',',$meta_color));
$att_color_sum += $count_meta;
$display = $color." ".$att_color_sum;
}
}
echo "<p> Top 3 color attribute views : ".$display."</p>";
Output it gives a view like this :
Top 3 color attribute views : Blue 15
What i want is like this :
Top 3 color attribute views :
Green : 57
Red : 42
Grey : 24
Obviously, I was lost.
Anyone, please guide me so that I am on the right track.
Sincerely
I created plugin for get post title via API on submit. I used simple api request for getting data after via wp_insert_post() function add to DB. But i want check every time on submit to exists title. If there is a new post title then add to the database if not then it will report that 'There are no new posts'
plugin.php
if(isset($_POST['enable'])) {
$url='api/url';
$result = file_get_contents($url);
$resultData = json_decode($result);
foreach ($resultData as $job) {
$post_exists = get_page_by_title( $job->JobTitle, OBJECT, 'post');
if ( post_exists) {
$data = array (
'post_type' => 'post',
'post_title' => $job->JobTitle,
'post_status' => 'publish',
'post_author' => $user_ID
);
$post_id = wp_insert_post( $data );
}
}
echo "Done!";
}
Try this code.
if( isset( $_POST['enable'] ) ) {
$url = 'api/url';
$result = file_get_contents( $url );
$resultData = json_decode( $result );
foreach ($resultData as $job) {
$post_title = sanitize_title( $job->JobTitle );
$post_id = post_exists( $post_title );
if( !$post_id ){
$data = array(
'post_type' => 'post',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user_ID,
);
$post_id = wp_insert_post( $data );
}else{
//post title exist
}
}
}
You should try this,
This code will return an array of all posts that match the title.
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title = "'.$post_title.'" AND post_status="publish"');
$post_exists = $wpdb->get_results( $query );
I am using a json feed to import new posts. This works as expected, but I am not able to prevent importing duplicated posts. When I run the script twice it also imports the posts twice.
How can I check the wordpress database to prevent importing the same posts.
require_once("wp-load.php");
$url = 'https://somejsonfeed.com'; // path to the JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$flights = json_decode($data, true); // decode the JSON feed
foreach ($flights['response'] as $item) {
$title = $item['flight']['iata_number'];
// Check if already exists
if ( get_page_by_title( $title ) == null ) {
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'post'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
What works well for me is post_exists($title). Returns the post ID, so in your code, I would use
$current_post_id = post_exists($title);
if( 0 === $current_post_id) {
`enter code here`add_post_meta( $post_id, 'meta_key', 'meta_value' );
}
One thing I notice is that you have:
'meta_key', 'meta_value', so of course, I copied that part, but you would need to replace whatever meta_key and meta_value.
I hope this helps.
Bruce
Solved by using the code below
require wp-load.php to use built-in WordPress functions
require_once("wp-load.php");
$url = 'https://somejsonfeed.com'; // path to the JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$flights = json_decode($data, true); // decode the JSON feed
foreach ($flights['response'] as $item) {
$title = $item['flight']['iata_number'];
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
// change custom-post-name in post type
if ( get_page_by_title( $title, OBJECT, 'custom-post-name' ) == null ) {
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => $title,
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'post'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $post_id, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
// Uncomment to check if meta key is added
// $get_meta_value = get_post_meta( $get_page->ID, 'meta_key', true );
// echo "<pre>";
// print_r($get_meta_value);
}
I am trying to merge the following arrays.
I want this result:
foreach( $datas as $data ) {
$my_post = array(
'post_title' => $title['title_value'],
'post_status' => 'pending',
'post_type' => $type['type_value'],
'post_author' => $author['author_value'],
);
wp_insert_post( $my_post );
}
My data:
$title = title1,title2,,title4,title5 // 5 datas separated with coma
$type = type1,type2,type3,type4,, // 5 datas separated with coma
$author = ,author2,author3,author4,author5 // 5 datas separated with coma
What I have done:
$datas = array(
'title' => explode( ",", $title ),
'type' => explode( ",", $type ),
'author' => explode( ",", $author ),
);
foreach( $datas as $data ) {
// foreach( $data as $d ) {
// }
}
Does anybody know how to do this?
Hope you can understand the question. Thank you in advance.
If your all data(title,type and author) have same data count you can use this way
$title_array = explode(',', $title);
$type_array = explode(',', $type);
$author_array = explode(',', $author);
if (count($title_array) > 0)
{
foreach ($title_array as $title_index => $title_value)
{
$my_post = array(
'post_title' => $title_value,
'post_status' => 'pending',
'post_type' => $type_array[$title_index],
'post_author' => $author_array[$title_index],
);
wp_insert_post($my_post);
}
}
I have this query to insert a new post:
$new_post_args = array(
'post_title' => empty($esc_title = wp_filter_nohtml_kses(wp_trim_words($_POST['text'], 10))) ? 'No Title' : $esc_title,
'post_content' => esc_textarea($_POST['text']),
'post_name' => sanitize_title($_POST['text']),
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_category' => array($_POST['category']),
'comment_status' => $_POST['comments']
);
$new_post_args['meta_input']['_thumbnail_id'] = $_POST['images'][0];
if (count($_POST['images']) > 1) {
unset($_POST['images'][0]);
$new_post_args['meta_input']['gallery_images'] = implode(",", $_POST['images']);
$new_post_args['meta_input']['slider_mode'] = 'horizontal';
$new_post_args['meta_input']['slider_auto'] = 'on';
$new_post_args['meta_input']['slider_pause'] = '3000';
$new_post_args['tax_input'] = array('post_format' => 'gallery');
} else {
if ($_POST['do'] == 'update-post') {
$new_post_args['meta_input']['gallery_images'] = '';
$new_post_args['meta_input']['slider_mode'] = '';
$new_post_args['meta_input']['slider_auto'] = '';
$new_post_args['meta_input']['slider_pause'] = '';
$new_post_args['tax_input'] = array('post_format' => 0);
}
}
if ($_POST['do'] == 'update-post') {
$new_post_args['ID'] = $_POST['id'];
$new_post_id = wp_update_post($new_post_args);
} elseif ($_POST['do'] == 'share-post') {
$new_post_id = wp_insert_post($new_post_args);
}
For posting action, only if the gallery images > 1 then the gallery meta args will be added, but on update-post action I need to delete the args, not to add them empty '' , I don't want to delete_post_meta after the post is published, I'm looking for a way to hook all meta values of the post and do not add them if they are empty, if this is possible I appreciate sharing the code.
Thanks.