Check if title exists in wordpress database before import - php

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);
}

Related

How to auto update an acf field based on the condition?

I have two custom post types with acf fields.
Custom Post_A, which has 2 fields - title / submitted
Custom Post_B, which has 2 fields - title / percent
Both Post_A and B have the same title (which is the logged in user's name) and they already exist.
When a field ‘submitted’ has the value ‘done’ in Post_A, I need to automatically update a ‘percent’ field with a value ‘50’ in Post_B.
I tried the following code but it doesn't update ‘50’ to Post_B.
Would you please correct my code?
$posts = get_posts(array(
'author' => get_current_user_id(),
'posts_per_page' => -1,
'post_type' => 'post_a',
'meta_key' => 'submitted',
'meta_value' => 'done'
));
$the_query = new WP_Query( $posts );
$the_count = count($the_query);
if($the_count>0) {
foreach ($the_query as $is_done){
$my_post = array();
$my_post['post_type'] = 'post_b';
$my_post['post_title'] = the_title();
// Update the post into the database
$field_key = "field_606cb546456343";
$value = "50";
update_field( $field_key, $value);
}
}
Thank you.
You can use save_post_{$post->post_type} action hook that will trigger on specific post type. check the below code.
function update_post_b( $post_id, $post, $update ){
$post_a_title = get_the_title( $post_id );
$posts = array(
'author' => get_current_user_id(),
'posts_per_page' => -1,
'post_type' => 'post_b'
);
$post_b = new WP_Query( $posts );
if( $post_b->have_posts() ){ while ( $post_b->have_posts() ) { $post_b->the_post();
if( $post_a_title == get_the_title() ){
update_post_meta( get_the_ID(), 'percent', 50 );
}
} }
}
add_action( 'save_post_post_a', 'update_post_b', 10, 3 );
USEFUL LINKS
save_post_{$post->post_type}

Wordpress modifies content when importing post

I use the PHP script below to import new posts into Wordpress.
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' );
}
if ( get_page_by_title( $title, OBJECT, 'custom-post-name' ) == null ) {
// Insert post
$new_post = array(
'post_title' => $title,
'post_content' => '[jsoncontentimporterpro url=yes url=https://someapiwithakey123abc&iata_code=<cf_wpcf-arrival-airport\> value&type=something]',
'post_status' => 'draft',
'post_author' => 1,
'post_type' => 'custom-post-name'
);
// Insert post
$post_id = wp_insert_post($new_post);
// Insert post meta if available
add_post_meta( $post_id, 'meta_key', 'meta_value' );
}
}else{
// Update meta value
update_post_meta($get_page->ID, 'my_key', 'meta_value');
}
But after importing the content it removes <cf_wpcf-arrival-airport\> and shows the content below in the Wordpress WYSIWYG editor.
[jsoncontentimporterpro url=yes url=https://someapiwithakey123abc&iata_code= value&type=something]
Any idea how I can fix this?
No perfect solution, but a work around.
Used the https://nl.wordpress.org/plugins/insert-html-snippet/ plugin and imported the post-content value into a snippet. Then I used the snippet in the file above.

How to create Wordpress posts from external json file?

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.

Multiple uri to same post in Wordpress

I wanted to make two uri to point same post in Wordpress but without redirect,
mysite.co.uk/awesome-post
mysite.co.uk/?p=12
I want those two uri to be pointed to same post but when you reach the page uri shouldn't change.
The only solution that i know is duplicate your post and get second link from it and hide the duplicate from loop and if you wish back end.
for that you have to use save_post action and plugin/theme activation hook for duplicate posts that have already published (this can be init hook but with caution you need to do this only one time).
first you have to loop through all posts and make duplicate
add_action('switch_theme', 'your_prefix_setup_options');
function your_prefix_setup_options () {
// WP_Query arguments
$args = array (
'post_type' => array( 'post' )
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// duplicate post like this
your_prefix_post_duplicate( get_the_ID(), get_the_title(), get_the_content(), get_post_thumbnail_id() );
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
}
function your_prefix_post_duplicate($post_id, $title, $content, $attachment){
$post_id = $post_id;
$post_name = $title;
$content = $content;
$attachment = $attachment;
$slug = str_replace( " ", "-", $post_name );
$slug = strtolower($slug);
$post_data = array(
'post_content' => $content,
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 0,
'post_name' => $slug,
'post_title' => $post_name,
'post_status' => 'published',
'post_type' => 'post'
);
$prefix = 'your_prefix__';
//create your duplicate post
$duplicate_post_id = wp_insert_post( $post_data );
set_post_thumbnail( $duplicate_post_id, $attachment );
add_post_meta( $duplicate_post_id, $prefix . 'duplicate', TRUE );
//get duplicate link
$perma_link = get_permalink ( $duplicate_post_id );
//set this link to your post as meta
add_post_meta( $post_id, $prefix . 'duplicate_url', $perma_link );
}
// now you can get second uri for fb like/share
$second_link = get_post_meta(get_post_ID(),$prefix . 'duplicate_url', true);
//and you can use the meta and ignore duplicate post from showing on loop
// or in advance you can use pre get post to hidethese duplicates from front end & back end permanently
get_post_meta(get_post_ID(),$prefix . 'duplicate', true);

Wordpress - Frontend form Post title automatic generation using authors name

I'm using Advanced custom fields and custom post types ui, I need to generate a post name with the author's name in it, however this just prints "Solicitud", it seem like my variable $autor gets no value, is there any way I can fix this?
function my_pre_save_post( $post_id ) {
$post2 = get_post($post_id);
$autor=$post2->author;
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud' . $autor,
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
And, here is the code I use to create the form, I'm using acf_form:
$current_inv = $_GET['invid'];
/**
* Template Name: Solicit
*/
acf_form_head();
get_header();
?>
<div id="primary">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php acf_form(array(
'post_id' => 'new',
'field_groups' => array( 243 ),
'submit_value' => 'Crear el ticket'
)); ?>
<?php endwhile; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
Try using 'post_author' instead of 'author'. And also make sure that WP_Debug is set to TRUE while you're developing.
Here's a long version
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud',
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// Once we save, retrieve the original post so we can take the post_author
$post2 = get_post($post_id);
// Use post_author
$autor = $post2->post_author;
// Update the post with the new title
wp_update_post(array('ID' => $post_id, $post2->post_title . $autor));
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
Slightly shorter version which uses the current logged in user's username.
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
$current_user = wp_get_current_user();
$author = $current_user->user_login; // OR [user_firstname, user_lastname, display_name]
// Create a new post
$post = array(
'post_status' => 'publish',
'post_title' => 'Solicitud' . $author,
'post_type' => 'solicit',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
References:
http://codex.wordpress.org/Class_Reference/WP_Post
http://www.advancedcustomfields.com/resources/tutorials/using-acf_form-to-create-a-new-post/
http://codex.wordpress.org/Function_Reference/wp_get_current_user

Categories