plugins – Import Recent Posts Only and Ignore old ones if exist

Question

I’m using MailChimp Campaigns Plugin where it imports all Mailchimp campaigns as a custom post type on the website. The app works perfectly however I’m modifying the process to import recent posts only to avoid any post modification to be overwritten.

The import() function works as following:

/**
 * Actually do the import of Mailchimp campaigns.
 */
public function import() {
  if ($this->is_error) {
    return;
  }

  $x = 0;
  $campaigns = $this->getCampaigns();
  foreach ($campaigns as $i => $campaign) {
    try {
      // Get content and save this campaign.
      $mcc = new MailchimpCampaign($campaign);
      $mcc->init()->fetch()->save();
      $this->admin_notice(
        ($i+1) . "https://wordpress.stackexchange.com/" . count($campaigns) . __(' campaign imported.', MCC_TEXT_DOMAIN),
        'updated'
      );

    } catch (Exception $e) {
      $this->admin_notice(
        __('Error during import after ' . $x . 'campaign:' . $e->getMessage() . "\n", MCC_TEXT_DOMAIN),
        'error'
      );
      break;
    }
    $x++;
  }

  // Display result
  $cpt_name = empty($this->settings['cpt_name']) ? MCC_DEFAULT_CPT : $this->settings['cpt_name'];
  $this->admin_notice(__($x . "https://wordpress.stackexchange.com/" . $this->count() . ' campaigns have been imported.', MCC_TEXT_DOMAIN));
}

The init() function

/**
 * Instanciate a new Campaign Post object
 */
public function init() {
  // Populate required fields
  $title   = !empty($this->campaign->settings->title) ? $this->campaign->settings->title : null; // Empty title
  $excerpt = !empty($this->campaign->settings->subject) ? $this->campaign->settings->subject : ''; // Empty exceprt

  // Create a new WP_Post
  $this->post->post_type    = $this->post_type;
  $this->post->post_name    = $title;
  $this->post->post_title   = $title;
  $this->post->post_excerpt = $excerpt;
  $this->post->post_date    = str_replace('T', ' ', $this->campaign->create_time);
  // $this->post->post_date_gmt = str_replace('T', ' ',  $campaign->create_time);
  // $this->post->post_content="";
  $this->post->post_status    = MCC_DEFAULT_CPT_STATUS;
  $this->post->comment_status="open";
  // $this->post->post_modified = '2016-08-15 14:53:24',
  // $this->post->post_modified_gmt="2016-08-15 14:53:24";

  // Custom metadata
  foreach ($this->campaign as $meta_key => $meta_value) {
    $this->post_metas[MCC_META_PRE . $meta_key] = $meta_value;
  }

  return $this;
}

The fetch() function

/**
 * Get a Mailchimp campaign content
 * or any other scope available throught the API
 * @return mixed object || false
 * Haseeb Asif https://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/
 */
public function fetch($scopes = false) {
  if (!$scopes) {
    // Currently only fetching content scope.
    $scopes = array('content');
    // See Mailchimp doc (link above).
    // array('content', 'feedback', 'send-checklist');
  }

  if (!is_array($scopes)) {
    $scopes = array($scopes);
  }

  foreach ($scopes as $scope) {
    try {
      // Save specific data for each activated scope.
      $data = $this->call('campaigns/' . $this->campaign->id . "https://wordpress.stackexchange.com/" . $scope)->get();
      if (!$this->is_error) {
        $this->meta($scope, $data);
      }
    } catch (Exception $e) {
      $this->admin_notice(__('Error during import of campaign (' . $this->campaign->id . '):' . $e->getMessage() . "\n", MCC_TEXT_DOMAIN));
    }
  }
  return $this;
}

The save() function

/**
 * Insert post in database
 */
