Filter and Hooks

PHP code to Import the POST from one website to another

Are you trying to import any post type contents from one website to another website ?

1. Create a folder in the root directory of the site i.e PARENT_SITE. I have created services folder in the root directory and created the php file named news.php

2. Include wp-load.php the files so that we could use all the WordPress available functions

3. Write a code that encode all the posts/contents related to ‘post_type’=>’post’. We can replace ‘post_type’ => ‘post’ by any other custom post types

include '../wp-load.php';
$args = ['post_type'=>'post',
    'posts_per_page' => -1,
    'post_status'=> 'publish'
];
$query = new WP_Query($args);
if(!($query->have_posts())){
    die("no post");
}

$jsonPost = [];
while ($query->have_posts() ) {
    $query->the_post();
        $postCategories = get_the_category($post->ID);
        $postTags = get_the_terms($post->ID,'post_tag');
        $attachedImage = get_the_post_thumbnail_url( $post->ID, 'full' );
        $imageUrl = !empty($attachedImage)?$attachedImage:'';
        $categories = [];
        // $postTerms = [];
        $communeTerms = [];
        // The Loop
        if(!empty($postTags)):
            $postTerms = saveTermInArray($postTags);
        endif;
        if(!empty($postCategories)):
            $categories = saveTermInArray($postCategories);
        endif;

        /*
	 * saves the post and related terms & categories in an array
	 */
        $jsonPost[]= [
            'post_title' => get_the_title(),
            'post_content'=> get_the_content(),
            'post_date'=> get_the_time('Y-m-d'),
            'post_cat' => $categories,
            'post_terms'=>$postTerms,
            'post_image_url'=>$imageUrl,
            'post_permalink'=> get_permalink($post->ID)
        ];
}

echo json_encode($jsonPost);
/*
 * function to save related terms in an array
 */
function saveTermInArray($tagArray) {
    $saveTerm =[];
    foreach ($tagArray as $postTag) {
        $saveTerm[] =[
            'slug'=> $postTag->slug,
            'name'=>$postTag->name,
            'term_id'=>$postTag->term_id,
            'parent_term_id'=> $postTag->parent
        ];

    };
    return $saveTerm;

}

We can check the encoded post contents in the Url : http://PARENT_SITE/services/news.php

4. Create a folder in the root directory of the site, I call it AS CHILD_SITE where we want to import the all the contents of posts from the PARENT_SITE. I have created app folder in the root directory of CHILD_SITE and created the php file named import-news.php inside the folder:

5.   I have created custom post type named  ‘imported-news’ and two meta fields , using acf to save the thumbnail  and permalink of imported posts

p.s. I   like to display the thumbnail of news directly from the source instead of saving it in my site and I  might need the source of the  news in the future

6. I have created main_site_url  field using ACF  in Options Page so that user can input the source url from where they can get the json encoded posts to be imported

7.  I have created Importer class that handles the import part.  Provided the post_type and source link of import in the Object of Importer Class and in return calling import method, it works like a charm . To parse the json encoded contents  I have used Guzzle

8. Before importing the posts, we shall delete existing posts and meta related to imported post_type

9. After deleting the posts and meta’s , we shall insert the imported post and categories. If the imported category doesn’t exist, we shall create it and assign the post to the created category.

require __DIR__.'/../wp-load.php';
require '/vendor/autoload.php';

class Importer
{
    protected $dbHandler;
    protected $importFromUrl ='';
    protected $postType = "";

/**
* Importer constructor.
* @param $importURl
* f
*/
    public function __construct($importFromUrl,$postType)
    {

        global $wpdb;
        $this->dbHandler = $wpdb;
        $this->postType = $postType;
        $this->importFromUrl = $importFromUrl;


        if(empty($importFromUrl)) :
            $mainSiteUrl = get_field('main_site_url','options');
            $this->importFromUrl = $mainSiteUrl.'services/news.php';
        endif;



    }
    /*
     * Delete all the existing posts and it's meta for the given post type
     *
     */

    public function deletePostsByType() {

        $newsPostID = get_posts([
            'fields' => 'ids',
            'posts_per_page' => -1,
            'post_type' => $this->postType

        ]);

        $post_IDS = [];
        foreach ($newsPostID as $cId) {
            $postID = (int) $cId;
            array_push($post_IDS, $postID);
        }
        $implodedPostID = implode(',',$post_IDS);


        $deleteFormPostQuery = "DELETE FROM ".$this->dbHandler->posts." WHERE post_type = '{$this->postType}';";
        $this->dbHandler->query($deleteFormPostQuery);
        $deleteQuery = "DELETE FROM " . $this->dbHandler->postmeta . " WHERE post_id IN (". $implodedPostID.")";
        $this->dbHandler->query($deleteQuery);

        /*
         * Delete Orphan Meta
         */
        $query = "DELETE pm
            FROM ".$this->dbHandler->postmeta." pm
            LEFT JOIN ".$this->dbHandler->posts." p ON pm.post_id = p.ID
            WHERE p.ID IS NULL
        ;";

        $this->dbHandler->query($query);
    }

    /*
     * Function to import posts
     */
    public function import() {

        $this->deletePostsByType();
        $importNewsUrl = $this->importFromUrl;
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $importNewsUrl);
        $items = json_decode($response->getBody());
        if(!empty($items)):
            $postCount = 0;
            foreach ($items as $item):
                $post = array(
                    'post_title' => $item->post_title,
                    'post_content'=>$item->post_content,
                    'post_date'=>$item->post_date,
                    'post_status'=>'publish',
                    'post_type'=>$this->postType,
                    'post_author' => 1,
                    'post_permalink'=>$item->post_permalink

                );
                $postID = wp_insert_post($post);

                if(!empty($item->post_image_url)):
                    update_field('news_featured_image', $item->post_image_url, $postID);
                endif;

                if(!empty($item->post_permalink)):
                    update_field('news_source', $item->post_permalink, $postID);
                endif;

                $termsArray = [];
                /*
                 * if post term is not empty check if the term exist in the database
                 * if exists, getTermsID() returns the id of the term
                 * if doesn't exist creates Term
                 */
                if(!empty($item->post_terms )):
                    foreach($item->post_terms as $postTag) {
                        $termID =  $this->getTermsID($postTag,'post_tag');
                        array_push($termsArray, $termID);
                    }
                endif;
                /*
                * if post category is not empty check if the category exist in the database
                * if exists, getTermsID() returns the id of the category
                * if doesn't exist creates category
                */
                if(!empty($item->post_cat )):
                    foreach($item->post_cat as $cat) {
                        $categoryID = $this->getTermsID($cat,'category');
                        array_push($termsArray, $categoryID);
                    }
                endif;



                /*
                 * function inserts all the terms related to post_tag, category, taxonomy in the database
                 */

                $this->insertRelatedTermsInDb ($termsArray,$postID);

 
                $postCount++;

            endforeach;

            echo $postCount. ' posts are imported !!';
        endif;


    }
    /*
     *  Returns term id of the inserted post
     */

    protected function getTermsID($termArray,$taxonomy) {
        $postTerm = term_exists( $termArray->slug, $taxonomy ); // array is returned if taxonomy is given
        if(empty($postTerm)) {
            $insertedTerm = wp_insert_term(
                $termArray->name, // the term
                $taxonomy, // the taxonomy
                array(
                    'slug' => $termArray->slug
                )
            );
            $termID = $insertedTerm['term_id'];
            update_term_meta($termID, 'id_main_site', $termArray->term_id);
            update_term_meta($termID, 'parent_id_main_site', $termArray->parent_term_id);

        }else {

            $termID = $postTerm['term_id'];
        }

        return $termID;
    }

    /*
     * Insert related terms associated with the post
     */
    protected function insertRelatedTermsInDb($termsArray,$postID) {

        // wp_defer_term_counting( true );
        $tax_fields = [];
        $tax_string = "INSERT INTO ".$this->dbHandler->term_relationships." (object_id, term_taxonomy_id, term_order) VALUES ";
        $termPlace_holders = [];

        foreach ($termsArray as $termID) {
            $term = (int)$termID;
            array_push($tax_fields, $postID, $term, '0');
            $termPlace_holders[] = "('%d', '%d', '%d')";
        }

        $tax_string .= implode(', ', $termPlace_holders);
        $this->dbHandler->query($this->dbHandler->prepare("$tax_string ", $tax_fields));
    }

}
$importNews = new Importer('','imported-news');
$importNews->import();

10. Last but not the list,  run the import file in the CHILD_SITE to import the news  : http://CHILD_SITE/app/import-news.php

P.S. The process is long and I haven’t displayed any screen-shots so that you could try it on your own; provided the full code 😛

Views: 86

Standard