public function save() {
  if (!$this->post_exists) {
    // Set new posts' content;
    $this->populatePostContent();
  }

  // Save || Update post
  $post_id = $this->post_exists ? wp_update_post($this->post, true) : wp_insert_post($this->post, true);

  // Save || Update post metas
  foreach ($this->post_metas as $meta_key => $meta_value) {
    $unique     = ($meta_key == MCC_META_PRE . 'id') ? true : false;
    $post_metas = $this->post_exists ?
    update_post_meta($post_id, $meta_key, $meta_value) : add_post_meta($post_id, $meta_key, $meta_value, $unique);
  }
  return $this;
}

The populatePostContent() function

/**
 * Add default content inside Newsletter WP Post.
 */
public function populatePostContent() {
  // We use our custom shortcode to display campaign HTML content on front.
  $cid_meta_key = MCC_META_PRE . 'id';
  if (isset($this->post_metas[$cid_meta_key]) && !empty($this->post_metas[$cid_meta_key])) {
    $this->post->post_content="[campaign id="" . $this->post_metas[$cid_meta_key] . '"]';
  }
}

So let’s say the user after importing all campaigns from Mailchimp and saving them into wordpress. The user has modified the titles or deleted certain campaigns he’s not interested to show on his website. Than he went again and click import it will re-import all campaigns overwriting all the modifications that he has done like overwriting the titles and re-imported the deleted campaigns.

Thus I’ve formmated the init() function to check if the date if bigger than the post meta value to import the post the latest ones only.

/**
 * Instanciate a new Campaign Post object
 */
public function init() {
  $args = array(
    'post_type'      => $this->post_type,
    "orderby"        => "post_date",
    "order"          => "DESC",
  );

  // Query the dabatase
  $posts = get_posts($args);

  if (count($posts) > 0) {
      $this->post         = $posts[0];
      $this->post_exists  = true;
      $mc_creation_time   = get_post_meta($this->post->ID, 'mcc_create_time');
      $creation_time      = new DateTime($mc_creation_time);
      $c_creation_time    = new DateTime($this->campaign->create_time);

      if($c_creation_time > $creation_time ) {
        // Populate required fields
        $title            = !empty($this->campaign->settings->title) ? $this->campaign->settings->title : null; // Empty title
        $excerpt          = !empty($this->campaign->settings->subject) ? $this->campaign->settings->subject : ''; // Empty excerpt

        // Create a new WP_Post
        $this->post->post_type      = $this->post_type;
        $this->post->post_name      = $title;
        $this->post->post_title     = $title;
        $this->post->post_excerpt   = $excerpt;
        $this->post->post_date      = str_replace('T', ' ', $this->campaign->create_time);
        $this->post->post_status    = MCC_DEFAULT_CPT_STATUS;
        $this->post->comment_status="open";

        // Custom metadata
        foreach ($this->campaign as $meta_key => $meta_value) {
          $this->post_metas[MCC_META_PRE . $meta_key] = $meta_value;
        }
      }
      echo "before";
  } else {
    // Populate required fields
    $title   = !empty($this->campaign->settings->title) ? $this->campaign->settings->title : null; // Empty title
    $excerpt = !empty($this->campaign->settings->subject) ? $this->campaign->settings->subject : ''; // Empty excerpt

    // Create a new WP_Post
    $this->post->post_type    = $this->post_type;
    $this->post->post_name    = $title;
    $this->post->post_title   = $title;
    $this->post->post_excerpt = $excerpt;
    $this->post->post_date    = str_replace('T', ' ', $this->campaign->create_time);
    // $this->post->post_date_gmt = str_replace('T', ' ',  $campaign->create_time);
    // $this->post->post_content="";
    $this->post->post_status    = MCC_DEFAULT_CPT_STATUS;
    $this->post->comment_status="open";
    // $this->post->post_modified = '2016-08-15 14:53:24',
    // $this->post->post_modified_gmt="2016-08-15 14:53:24";

    // Custom metadata
    foreach ($this->campaign as $meta_key => $meta_value) {
      $this->post_metas[MCC_META_PRE . $meta_key] = $meta_value;
    }
  }

  return $this;
}

Remark the creation_time looks like 2021-12-23T16:02:01+00:00 thus I’m converting it to timestamp to do the comparison.

0
David Buik 9 months 2022-02-24T20:05:48-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse