function tweetimport_import_twitter_feed($twitter_account)
{
  require_once (ABSPATH . WPINC . '/class-feed.php');

  $feed = new SimplePie();

  $account_parts = explode ('/', $twitter_account['twitter_name'], 2);



  if ($twitter_account['account_type'] == 1): //Account is Favorites
    $feed->set_feed_url(str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_FAVORITES_URL));
  elseif ($twitter_account['account_type'] == 0 && count($account_parts) == 1): //User timeline
      $feed->set_feed_url(str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_USER_TIMELINE_URL));
  elseif ($twitter_account['account_type'] == 2 && count($account_parts) == 2): //Account is list
      $feed_url = str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_LIST_URL);
      $feed_url = str_replace('#=#LIST#=#', $account_parts[1], $feed_url);
      $feed->set_feed_url($feed_url);
  else :
      return '<strong>ERROR: Account information not correct. Account type wrong?</strong>';
  endif;

  $feed->set_useragent('Tweet Import http://skinju.com/wordpress/tweetimport');
  $feed->set_cache_class('WP_Feed_Cache');
  $feed->set_file_class('WP_SimplePie_File');
  $feed->enable_cache(true);
  $feed->set_cache_duration (apply_filters('tweetimport_cache_duration', 880));
  $feed->enable_order_by_date(false);
  $feed->init();
  $feed->handle_content_type();

  if ($feed->error()):
   return '<strong>ERROR: Feed Reading Error.</strong>';
  endif;

  $rss_items = $feed->get_items();

  $imported_count = 0;
  foreach ($rss_items as $item)
  {
    $item = apply_filters ('tweetimport_tweet_before_new_post', $item); //return false to stop processing an item.
    if (!$item) continue;

    $processed_description = $item->get_description();

    //Get the twitter author from the beginning of the tweet text
    $twitter_author = trim(preg_replace("~^(\w+):(.*?)$~", "\\1", $processed_description));

    if ($twitter_account['strip_name'] == 1):
      $processed_description = preg_replace("~^(\w+):(.*?)~i", "\\2", $processed_description);
    endif;

    if ($twitter_account['names_clickable'] == 1):
      $processed_description = preg_replace("~@(\w+)~", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $processed_description);
      $processed_description = preg_replace("~^(\w+):~", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>:", $processed_description);
    endif;

    if ($twitter_account['hashtags_clickable'] == 1):
      if ($twitter_account['hashtags_clickable_twitter'] == 1):
          $processed_description = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $processed_description);
      else:
        $processed_description = preg_replace("/#(\w+)/", "<a href=\"" . skinju_get_tag_link("\\1") . "\">#\\1</a>", $processed_description);
      endif;
    endif;

  $processed_description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $processed_description);
  $processed_description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $processed_description);

    $new_post = array('post_title' => trim (substr (preg_replace("~{$account_parts[0]}: ~i", "", $item->get_title()), 0, 25) . '...'),
                      'post_content' => trim ($processed_description),
                      'post_date' => $item->get_date('Y-m-d H:i:s'),
                      'post_author' => $twitter_account['author'],
                      'post_category' => array($twitter_account['category']),
                      'post_status' => 'publish');

    $new_post = apply_filters('tweetimport_new_post_before_create', $new_post); // Offer the chance to manipulate new post data. return false to skip
    if (!$new_post) continue;
    $new_post_id = wp_insert_post($new_post);

    $imported_count++;

    add_post_meta ($new_post_id, 'tweetimport_twitter_author', $twitter_author, true); 
    add_post_meta ($new_post_id, 'tweetimport_date_imported', date ('Y-m-d H:i:s'), true);
    add_post_meta ($new_post_id, 'tweetimport_twitter_id', $item->get_id(), true);
    add_post_meta ($new_post_id, 'tweetimport_twitter_id', $item->get_id(), true);
    add_post_meta ($new_post_id, '_tweetimport_twitter_id_hash', $item->get_id(true), true);
    add_post_meta ($new_post_id, 'tweetimport_twitter_post_uri', $item->get_link(0));
    add_post_meta ($new_post_id, 'tweetimport_author_avatar', $item->get_link(0, 'image'));

    preg_match_all ('~#([A-Za-z0-9_]+)(?=\s|\Z)~', $item->get_description(), $out);
    if ($twitter_account['add_tag']) $out[0][] = $twitter_account['add_tag'];
    wp_set_post_tags($new_post_id, implode (',', $out[0]));
  }

  return $imported_count;
}
Example #2
1
 function custom_bulk_action()
 {
     global $typenow;
     $post_type = $typenow;
     if ($post_type == 'post') {
         // get the action
         $wp_list_table = _get_list_table('WP_Posts_List_Table');
         $action = $wp_list_table->current_action();
         $allowed_actions = array("add_tag");
         if (!in_array($action, $allowed_actions)) {
             return;
         }
         // security check
         check_admin_referer('bulk-posts');
         // make sure ids are submitted.
         if (isset($_REQUEST['post'])) {
             $post_ids = array_map('intval', $_REQUEST['post']);
         }
         if (empty($post_ids)) {
             return;
         }
         $sendback = remove_query_arg(array('exported', 'untrashed', 'deleted', 'ids'), wp_get_referer());
         if (!$sendback) {
             $sendback = admin_url("edit.php?post_type={$post_type}");
         }
         $pagenum = $wp_list_table->get_pagenum();
         $sendback = add_query_arg('paged', $pagenum, $sendback);
         switch ($action) {
             case 'add_tag':
                 $tags_added = 0;
                 foreach ($post_ids as $post_id) {
                     // ANALYSIS CODE
                     if ($valuetoken != 'notoken') {
                         $valuetoken = get_option('apitoken', 'notoken');
                         $keywordsopt = get_option('keywords', 'true');
                         $relevanceopt = get_option('relevance', '0.5');
                         $peopleopt = get_option('people', 'true');
                         $placesopt = get_option('places', 'true');
                         $otheropt = get_option('other', 'true');
                         $organizationsopt = get_option('organization', 'true');
                         $idioma1 = get_option('language1', 'English');
                         $content_post = get_post($post_id);
                         $content = strip_tags($content_post->post_content);
                         $arraytags = array();
                         if ($idioma1 === 'English') {
                             $engine = "https://api.monkeylearn.com/v2/extractors/ex_isnnZRbS/extract/";
                             $keywords = "https://api.monkeylearn.com/v2/extractors/ex_y7BPYzNG/extract/";
                             $location = "LOCATION";
                             $organization = "ORGANIZATION";
                             $person = "PERSON";
                             $other = "OTRO";
                         } elseif ($idioma1 === 'Español') {
                             $engine = "https://api.monkeylearn.com/v2/extractors/ex_Kc8uzhSi/extract/";
                             $keywords = "https://api.monkeylearn.com/v2/extractors/ex_eV2dppYE/extract/";
                             $location = "LUG";
                             $organization = "ORG";
                             $person = "PERS";
                             $other = "OTROS";
                         }
                         //ENTITIES ANALYSIS
                         if ($peopleopt || $organizationsopt || $otheropt || $placesopt) {
                             $url = $engine;
                             $result = wp_autoTAG_remoteApiCall($content, $url, $valuetoken);
                             $jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($result, true)), RecursiveIteratorIterator::SELF_FIRST);
                             $push = false;
                             foreach ($jsonIterator as $key => $val) {
                                 if (is_array($val)) {
                                     // Nothing to do here?
                                 } else {
                                     if ($peopleopt) {
                                         if ($key === 'tag' && $val === $person) {
                                             $push = true;
                                         }
                                     }
                                     if ($placesopt) {
                                         if ($key === 'tag' && $val === $location) {
                                             $push = true;
                                         }
                                     }
                                     if ($organizationsopt) {
                                         if ($key === 'tag' && $val === $organization) {
                                             $push = true;
                                         }
                                     }
                                     if ($otheropt) {
                                         if ($key === 'tag' && $val === $other) {
                                             $push = true;
                                         }
                                     }
                                     if ($key === 'entity' && $push == true) {
                                         $entity = $val;
                                         array_push($arraytags, $entity);
                                         $push = false;
                                     }
                                 }
                             }
                         }
                         // RELEVANT KEYWORDS ANALYSIS
                         if ($keywordsopt) {
                             $limite = $relevanceopt;
                             $url = $keywords;
                             $result2 = wp_autoTAG_remoteApiCall($content, $url, $valuetoken);
                             $jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($result2, TRUE)), RecursiveIteratorIterator::SELF_FIRST);
                             foreach ($jsonIterator as $key => $val) {
                                 if (is_array($val)) {
                                     // Nothing to do here?
                                 } else {
                                     // CHECK RELEVANCE
                                     if ($key === 'relevance') {
                                         if (floatval($val) > floatval($limite)) {
                                             $push = true;
                                         } else {
                                             $push = false;
                                         }
                                     }
                                     // ADD KEYWORDS TO ARRAY
                                     if ($key === 'keyword') {
                                         if ($push == true) {
                                             array_push($arraytags, $val);
                                         }
                                     }
                                 }
                             }
                         }
                         wp_set_post_tags($post_id, $arraytags);
                     }
                     if (!$this->perform_export($post_id)) {
                         wp_die(__('Error adding tags.'));
                     }
                     $tags_added++;
                 }
                 $sendback = add_query_arg(array('exported' => $tags_added, 'ids' => join(',', $post_ids)), $sendback);
                 break;
             default:
                 return;
         }
         $sendback = remove_query_arg(array('action', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status', 'post', 'bulk_edit', 'post_view'), $sendback);
         wp_redirect($sendback);
         exit;
     }
 }
 public function ct_update_tags($tags, $object, $field_name)
 {
     if (empty($tags) || !tags) {
         return;
     }
     return wp_set_post_tags($object->ID, $tags);
 }
Example #4
0
function wp_aatags_alts($post_ID, $post_title, $post_content)
{
    $tags = get_tags(array('hide_empty' => false));
    $tagx = get_option('wp_aatags_opts');
    $number = get_option('wp_aatags_aadnumber');
    switch ($tagx) {
        case 3:
            $d = strtolower($post_title . ' ' . wp_trim_words($post_content, 333, ''));
            break;
        case 2:
            $d = strtolower($post_title . ' ' . wp_trim_words($post_content, 999, ''));
            break;
        default:
            $d = strtolower($post_title);
            break;
    }
    if ($tags) {
        $i = 0;
        foreach ($tags as $tag) {
            if (strpos($d, strtolower($tag->name)) !== false) {
                wp_set_post_tags($post_ID, $tag->name, true);
                $i++;
            }
            if ($i == $number) {
                break;
            }
        }
    }
}
 /**
  * Set tags to the post.
  *
  * @param  int   $post_id Post ID.
  * @param  array $post	Post object.
  * @return none
  * @since  0.1.0
  */
 public static function set_tags($post_id, $post)
 {
     if (!is_wp_error($post_id)) {
         if (isset($post['tags_input'])) {
             wp_set_post_tags($post_id, $post['tags_input'], true);
         }
     }
 }
function image_keyword_tagger_add_keywords($mid, $object_id, $meta_key, $_meta_value)
{
    if ('_wp_attachment_metadata' == $meta_key) {
        $attachment_meta = wp_get_attachment_metadata($object_id);
        if (!empty($attachment_meta['image_meta']['keywords'])) {
            wp_set_post_tags($object_id, implode(',', $attachment_meta['image_meta']['keywords']), true);
        }
    }
}
 public function set_tags($value, $object, $field_name)
 {
     $tags = [];
     foreach ($value as $k => $v) {
         error_log("Setting tag: {$k}");
         $tags[] = $k;
     }
     return wp_set_post_tags($object->ID, $tags);
 }
Example #8
0
 function test_get_the_taxonomies()
 {
     $post_id = $this->factory->post->create();
     $taxes = get_the_taxonomies($post_id);
     $this->assertNotEmpty($taxes);
     $this->assertEquals(array('category'), array_keys($taxes));
     $id = $this->factory->tag->create();
     wp_set_post_tags($post_id, array($id));
     $taxes = get_the_taxonomies($post_id);
     $this->assertNotEmpty($taxes);
     $this->assertCount(2, $taxes);
     $this->assertEquals(array('category', 'post_tag'), array_keys($taxes));
 }
 function tdomf_widget_tags_post($args)
 {
     extract($args);
     $options = tdomf_widget_tags_options($tdomf_form_id);
     $tagslist = '';
     if ($options['default']) {
         $tagslist = strip_tags($options['default']);
     }
     if (isset($tags) && !empty($tags)) {
         if (!empty($tagslist)) {
             $tagslist .= ',';
         }
         $tagslist .= strip_tags($tags);
     }
     if (!empty($tagslist)) {
         # set last var to true to just append
         wp_set_post_tags($post_ID, strip_tags($tagslist), false);
     }
     return NULL;
 }
Example #10
0
 /**
  * @ticket 28099
  * @group taxonomy
  */
 function test_empty_category__in()
 {
     $cat_id = $this->factory->category->create();
     $post_id = $this->factory->post->create();
     wp_set_post_categories($post_id, $cat_id);
     $q1 = get_posts(array('category__in' => array($cat_id)));
     $this->assertNotEmpty($q1);
     $q2 = get_posts(array('category__in' => array()));
     $this->assertNotEmpty($q2);
     $tag = wp_insert_term('woo', 'post_tag');
     $tag_id = $tag['term_id'];
     $slug = get_tag($tag_id)->slug;
     wp_set_post_tags($post_id, $slug);
     $q3 = get_posts(array('tag__in' => array($tag_id)));
     $this->assertNotEmpty($q3);
     $q4 = get_posts(array('tag__in' => array()));
     $this->assertNotEmpty($q4);
     $q5 = get_posts(array('tag_slug__in' => array($slug)));
     $this->assertNotEmpty($q5);
     $q6 = get_posts(array('tag_slug__in' => array()));
     $this->assertNotEmpty($q6);
 }
Example #11
0
function ipin_edit()
{
    $nonce = $_POST['nonce'];
    if (!wp_verify_nonce($nonce, 'ajax-nonce')) {
        die;
    }
    do_action('ipin_before_edit_pin', $_POST);
    global $user_ID;
    $postinfo = get_post(intval($_POST['postdata_pid']), ARRAY_A);
    $user_id = $postinfo['post_author'];
    if (!(current_user_can('administrator') || current_user_can('editor') || $user_id == $user_ID)) {
        die;
    }
    //Get board info
    $board_add_new = sanitize_text_field($_POST['postdata_board_add_new']);
    $board_add_new_category = $_POST['postdata_board_add_new_category'];
    $board_parent_id = get_user_meta($user_id, '_Board Parent ID', true);
    if ($board_add_new !== '') {
        $board_children = get_term_children($board_parent_id, 'board');
        $found = '0';
        foreach ($board_children as $board_child) {
            $board_child_term = get_term_by('id', $board_child, 'board');
            if (stripslashes(htmlspecialchars($board_add_new, ENT_NOQUOTES, 'UTF-8')) == $board_child_term->name) {
                $found = '1';
                $found_board_id = $board_child_term->term_id;
                break;
            }
        }
        if ($found == '0') {
            $slug = wp_unique_term_slug($board_add_new . '__ipinboard', 'board');
            //append __ipinboard to solve slug conflict with category and 0 in title
            if ($board_add_new_category == '-1') {
                $board_add_new_category = '1';
            }
            $new_board_id = wp_insert_term($board_add_new, 'board', array('description' => $board_add_new_category, 'parent' => $board_parent_id, 'slug' => $slug));
            $postdata_board = $new_board_id['term_id'];
        } else {
            $postdata_board = $found_board_id;
        }
    } else {
        $postdata_board = $_POST['postdata_board'];
    }
    //category ID is stored in the board description field
    $category_id = get_term_by('id', $postdata_board, 'board');
    $post_id = intval($_POST['postdata_pid']);
    $edit_post = array();
    $edit_post['ID'] = $post_id;
    $edit_post['post_category'] = array($category_id->description);
    $edit_post['post_name'] = '';
    $allowed_html = array('a' => array('href' => true), 'em' => array(), 'blockquote' => array(), 'p' => array(), 'li' => array(), 'ol' => array(), 'strong' => array(), 'ul' => array());
    if (of_get_option('htmltags') != 'enable') {
        unset($allowed_html);
        $allowed_html = array();
    }
    if (of_get_option('form_title_desc') != 'separate') {
        $edit_post['post_title'] = balanceTags(wp_kses($_POST['postdata_title'], $allowed_html), true);
    } else {
        $edit_post['post_title'] = sanitize_text_field($_POST['postdata_title']);
    }
    $edit_post['post_content'] = balanceTags(wp_kses($_POST['postdata_content'], $allowed_html), true);
    remove_action('save_post', 'ipin_save_post', 50, 2);
    wp_update_post($edit_post);
    wp_set_post_terms($post_id, array($postdata_board), 'board');
    //update postmeta for new post
    if ($_POST['postdata_source'] != '') {
        update_post_meta($post_id, '_Photo Source', esc_url($_POST['postdata_source']));
        update_post_meta($post_id, '_Photo Source Domain', parse_url(esc_url($_POST['postdata_source']), PHP_URL_HOST));
    } else {
        delete_post_meta($post_id, '_Photo Source');
        delete_post_meta($post_id, '_Photo Source Domain');
    }
    //add tags
    wp_set_post_tags($post_id, sanitize_text_field($_POST['postdata_tags']));
    //add price
    if ($_POST['postdata_price']) {
        if (strpos($_POST['postdata_price'], '.') !== false) {
            $_POST['postdata_price'] = number_format($_POST['postdata_price'], 2);
        }
        update_post_meta($post_id, '_Price', sanitize_text_field($_POST['postdata_price']));
    } else {
        if (get_post_meta($post_id, '_Price', true) !== '') {
            delete_post_meta($post_id, '_Price');
        }
    }
    //add new board to followers who fully follow user
    if ($new_board_id && !is_wp_error($new_board_id)) {
        $usermeta_followers_id_allboards = get_user_meta($user_id, '_Followers User ID All Boards');
        $followers_id_allboards = $usermeta_followers_id_allboards[0];
        if (!empty($followers_id_allboards)) {
            foreach ($followers_id_allboards as $followers_id_allboard) {
                $usermeta_following_board_id = get_user_meta($followers_id_allboard, '_Following Board ID');
                $following_board_id = $usermeta_following_board_id[0];
                array_unshift($following_board_id, $new_board_id['term_id']);
                update_user_meta($followers_id_allboard, '_Following Board ID', $following_board_id);
            }
        }
    }
    do_action('ipin_after_edit_pin', $post_id);
    echo get_permalink($post_id);
    exit;
}
Example #12
0
function mass_photo_posting()
{
    global $box;
    // check user permission to use bulk photo posting
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.', MAX_SHORTNAME));
    }
    // get the current user object
    $current_user = wp_get_current_user();
    if (!empty($_POST) && !empty($_POST['post'])) {
        ksort($_POST['post']);
        foreach ($_POST['post'] as $key => $value) {
            $imageID = $key;
            $photos[$imageID]['id_photo'] = $imageID;
            $photos[$imageID]['post_name'] = $_POST['post_name'][$imageID];
            foreach (@$_POST['galleries'] as $key => $value) {
                if ($key == $imageID) {
                    foreach ($value as $key2 => $value2) {
                        $photos[$imageID]['gal'] .= $key2 . ",";
                    }
                }
            }
            $photos[$imageID]['photo_copyright_information_value'] = $_POST['photo_copyright_information_value'][$imageID];
            $photos[$imageID]['photo_copyright_link_value'] = $_POST['photo_copyright_link_value'][$imageID];
            $photos[$imageID]['photo_location_value'] = $_POST['photo_location_value'][$imageID];
            $photos[$imageID]['photo_date_value'] = strtotime($_POST['photo_date_value'][$imageID]);
            $photos[$imageID]['photo_item_type_value'] = $_POST['photo_item_type_value'][$imageID];
            $photos[$imageID]['photo_cropping_direction_value'] = $_POST['photo_cropping_direction_value'][$imageID];
            $photos[$imageID]['photo_lightbox_type_value'] = "Photo";
            // Get fullsize background
            if ($_POST['fullsize_background'][$imageID] == 'nofullsize') {
                $photos[$imageID]['show_post_fullsize_value'] = 'false';
            } else {
                $photos[$imageID]['show_post_fullsize_value'] = 'true';
            }
            if ($_POST['fullsize_background'][$imageID] == 'random') {
                $photos[$imageID]['show_random_fullsize_value'] = 'true';
            } else {
                if ($_POST['fullsize_background'][$imageID] == 'featured') {
                    $photos[$imageID]['show_random_fullsize_value'] = 'false';
                } else {
                    $photos[$imageID]['show_random_fullsize_value'] = 'false';
                }
            }
            if ($_POST['fullsize_background_url'][$imageID] != '') {
                $photos[$imageID]['show_page_fullsize_url_value'] = $_POST['fullsize_background_url'][$imageID];
            }
            // get the tags array
            $photos[$imageID]['post_tags'] = explode(",", trim($_POST['post_tags'][$imageID]));
        }
        if (!empty($photos)) {
            foreach ($photos as $photo) {
                $cat_array = explode(',', substr($photo['gal'], 0, -1));
                // prepare the photo post values
                $post = array('post_title' => $photo['post_name'], 'post_content' => '', 'post_status' => 'publish', 'post_author' => $current_user->ID, 'post_type' => POST_TYPE_GALLERY, 'tax_input' => array(GALLERY_TAXONOMY => $cat_array));
                // add the new post
                $post_id = wp_insert_post($post);
                // add the tags to the new post
                if (!empty($photo['post_tags'])) {
                    wp_set_post_tags($post_id, $photo['post_tags']);
                    unset($GLOBALS['tag_cache']);
                }
                // add the meta fields from $_POST values to the new post
                foreach ($photo as $index => $value) {
                    add_post_meta($post_id, MAX_SHORTNAME . '_' . $index, $photo[$index]);
                }
                // Set featured post from media attachment
                set_post_thumbnail($post_id, $photo['id_photo']);
                $image_post = array();
                $image_post['ID'] = $photo['id_photo'];
                $image_post['post_parent'] = $post_id;
                // update the post
                wp_update_post($image_post);
                // show update message
                $_saved = true;
            }
        }
    } else {
        $_saved = false;
    }
    // Get unassigned attachments
    $images_args = array('numberposts' => 99999, 'orderby' => 'post_date', 'order' => 'ASC', 'post_type' => 'attachment', 'post_parent' => 0, 'post_status' => 'inherit');
    $images = get_posts($images_args);
    // Get Gallery Categories
    $gallery_args = array('type' => 'post', 'child_of' => 0, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => 0, 'hierarchical' => 1, 'taxonomy' => GALLERY_TAXONOMY, 'pad_counts' => false);
    $galleries = get_categories($gallery_args);
    // get the custom post type for further use
    $post_types = max_get_custom_post_type();
    // get galleries in hirachical order
    $taxonomy_names = get_object_taxonomies('gallery');
    $hierarchical_taxonomies = array();
    $flat_taxonomies = array();
    foreach ($taxonomy_names as $taxonomy_name) {
        $taxonomy = get_taxonomy($taxonomy_name);
        if (!$taxonomy->show_ui) {
            continue;
        }
        if ($taxonomy->hierarchical) {
            $hierarchical_taxonomies[] = $taxonomy;
        } else {
            $flat_taxonomies[] = $taxonomy;
        }
    }
    ?>

	<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/base/jquery-ui.css" rel="stylesheet" />

	<style type="text/css">
		#massPhotoUpload th { }
		#massPhotoUpload th.col-preview, #massPhotoUpload td.media-icon { width: 70px; padding: 8px 0; }

		#massPhotoUpload .col-gallery, #massPhotoUpload .col-gallery ul, #massPhotoUpload .col-gallery ul li { margin: 0; padding: 0; font-size: 11px; line-height: 20px; }
		#massPhotoUpload td.col-gallery { padding: 7px 13px 7px 0; white-space: nowrap; width: 15% }

		#massPhotoUpload ul.cat-checklist { background-color: white; border-color: #DDD; padding: 0 5px; }

		#massPhotoUpload .col-gallery ul.children { margin: 0 0 0 18px; }
		#massPhotoUpload .col-gallery input { margin-top: 0; }

		#massPhotoUpload th.col-meta { width: 10em; }
		#massPhotoUpload td { padding: 4px 7px 2px; }
		#massPhotoUpload td label { white-space: nowrap  }
		#massPhotoUpload td.col-description .input-text-wrap, #massPhotoUpload th.col-description .input-text-wrap { color: #808387; font-size: 11px; }
		#massPhotoUpload td.col-description .input-text-wrap .text-description{ width: 90%; display: block; white-space: normal; padding-left: .65em; }
		#massPhotoUpload td.col-background { width: 160px; }
		#massPhotoUpload td.col-background label span.title { width: auto; float: none; }
		#massPhotoUpload td.col-background label span.input-text-wrap { margin: 0; float: left; width: 1.5em }

		#massPhotoUpload tr.front-row td, #massPhotoUpload tr.front-row th { background: #ECECEC; }
		#massPhotoUpload input.post_name, #massPhotoUpload textarea.post_tags { width: 90%; }
		#massPhotoUpload a.post_file { line-height: 22px; font-size: 11px; }
		#massPhotoUpload .file-ext { text-transform: uppercase; }
		#massPhotoUpload td.column-file label span.file-ext { font-size: 11px; }
		#massPhotoUpload input.button-primary { margin-bottom: 15px; }
		#massPhotoUpload input[type="radio"] { height: 17px; }

		#massPhotoUpload select, #massPhotoUpload textarea { font-size: 11px; }
		#massPhotoUpload .input-url { display: none; width: 90% }
	</style>

	<div class="wrap">
		<div id="icon-upload" class="icon32"><br /></div>
		<h2>Bulk <?php 
    echo $post_types[POST_TYPE_GALLERY]->labels->singular_name;
    ?>
 Posting <a href="media-new.php" class="add-new-h2">Add New Media</a></h2>

		<?php 
    if ($_saved === true) {
        ?>
		<div id="message" class="updated below-h2">
			<p>
				<?php 
        echo $post_types[POST_TYPE_GALLERY]->labels->name;
        ?>
 saved and published. <a href="edit.php?post_type=gallery"><?php 
        echo $post_types[POST_TYPE_GALLERY]->labels->name;
        ?>
</a><br>
			</p>
		</div>
		<?php 
    }
    ?>


		<form method="post" id="massPhotoUpload">
		<p>
			<?php 
    _e('This list shows all the images from your media library that are not attached to any post. You can create your posts easily from here with a few clicks.', MAX_SHORTNAME);
    ?>
		</p>

		<?php 
    if ($images) {
        ?>

			<table class="wp-list-table widefat" cellpadding="0" cellspacing="0">
			<thead>
				<tr>
					<th scope="col" class="manage-column column-cb check-column">&nbsp;</th>
					<th scope="col" class="manage-column col-preview">&nbsp;</th>
					<th scope="col" class="manage-column"><?php 
        _e('File', MAX_SHORTNAME);
        ?>
</th>
					<th scope="col" class="manage-column col-gallery"><?php 
        _e('Galleries', MAX_SHORTNAME);
        ?>
</th>
					<th scope="col" class="manage-column col-meta"><?php 
        _e('Meta Information', MAX_SHORTNAME);
        ?>
</th>
					<th scope="col" class="manage-column"><?php 
        _e('Settings', MAX_SHORTNAME);
        ?>
</th>
					<th scope="col" class="manage-column"><?php 
        _e('Background Image ', MAX_SHORTNAME);
        ?>
</th>
				</tr>
			</thead>
			<tbody>

				<?php 
        // More than one image
        if (count($images) > 1) {
            ?>
				<tr class="front-row inline-edit-row">
					<th scope="row" class="column-cb check-column"><input type="checkbox" id="post" disabled="disabled" /></th>
					<td>&nbsp;</td>
					<td class="col-description">
						<fieldset>
							<label>
								<span class="title"><?php 
            _e('Title', MAX_SHORTNAME);
            ?>
</span>
								<span class="input-text-wrap">
									<input type="text" id="post_name" class="post_name">
								</span>
							</label>
							<label>
								<span class="title"><?php 
            _e('Tags', MAX_SHORTNAME);
            ?>
</span>
								<span class="input-text-wrap">
									<textarea id="post_tags" class="post_tags tax_input_post_tag"></textarea>
								</span>
							</label>
							<label>
								<span class="input-text-wrap"><span class="text-description"><?php 
            _e('Changes made in this line will be incorporated into other lines.', MAX_SHORTNAME);
            ?>
</span></span>
							</label>
						</fieldset>
					</td>
					<td class="col-gallery">
						<?php 
            if (count($hierarchical_taxonomies)) {
                foreach ($hierarchical_taxonomies as $taxonomy) {
                    $box = array('id' => $taxonomy->name, 'hideid' => 1);
                    $output = '<input type="hidden" name="" value="0" />';
                    $output .= '<ul class="cat-checklist ' . esc_attr($taxonomy->name) . '-checklist">';
                    ob_start();
                    wp_terms_checklist(null, array('taxonomy' => $taxonomy->name, 'walker' => new max_category_checklist_walker(), 'selected_cats' => "", 'checked_ontop' => false));
                    $output .= ob_get_contents();
                    ob_end_clean();
                    $output .= '</ul>';
                }
                //$hierarchical_taxonomies as $taxonomy
            }
            // count( $hierarchical_taxonomies ) && !$bulk
            echo $output;
            ?>
					</td>
					<td>
						<fieldset>
							<label>
								<span class="title">&copy; Owner</span>
								<span class="input-text-wrap">
									<input type="text" id="photo_copyright_information_value" />
								</span>
							</label>
							<label>
								<span class="title">&copy; Link</span>
								<span class="input-text-wrap">
									<input type="text" id="photo_copyright_link_value" />
								</span>
							</label>
							<label>
								<span class="title">Location</span>
								<span class="input-text-wrap">
									<input type="text" id="photo_location_value">
								</span>
							</label>
							<label>
								<span class="title">Date</span>
								<span class="input-text-wrap">
									<input type="text" id="photo_date_value" class="photo_date_value">
								</span>
							</label>
						</fieldset>
					</td>
					<td>
						<fieldset>
							<label>
								<span class="title"><?php 
            _e('Link type', MAX_SHORTNAME);
            ?>
</span>
								<span class="input-text-wrap">
									<select id="photo_item_type_value"><option value="lightbox" selected="selected" >Lightbox</option><option value="projectpage">Project Page</option></select>
								</span>
							</label>
							<label>
								<span class="title"><?php 
            _e('Cropping', MAX_SHORTNAME);
            ?>
</span>
								<span class="input-text-wrap">
									<select id="photo_cropping_direction_value">
										<option value="c" selected="selected">Position in the Center (default)</option>
										<option value="t">Align top</option>
										<option value="tr">Align top right</option>
										<option value="tl">Align top left</option>
										<option value="b">Align bottom</option>
										<option value="br">Align bottom right</option>
										<option value="bl">Align bottom left</option>
										<option value="l">Align left</option>
										<option value="r">Align right</option>
									</select>
								</span>

							</label>
						</fieldset>
					</td>
					<td class="col-description col-background">
						<fieldset>
							<label>
								<span class="input-text-wrap">
									<input type="radio" id="fullsize_background_featured" name="fullsize_background" value="featured" checked="checked" />
								</span>
								<span class="title"><?php 
            _e('Post Featured Image', MAX_SHORTNAME);
            ?>
</span>
							</label>
							<label>
								<span class="input-text-wrap">
									<input type="radio" id="fullsize_background_random" name="fullsize_background" value="random" />
								</span>
								<span class="title"><?php 
            _e('Random Gallery Image', MAX_SHORTNAME);
            ?>
</span>
							</label>
							<label>
								<span class="input-text-wrap">
									<input type="radio" id="fullsize_background_url" name="fullsize_background" value="url" />
								</span>
								<span class="title"><?php 
            _e('Image from URL', MAX_SHORTNAME);
            ?>
</span>
								<input type="text" id="fullsize_background_url_value" name="fullsize_background_url" class="input-url"/>
							</label>
							<label>
								<span class="input-text-wrap">
									<input type="radio" id="fullsize_background_show" name="fullsize_background" value="nofullsize" />
								</span>
								<span class="title"><?php 
            _e('No Background', MAX_SHORTNAME);
            ?>
</span>
							</label>
						</fieldset>
					</td>
				</tr>
				<?php 
        }
        ?>
				<?php 
        foreach ($images as $image) {
            $path_info = pathinfo(wp_get_attachment_url($image->ID, 'full'));
            echo '<tr class="inline-edit-row">';
            echo '<th class="check-column"><input type="checkbox" class="post" name="post[' . $image->ID . ']" value="1" disabled="disabled" /></th>';
            echo '<td class="column-icon media-icon"><a href="' . wp_get_attachment_url($image->ID, 'full') . '">' . wp_get_attachment_image($image->ID, array(64, 64)) . '</a></td>';
            echo '<td class="column-file">
								<fieldset>
									<label>
										<span class="title">' . __('Title', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<input type="text" name="post_name[' . $image->ID . ']" class="post_name" value="' . $image->post_title . '">
											<input type="hidden" name="post_hidden_name[' . $image->ID . ']" value="' . $image->post_title . '">
										</span>
									</label>
									<label>
										<span class="title">' . __('Tags', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<textarea name="post_tags[' . $image->ID . ']" class="post_tags">' . $image->post_tags . '</textarea>
											<input type="hidden" name="post_hidden_tags[' . $image->ID . ']" value="' . $image->post_tags . '">
										</span>
									</label>
									<label>
										<span class="title">' . __('File', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<a href="media.php?attachment_id=' . $image->ID . '&action=edit" class="post_file">' . $image->post_title . '</a> - <span class="file-ext">' . $path_info['extension'] . '</span>
										</span>
									</label>
									<label class="gallery-error">
										<span class="title"></span>
										<span class="input-text-wrap">
											<small class="ui-state-error-text">' . __('You need to choose at least one gallery to save this photo.', MAX_SHORTNAME) . '</small>
										</span>
									</label>
								</fieldset>

							  </td>';
            echo '<td class="col-gallery">';
            $output = "";
            if (count($hierarchical_taxonomies)) {
                foreach ($hierarchical_taxonomies as $taxonomy) {
                    $box = array('id' => 'galleries', 'imageID' => $image->ID);
                    $output .= '<input type="hidden" name="" value="0" />';
                    $output .= '<ul class="cat-checklist ' . esc_attr($taxonomy->name) . '-checklist">';
                    ob_start();
                    wp_terms_checklist(null, array('taxonomy' => $taxonomy->name, 'walker' => new max_category_checklist_walker(), 'selected_cats' => get_post_meta($image->ID, $box['id'], true), 'checked_ontop' => false));
                    $output .= ob_get_contents();
                    ob_end_clean();
                    $output .= '</ul>';
                }
                //$hierarchical_taxonomies as $taxonomy
            }
            // count( $hierarchical_taxonomies ) && !$bulk
            echo $output;
            echo '</td>';
            echo '<td>
								<fieldset>
									<label>
										<span class="title">' . __('&copy; Owner', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<input type="text" class="photo_copyright_information_value" name="photo_copyright_information_value[' . $image->ID . ']">
										</span>
									</label>
									<label>
										<span class="title">' . __('&copy; Link', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<input type="text" class="photo_copyright_link_value" name="photo_copyright_link_value[' . $image->ID . ']">
										</span>
									</label>
								</fieldset>
								<fieldset>
									<label>
										<span class="title">' . __('Location', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<input type="text" class="photo_location_value" name="photo_location_value[' . $image->ID . ']">
										</span>
									</label>
									<label>
										<span class="title">' . __('Date', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<input type="text" class="photo_date_value" name="photo_date_value[' . $image->ID . ']">
										</span>
									</label>
								</fieldset>
							 </td>';
            echo '<td>
								<fieldset>
									<label>
										<span class="title">' . __('Link type', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<select name="photo_item_type_value[' . $image->ID . ']" class="photo_item_type_value"><option value="lightbox" selected="selected">Lightbox</option><option value="projectpage">Project Page</option></select>
										</span>
									</label>
									<label>
										<span class="title">' . __('Cropping', MAX_SHORTNAME) . '</span>
										<span class="input-text-wrap">
											<select name="photo_cropping_direction_value[' . $image->ID . ']" class="photo_cropping_direction_value">
												<option value="c" selected="selected">Position in the Center (default)</option>
												<option value="t">Align top</option>
												<option value="tr">Align top right</option>
												<option value="tl">Align top left</option>
												<option value="b">Align bottom</option>
												<option value="br">Align bottom right</option>
												<option value="bl">Align bottom left</option>
												<option value="l">Align left</option>
												<option value="r">Align right</option>
											</select>
										</span>
									</label>
								</fieldset>
							  </td>';
            echo '<td class="col-background">
								<fieldset>
									<label>
										<span class="input-text-wrap">
											<input type="radio" class="fullsize_background_featured" name="fullsize_background[' . $image->ID . ']" value="featured"  checked="checked">
										</span>
										<span class="title">' . __('Post Featured Image', MAX_SHORTNAME) . '</span>
									</label>
									<label>
										<span class="input-text-wrap">
											<input type="radio" class="fullsize_background_random" name="fullsize_background[' . $image->ID . ']" value="random">
										</span>
										<span class="title">' . __('Random Gallery Image', MAX_SHORTNAME) . '</span>
									</label>
									<label>
										<span class="input-text-wrap">
											<input type="radio" class="fullsize_background_url" name="fullsize_background[' . $image->ID . ']" value="url" />
										</span>
										<span class="title">' . __('Image from URL', MAX_SHORTNAME) . '</span>
										<input type="text" class="fullsize_background_url_value input-url" name="fullsize_background_url[' . $image->ID . ']" />
									</label>
									<label>
										<span class="input-text-wrap">
											<input type="radio" class="fullsize_background_show" name="fullsize_background[' . $image->ID . ']" value="nofullsize">
										</span>
										<span class="title">' . __('No Background', MAX_SHORTNAME) . '</span>
									</label>
								</fieldset>
							  </td>';
            echo '</tr>';
        }
        ?>
				</tbody>
			</table>
			<p class="submit"><input type="submit" disabled="disabled" value="<?php 
        _e('Save and publish marked ' . $post_types[POST_TYPE_GALLERY]->labels->name, MAX_SHORTNAME);
        ?>
" class="button-primary save"></p>

			<?php 
    } else {
        // no unattached images in media library
        ?>
			<div id="message" class="updated below-h2">
				<p>
					You don't have images in your media library that are not attached to any post. <a href="media-new.php">Add New Media</a> <br>
				</p>
			</div>
			<?php 
    }
    ?>

		</form>
	</div>

	<script type="text/javascript">

		jQuery(document).ready(function($) {

			jQuery(".photo_date_value").datepicker();

			// odd/even for alternate rows
			jQuery('#massPhotoUpload tr:odd').addClass('alternate');

			// Change action for all rows
			jQuery("#massPhotoUpload tr.front-row td input, #massPhotoUpload tr.front-row td textarea, #massPhotoUpload tr.front-row th input, #massPhotoUpload tr.front-row th textarea").change(function () {
				var gal = jQuery(this).attr('id');

				// check for checkbox and cb value
				if(jQuery(this).is(':checkbox') || jQuery(this).is(':radio')){
					if(jQuery(this).is(':checked')){
						var $checkbox = jQuery("."+gal);
						$checkbox.attr('checked', true);
						$checkbox.change();
					}else{
						var $checkbox = jQuery("."+gal);
						$checkbox.attr('checked', false);
						$checkbox.change();
					}
				}

				// if its the post title
				if(jQuery(this).hasClass('post_name')){
					var ele = jQuery(this);
					var i = 1;
					jQuery("."+gal).not(ele).each(function(){
						if(ele.attr('value') != ""){
							jQuery(this).attr('value', ele.attr('value') + "-" + i);
							i++;
						}else{

							jQuery(this).attr('value', jQuery(this).next().val() );

						}
					});
				}else{
					jQuery("."+gal).attr('value', jQuery(this).attr('value'));
				}
			});

			// change event of select
			jQuery("#massPhotoUpload tr.front-row td select").change(function () {
				var id = jQuery(this).attr('id');
				var sel = jQuery(this).val();
				jQuery("."+id).val(sel);
			});

			// Show and hide URL input
			jQuery("#massPhotoUpload input[type='radio']").bind('change',function(){

				if( jQuery(this).is("tr.front-row input[type='radio']") && jQuery(this).val() == 'url' ){
					jQuery("#massPhotoUpload .input-url").show();
				}else if ( jQuery(this).is("tr.front-row input[type='radio']") && jQuery(this).val() != 'url' ){
					jQuery("#massPhotoUpload .input-url").hide().val('');
				}else{

					if(jQuery(this).val() == 'url'){
						jQuery(this).parents('fieldset').find('.input-url').show();
					}else{
						jQuery(this).parents('fieldset').find('.input-url').hide();
					}

				}
			})

			// check for number of images to publish
			jQuery('th.check-column input[type=checkbox]').bind('change', function(){

                var b = $('th.check-column input');
                if( b.filter(':checked').length > 0) {
					jQuery('p.submit input.save').removeAttr('disabled');
				}else{
					jQuery('p.submit input.save').attr('disabled', 'disabled');
				}

			})


			// gallery checkbox action
			jQuery('ul.cat-checklist input').live('change', function (){

				var ul = jQuery(this).parents('ul.cat-checklist')
				var checked = jQuery('input', ul).filter(':checked').length;

				if(checked > 0){
					ul.parents('tr').find('th.check-column input').attr('disabled',false);
					ul.parents('tr').find('td.column-file .gallery-error').hide();
				}else{
					ul.parents('tr').find('th.check-column input').attr('disabled',true);
					ul.parents('tr').find('td.column-file .gallery-error').show();
				}
			})



		});
	</script>
	<?php 
}
function usp_createPublicSubmission($title, $content, $authorName, $authorID, $authorUrl, $tags, $category, $fileData)
{
    global $usp_options, $usp_post_meta_IsSubmission, $usp_post_meta_SubmitterIp, $usp_post_meta_Submitter, $usp_post_meta_SubmitterUrl, $usp_post_meta_Image;
    $authorName = strip_tags($authorName);
    $authorUrl = strip_tags($authorUrl);
    if (isset($_SERVER['REMOTE_ADDR'])) {
        $authorIp = stripslashes(trim($_SERVER['REMOTE_ADDR']));
    }
    if (isset($_POST['user-submitted-captcha'])) {
        $captcha = stripslashes(trim($_POST['user-submitted-captcha']));
    }
    if (isset($_POST['user-submitted-verify'])) {
        $verify = stripslashes(trim($_POST['user-submitted-verify']));
    }
    if (!usp_validateTitle($title)) {
        return false;
    }
    if (!usp_validateTags($tags)) {
        return false;
    }
    if (!empty($verify)) {
        return false;
    }
    if ($usp_options['usp_captcha'] == 'show') {
        if (!usp_spam_question($captcha)) {
            return false;
        }
    }
    $postData = array();
    $postData['post_title'] = $title;
    $postData['post_content'] = $content;
    $postData['post_status'] = 'pending';
    $postData['post_author'] = $authorID;
    $numberApproved = $usp_options['number-approved'];
    if ($numberApproved < 0) {
    } elseif ($numberApproved == 0) {
        $postData['post_status'] = 'publish';
    } else {
        $posts = get_posts(array('post_status' => 'publish', 'meta_key' => $usp_post_meta_Submitter, 'meta_value' => $authorName));
        $counter = 0;
        foreach ($posts as $post) {
            $submitterUrl = get_post_meta($post->ID, $usp_post_meta_SubmitterUrl, true);
            $submitterIp = get_post_meta($post->ID, $usp_post_meta_SubmitterIp, true);
            if ($submitterUrl == $authorUrl && $submitterIp == $authorIp) {
                $counter++;
            }
        }
        if ($counter >= $numberApproved) {
            $postData['post_status'] = 'publish';
        }
    }
    $newPost = wp_insert_post($postData);
    if ($newPost) {
        wp_set_post_tags($newPost, $tags);
        wp_set_post_categories($newPost, array($category));
        if ($usp_options['usp_email_alerts'] == true) {
            $to = $usp_options['usp_email_address'];
            if ($to !== '') {
                $subject = 'New user-submitted post!';
                $message = 'Hey, there is a new user-submitted post waiting for you.';
                wp_mail($to, $subject, $message);
            }
        }
        if (!function_exists('media_handle_upload')) {
            require_once ABSPATH . '/wp-admin/includes/media.php';
            require_once ABSPATH . '/wp-admin/includes/file.php';
            require_once ABSPATH . '/wp-admin/includes/image.php';
        }
        $attachmentIds = array();
        $imageCounter = 0;
        if ($fileData !== '') {
            for ($i = 0; $i < count($fileData['name']); $i++) {
                $imageInfo = @getimagesize($fileData['tmp_name'][$i]);
                if (false === $imageInfo || !usp_imageIsRightSize($imageInfo[0], $imageInfo[1])) {
                    continue;
                }
                $key = "public-submission-attachment-{$i}";
                $_FILES[$key] = array();
                $_FILES[$key]['name'] = $fileData['name'][$i];
                $_FILES[$key]['tmp_name'] = $fileData['tmp_name'][$i];
                $_FILES[$key]['type'] = $fileData['type'][$i];
                $_FILES[$key]['error'] = $fileData['error'][$i];
                $_FILES[$key]['size'] = $fileData['size'][$i];
                $attachmentId = media_handle_upload($key, $newPost);
                if (!is_wp_error($attachmentId) && wp_attachment_is_image($attachmentId)) {
                    $attachmentIds[] = $attachmentId;
                    add_post_meta($newPost, $usp_post_meta_Image, wp_get_attachment_url($attachmentId));
                    $imageCounter++;
                } else {
                    wp_delete_attachment($attachmentId);
                }
                if ($imageCounter == $usp_options['max-images']) {
                    break;
                }
            }
        }
        if (count($attachmentIds) < $usp_options['min-images']) {
            foreach ($attachmentIds as $idToDelete) {
                wp_delete_attachment($idToDelete);
            }
            wp_delete_post($newPost);
            return false;
        }
        update_post_meta($newPost, $usp_post_meta_IsSubmission, true);
        update_post_meta($newPost, $usp_post_meta_Submitter, htmlentities($authorName, ENT_QUOTES, 'UTF-8'));
        update_post_meta($newPost, $usp_post_meta_SubmitterUrl, htmlentities($authorUrl, ENT_QUOTES, 'UTF-8'));
        update_post_meta($newPost, $usp_post_meta_SubmitterIp, htmlentities($authorIp, ENT_QUOTES, 'UTF-8'));
    }
    return $newPost;
}
Example #14
0
function tag_post_image_luminance($post_id)
{
    $threshold = 128;
    $tags = array();
    // Get the image data
    $image_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'small');
    $image_url = $image_src[0];
    if (empty($image_url)) {
        return $post_id;
    }
    // detect luminence value
    $luminance = calculate_image_luminance($image_url);
    $tags = wp_get_post_tags($post_id, array('fields' => 'names'));
    if ($luminance < $threshold) {
        $tags[] = 'dark';
    } elseif (false !== ($key = array_search('dark', $messages))) {
        unset($tags[$key]);
    }
    // Set a tag class
    if (!empty($tags)) {
        wp_set_post_tags($post_id, $tags, true);
    }
    return $post_id;
}
Example #15
0
 public function test_get_objects_in_term_should_return_objects_ids()
 {
     $tag_id = $this->factory->tag->create();
     $cat_id = $this->factory->category->create();
     $posts_with_tag = array();
     $posts_with_category = array();
     for ($i = 0; $i < 3; $i++) {
         $post_id = $this->factory->post->create();
         wp_set_post_tags($post_id, array($tag_id));
         $posts_with_tag[] = $post_id;
     }
     for ($i = 0; $i < 3; $i++) {
         $post_id = $this->factory->post->create();
         wp_set_post_categories($post_id, array($cat_id));
         $posts_with_category[] = $post_id;
     }
     for ($i = 0; $i < 3; $i++) {
         $this->factory->post->create();
     }
     $posts_with_terms = array_merge($posts_with_tag, $posts_with_category);
     $this->assertEquals($posts_with_tag, get_objects_in_term($tag_id, 'post_tag'));
     $this->assertEquals($posts_with_category, get_objects_in_term($cat_id, 'category'));
     $this->assertEquals($posts_with_terms, get_objects_in_term(array($tag_id, $cat_id), array('post_tag', 'category')));
     $this->assertEquals(array_reverse($posts_with_tag), get_objects_in_term($tag_id, 'post_tag', array('order' => 'desc')));
 }
Example #16
0
/**
 * Insert an attachment.
 *
 * If you set the 'ID' in the $object parameter, it will mean that you are
 * updating and attempt to update the attachment. You can also set the
 * attachment name or title by setting the key 'post_name' or 'post_title'.
 *
 * You can set the dates for the attachment manually by setting the 'post_date'
 * and 'post_date_gmt' keys' values.
 *
 * By default, the comments will use the default settings for whether the
 * comments are allowed. You can close them manually or keep them open by
 * setting the value for the 'comment_status' key.
 *
 * The $object parameter can have the following:
 *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
 *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
 *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
 *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
 *                       can accept pings.
 *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
 *                       to, if any.
 *     'menu_order'    - Default is 0. The order it is displayed.
 *     'to_ping'       - Whether to ping.
 *     'pinged'        - Default is empty string.
 *     'post_password' - Default is empty string. The password to access the attachment.
 *     'guid'          - Global Unique ID for referencing the attachment.
 *     'post_content_filtered' - Attachment post content filtered.
 *     'post_excerpt'  - Attachment excerpt.
 *
 * @since 2.0.0
 * @uses $wpdb
 * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
 * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
 *
 * @param string|array $object Arguments to override defaults.
 * @param string $file Optional filename.
 * @param int $parent Parent post ID.
 * @return int Attachment ID.
 */
function wp_insert_attachment($object, $file = false, $parent = 0)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'post_title' => '', 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'post_content' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => '');
    $object = wp_parse_args($object, $defaults);
    if (!empty($parent)) {
        $object['post_parent'] = $parent;
    }
    unset($object['filter']);
    $object = sanitize_post($object, 'db');
    // export array as variables
    extract($object, EXTR_SKIP);
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    $post_type = 'attachment';
    if (!in_array($post_status, array('inherit', 'private'))) {
        $post_status = 'inherit';
    }
    if (!empty($post_category)) {
        $post_category = array_filter($post_category);
    }
    // Filter out empty terms
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        $post_category = array();
    }
    // Are we updating or creating?
    if (!empty($ID)) {
        $update = true;
        $post_ID = (int) $ID;
    } else {
        $update = false;
        $post_ID = 0;
    }
    // Create a valid post name.
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = sanitize_title($post_name);
    }
    // expected_slashed ($post_name)
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    if (empty($post_date)) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt)) {
        $post_date_gmt = current_time('mysql', 1);
    }
    if (empty($post_modified)) {
        $post_modified = $post_date;
    }
    if (empty($post_modified_gmt)) {
        $post_modified_gmt = $post_date_gmt;
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password)) {
        $post_password = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid'));
    $data = wp_unslash($data);
    if ($update) {
        $wpdb->update($wpdb->posts, $data, array('ID' => $post_ID));
    } else {
        // If there is a suggested ID, use it if not already present
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        $wpdb->insert($wpdb->posts, $data);
        $post_ID = (int) $wpdb->insert_id;
    }
    if (empty($post_name)) {
        $post_name = sanitize_title($post_title, $post_ID);
        $wpdb->update($wpdb->posts, compact("post_name"), array('ID' => $post_ID));
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    // support for all custom taxonomies
    if (!empty($tax_input)) {
        foreach ($tax_input as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (is_array($tags)) {
                // array = hierarchical, string = non-hierarchical.
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if ($file) {
        update_attached_file($post_ID, $file);
    }
    clean_post_cache($post_ID);
    if (!empty($context)) {
        add_post_meta($post_ID, '_wp_attachment_context', $context, true);
    }
    if ($update) {
        do_action('edit_attachment', $post_ID);
    } else {
        do_action('add_attachment', $post_ID);
    }
    return $post_ID;
}
 /**
  * Loop through the fields being edited and if they include Post fields, update the Entry's post object
  *
  * @param array $form Gravity Forms form
  *
  * @return void
  */
 function maybe_update_post_fields($form)
 {
     $post_id = $this->entry['post_id'];
     // Security check
     if (false === GVCommon::has_cap('edit_post', $post_id)) {
         do_action('gravityview_log_error', 'The current user does not have the ability to edit Post #' . $post_id);
         return;
     }
     $update_entry = false;
     $updated_post = $original_post = get_post($post_id);
     foreach ($this->entry as $field_id => $value) {
         //todo: only run through the edit entry configured fields
         $field = RGFormsModel::get_field($form, $field_id);
         if (class_exists('GF_Fields')) {
             $field = GF_Fields::create($field);
         }
         if (GFCommon::is_post_field($field)) {
             // Get the value of the field, including $_POSTed value
             $value = RGFormsModel::get_field_value($field);
             // Convert the field object in 1.9 to an array for backward compatibility
             $field_array = GVCommon::get_field_array($field);
             switch ($field_array['type']) {
                 case 'post_title':
                 case 'post_content':
                 case 'post_excerpt':
                     $updated_post->{$field_array['type']} = $value;
                     break;
                 case 'post_tags':
                     wp_set_post_tags($post_id, $value, false);
                     break;
                 case 'post_category':
                     $categories = is_array($value) ? array_values($value) : (array) $value;
                     $categories = array_filter($categories);
                     wp_set_post_categories($post_id, $categories, false);
                     // prepare value to be saved in the entry
                     $field = GFCommon::add_categories_as_choices($field, '');
                     // if post_category is type checkbox, then value is an array of inputs
                     if (isset($value[strval($field_id)])) {
                         foreach ($value as $input_id => $val) {
                             $input_name = 'input_' . str_replace('.', '_', $input_id);
                             $this->entry[strval($input_id)] = RGFormsModel::prepare_value($form, $field, $val, $input_name, $this->entry['id']);
                         }
                     } else {
                         $input_name = 'input_' . str_replace('.', '_', $field_id);
                         $this->entry[strval($field_id)] = RGFormsModel::prepare_value($form, $field, $value, $input_name, $this->entry['id']);
                     }
                     break;
                 case 'post_custom_field':
                     $input_type = RGFormsModel::get_input_type($field);
                     $custom_field_name = $field_array['postCustomFieldName'];
                     // Only certain custom field types are supported
                     if (!in_array($input_type, array('list', 'fileupload'))) {
                         update_post_meta($post_id, $custom_field_name, $value);
                     }
                     break;
                 case 'post_image':
                     $value = '';
                     break;
             }
             //ignore fields that have not changed
             if ($value === rgget((string) $field_id, $this->entry)) {
                 continue;
             }
             // update entry
             if ('post_category' !== $field->type) {
                 $this->entry[strval($field_id)] = $value;
             }
             $update_entry = true;
         }
     }
     if ($update_entry) {
         $return_entry = GFAPI::update_entry($this->entry);
         if (is_wp_error($return_entry)) {
             do_action('gravityview_log_error', 'Updating the entry post fields failed', $return_entry);
         } else {
             do_action('gravityview_log_debug', 'Updating the entry post fields for post #' . $post_id . ' succeeded');
         }
     }
     $return_post = wp_update_post($updated_post, true);
     if (is_wp_error($return_post)) {
         do_action('gravityview_log_error', 'Updating the post content failed', $return_post);
     } else {
         do_action('gravityview_log_debug', 'Updating the post content for post #' . $post_id . ' succeeded');
     }
 }
Example #18
0
        die;
    } elseif (!empty($_GET['tag']) || !empty($_GET['replace_tags'])) {
        $tags = $_GET['tags'];
        foreach ((array) $_GET['ids'] as $id) {
            $id = intval($id);
            $append = empty($_GET['replace_tags']);
            wp_set_post_tags($id, $tags, $append);
        }
        wp_redirect(get_option('siteurl') . "/wp-admin/edit.php?page=batch_categories&done=tag&what={$tags}&num={$num}{$query}");
        die;
    } elseif (!empty($_GET['untag'])) {
        $tags = explode(',', $_GET['tags']);
        foreach ((array) $_GET['ids'] as $id) {
            $id = intval($id);
            $existing = wp_get_post_tags($id);
            $new = array();
            foreach ((array) $existing as $_tag) {
                foreach ((array) $tags as $tag) {
                    if ($_tag->name != $tag) {
                        $new[] = $_tag->name;
                    }
                }
            }
            wp_set_post_tags($id, $new);
        }
        $tags = join(', ', $tags);
        wp_redirect(get_option('siteurl') . "/wp-admin/edit.php?page=batch_categories&done=untag&what={$tags}&num={$num}{$query}");
        die;
    }
}
die("Invalid action.");
 /**
  * function to map the csv file and process it
  *
  * @return boolean
  */
 function processDataInWP($data_rows, $ret_array, $session_arr, $currentLimit, $extractedimagelocation, $importinlineimageoption, $sample_inlineimage_url = null)
 {
     global $wpdb;
     $post_id = '';
     $new_post = array();
     $smack_taxo = array();
     $custom_array = array();
     $seo_custom_array = array();
     $imported_feature_img = array();
     $headr_count = $ret_array['h2'];
     //for ($i = 0; $i < count($data_rows); $i++) {
     for ($i = 0; $i <= $ret_array['basic_count']; $i++) {
         if (array_key_exists('coremapping' . $i, $ret_array)) {
             if ($ret_array['coretextbox' . $i] != '-- Select --' && $ret_array['coremapping' . $i] != '') {
                 $mappedindex = str_replace('textbox', '', $ret_array['coretextbox' . $i]);
                 $new_post[$ret_array['coremapping' . $i]] = $data_rows[$mappedindex];
                 $custom_array[$ret_array['coremapping' . $i]] = $data_rows[$mappedindex];
             }
         } else {
             if (array_key_exists('mapping' . $i, $ret_array)) {
                 if ($ret_array['mapping' . $i] != '-- Select --') {
                     if ($ret_array['mapping' . $i] != 'add_custom' . $i) {
                         $strip_CF = strpos($ret_array['mapping' . $i], 'CF: ');
                         $strip_SEO = strpos($ret_array['mapping' . $i], 'SEO: ');
                         if ($strip_CF === 0) {
                             $custom_key = substr($ret_array['mapping' . $i], 4);
                             $custom_array[$custom_key] = $data_rows[$i];
                         } elseif ($strip_SEO === 0) {
                             $seo_key = substr($ret_array['mapping' . $i], 5);
                             $seo_custom_array[$seo_key] = $data_rows[$i];
                         } else {
                             $new_post[$ret_array['mapping' . $i]] = $data_rows[$i];
                         }
                     } else {
                         $new_post[$ret_array['textbox' . $i]] = $data_rows[$i];
                         $custom_array[$ret_array['textbox' . $i]] = $data_rows[$i];
                     }
                 }
             }
         }
     }
     /*		for($j = 0; $j< $ret_array['corecustomcount'];j++){	
     			if(array_key_exists('coremapping' . $i,$ret_array)){
                                     echo '<pre>';print_r($ret_array['coretextbox' . $i]);echo '</pre>';
                                     if($ret_array['coretextbox' . $i] != '-- Select --'){
                                             $mappedindex = str_replace('textbox','',$ret_array['coretextbox'.$i]);
                                             echo '<pre>';print_r($mappedindex);echo '</pre>';die;
                                             //$new_post[$ret_array['coretextbox'.$i]] = $data_rows[];
                                             //$custom_array[$ret_array['coremapping'.$i]] = $data_rows[$i];
                                     }
                             }
     		}*/
     for ($inc = 0; $inc < count($data_rows); $inc++) {
         foreach ($this->keys as $k => $v) {
             if (array_key_exists($v, $new_post)) {
                 $custom_array[$v] = $new_post[$v];
             }
         }
     }
     if (is_array($new_post)) {
         foreach ($new_post as $ckey => $cval) {
             $this->postFlag = true;
             $taxo = get_taxonomies();
             foreach ($taxo as $taxokey => $taxovalue) {
                 if ($taxokey != 'category' && $taxokey != 'link_category' && $taxokey != 'post_tag' && $taxokey != 'nav_menu' && $taxokey != 'post_format') {
                     if ($taxokey == $ckey) {
                         $smack_taxo[$ckey] = $new_post[$ckey];
                     }
                 }
             }
             $taxo_check = 0;
             if (!isset($smack_taxo[$ckey])) {
                 $smack_taxo[$ckey] = null;
                 $taxo_check = 1;
             }
             if ($ckey != 'post_category' && $ckey != 'post_tag' && $ckey != 'featured_image' && $ckey != $smack_taxo[$ckey] && $ckey != 'wp_page_template') {
                 if ($taxo_check == 1) {
                     unset($smack_taxo[$ckey]);
                     $taxo_check = 0;
                 }
                 if (array_key_exists($ckey, $custom_array)) {
                     $darray[$ckey] = $new_post[$ckey];
                 } else {
                     if (array_key_exists($ckey, $smack_taxo)) {
                         $data_array[$ckey] = null;
                     } else {
                         $data_array[$ckey] = $new_post[$ckey];
                     }
                 }
             } else {
                 switch ($ckey) {
                     case 'post_tag':
                         $tags[$ckey] = $new_post[$ckey];
                         break;
                     case 'post_category':
                         $categories[$ckey] = $new_post[$ckey];
                         break;
                     case 'wp_page_template':
                         $custom_array['_wp_page_template'] = $new_post[$ckey];
                         break;
                     case 'featured_image':
                         require_once ABSPATH . "wp-includes/pluggable.php";
                         require_once ABSPATH . 'wp-admin/includes/image.php';
                         $dir = wp_upload_dir();
                         $get_media_settings = get_option('uploads_use_yearmonth_folders');
                         if ($get_media_settings == 1) {
                             $dirname = date('Y') . '/' . date('m');
                             $full_path = $dir['basedir'] . '/' . $dirname;
                             $baseurl = $dir['baseurl'] . '/' . $dirname;
                         } else {
                             $full_path = $dir['basedir'];
                             $baseurl = $dir['baseurl'];
                         }
                         $f_img = $new_post[$ckey];
                         $fimg_path = $full_path;
                         $fimg_name = @basename($f_img);
                         $featured_image = $fimg_name;
                         $fimg_name = strtolower(str_replace(' ', '-', $fimg_name));
                         $fimg_name = preg_replace('/[^a-zA-Z0-9._\\s]/', '', $fimg_name);
                         $fimg_name = urlencode($fimg_name);
                         $parseURL = parse_url($f_img);
                         $path_parts = pathinfo($f_img);
                         if (!isset($path_parts['extension'])) {
                             $fimg_name = $fimg_name . '.jpg';
                         }
                         //else
                         //	$fimg_name = $fimg_name.'.'.$path_parts['extension'];
                         $f_img_slug = '';
                         $f_img_slug = strtolower(str_replace('', '-', $f_img_slug));
                         $f_img_slug = preg_replace('/[^a-zA-Z0-9._\\s]/', '', $f_img_slug);
                         $post_slug_value = strtolower($f_img_slug);
                         if (array_key_exists('extension', $path_parts)) {
                             //$fimg_name = wp_unique_filename($fimg_path, $fimg_name, $path_parts['extension']);
                         }
                         $this->get_fimg_from_URL($f_img, $fimg_path, $fimg_name, $post_slug_value, $currentLimit, $this);
                         $filepath = $fimg_path . "/" . $fimg_name;
                         if (@getimagesize($filepath)) {
                             $img = wp_get_image_editor($filepath);
                             /*if (!is_wp_error($img)) {
                             			$sizes_array = array(
                             					// #1 - resizes to 1024x768 pixel, square-cropped image
                             					array('width' => 1024, 'height' => 768, 'crop' => true),
                             					// #2 - resizes to 100px max width/height, non-cropped image
                             					array('width' => 100, 'height' => 100, 'crop' => false),
                             					// #3 - resizes to 100 pixel max height, non-cropped image
                             					array('width' => 300, 'height' => 100, 'crop' => false),
                             					// #3 - resizes to 624x468 pixel max width, non-cropped image
                             					array('width' => 624, 'height' => 468, 'crop' => false)
                             					);
                             			$resize = $img->multi_resize($sizes_array);
                             		}*/
                             $file['guid'] = $baseurl . "/" . $fimg_name;
                             $file['post_title'] = $fimg_name;
                             $file['post_content'] = '';
                             $file['post_status'] = 'attachment';
                         } else {
                             $file = false;
                         }
                         break;
                 }
             }
         }
     }
     if ($_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['selectedImporter'] != 'custompost') {
         $data_array['post_type'] = $_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['selectedImporter'];
     } else {
         $data_array['post_type'] = $_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['custompostlist'];
     }
     if ($this->titleDupCheck == 'true') {
         $this->postFlag = $this->duplicateChecks('title', $data_array['post_title'], $data_array['post_type'], $currentLimit, $data_array['post_title']);
     }
     if ($this->conDupCheck == 'true' && $this->postFlag) {
         $this->postFlag = $this->duplicateChecks('content', $data_array['post_content'], $data_array['post_type'], $currentLimit, $data_array['post_title']);
     }
     if ($this->titleDupCheck == 'true' && $this->conDupCheck == 'true') {
         $this->postFlag = $this->duplicateChecks('title && content', $data_array['post_content'], $data_array['post_type'], $currentLimit, $data_array['post_title']);
     }
     if ($this->postFlag) {
         unset($sticky);
         if (empty($data_array['post_status'])) {
             $data_array['post_status'] = null;
         }
         if ($_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['importallwithps'] != 0) {
             $data_array['post_status'] = $_SESSION['SMACK_MAPPING_SETTINGS_VALUES']['importallwithps'];
         }
         switch ($data_array['post_status']) {
             case 1:
                 $data_array['post_status'] = 'publish';
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('publish', 'wp-ultimate-csv-importer');
                 break;
             case 2:
                 $data_array['post_status'] = 'publish';
                 $sticky = true;
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('sticky', 'wp-ultimate-csv-importer');
                 break;
             case 3:
                 $data_array['post_status'] = 'publish';
                 $data_array['post_password'] = $_POST['postsPassword'];
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $data_array['post_password'];
                 break;
             case 4:
                 $data_array['post_status'] = 'private';
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('private', 'wp-ultimate-csv-importer');
                 break;
             case 5:
                 $data_array['post_status'] = 'draft';
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('draft', 'wp-ultimate-csv-importer');
                 break;
             case 6:
                 $data_array['post_status'] = 'pending';
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('pending', 'wp-ultimate-csv-importer');
                 break;
             default:
                 $poststatus = $data_array['post_status'] = strtolower($data_array['post_status']);
                 if ($data_array['post_status'] != 'publish' && $data_array['post_status'] != 'private' && $data_array['post_status'] != 'draft' && $data_array['post_status'] != 'pending' && $data_array['post_status'] != 'sticky') {
                     $stripPSF = strpos($data_array['post_status'], '{');
                     if ($stripPSF === 0) {
                         $poststatus = substr($data_array['post_status'], 1);
                         $stripPSL = substr($poststatus, -1);
                         if ($stripPSL == '}') {
                             $postpwd = substr($poststatus, 0, -1);
                             $data_array['post_status'] = 'publish';
                             $data_array['post_password'] = $postpwd;
                             $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $data_array['post_password'];
                         } else {
                             $data_array['post_status'] = 'publish';
                             $data_array['post_password'] = $poststatus;
                             $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $data_array['post_password'];
                         }
                     } else {
                         $data_array['post_status'] = 'publish';
                         $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('publish', 'wp-ultimate-csv-importer');
                     }
                 }
                 if ($data_array['post_status'] == 'sticky') {
                     $data_array['post_status'] = 'publish';
                     $sticky = true;
                     $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('sticky', 'wp-ultimate-csv-importer');
                 } else {
                     $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . $data_array['post_status'];
                 }
         }
         // Post Format Options
         if (isset($data_array['post_format'])) {
             $post_format = 0;
             switch ($data_array['post_format']) {
                 case 1:
                     $post_format = 'post-format-aside';
                     break;
                 case 2:
                     $post_format = 'post-format-image';
                     break;
                 case 3:
                     $post_format = 'post-format-video';
                     break;
                 case 4:
                     $post_format = 'post-format-audio';
                     break;
                 case 5:
                     $post_format = 'post-format-quote';
                     break;
                 case 6:
                     $post_format = 'post-format-link';
                     break;
                 case 7:
                     $post_format = 'post-format-gallery';
                     break;
                 default:
                     if ($data_array['post_format'] == 'post-format-aside') {
                         $post_format = 'post-format-aside';
                         break;
                     }
                     if ($data_array['post_format'] == 'post-format-image') {
                         $post_format = 'post-format-image';
                         break;
                     }
                     if ($data_array['post_format'] == 'post-format-video') {
                         $post_format = 'post-format-video';
                         break;
                     }
                     if ($data_array['post_format'] == 'post-format-audio') {
                         $post_format = 'post-format-audio';
                         break;
                     }
                     if ($data_array['post_format'] == 'post-format-quote') {
                         $post_format = 'post-format-quote';
                         break;
                     }
                     if ($data_array['post_format'] == 'post-format-link') {
                         $post_format = 'post-format-link';
                         break;
                     }
                     if ($data_array['post_format'] == 'post-format-gallery') {
                         $post_format = 'post-format-gallery';
                         break;
                     }
                     $post_format = 0;
             }
         }
         // Author name/id update
         if (isset($data_array['post_author'])) {
             $authorLen = strlen($data_array['post_author']);
             $postuserid = $data_array['post_author'];
             $checkpostuserid = intval($data_array['post_author']);
             $postAuthorLen = strlen($checkpostuserid);
             $postauthor = array();
             if ($authorLen == $postAuthorLen) {
                 $postauthor = $wpdb->get_results("select ID,user_login from {$wpdb->users} where ID = \"{$postuserid}\"");
                 if (empty($postauthor) || !$postauthor[0]->ID) {
                     // If user name are numeric Ex: 1300001
                     $postauthor = $wpdb->get_results("select ID,user_login from {$wpdb->users} where user_login = \"{$postuserid}\"");
                 }
             } else {
                 $postauthor = $wpdb->get_results("select ID,user_login from {$wpdb->users} where user_login = \"{$postuserid}\"");
             }
             if (empty($postauthor) || !$postauthor[0]->ID) {
                 $data_array['post_author'] = 1;
                 $admindet = $wpdb->get_results("select ID,user_login from {$wpdb->users} where ID = 1");
                 $this->detailedLog[$currentLimit]['assigned_author'] = "<b>" . __('Author - not found (assigned to', 'wp-ultimate-csv-importer') . " </b>" . $admindet[0]->user_login . ")";
                 $this->noPostAuthCount++;
             } else {
                 $data_array['post_author'] = $postauthor[0]->ID;
                 $this->detailedLog[$currentLimit]['assigned_author'] = "<b>" . __('Author', 'wp-ultimate-csv-importer') . " - </b>" . $postauthor[0]->user_login;
             }
         } else {
             $data_array['post_author'] = 1;
             $admindet = $wpdb->get_results("select ID,user_login from {$wpdb->users} where ID = 1");
             $this->detailedLog[$currentLimit]['assigned_author'] = "<b>" . __('Author - not found (assigned to', 'wp-ultimate-csv-importer') . " </b>" . $admindet[0]->user_login . ")";
             $this->noPostAuthCount++;
         }
         // Date format post
         $data_array['post_date'] = str_replace('/', '-', $data_array['post_date']);
         if (!isset($data_array['post_date'])) {
             $data_array['post_date'] = date('Y-m-d H:i:s');
             $this->detailedLog[$currentLimit]['postdate'] = "<b>" . __('Date', 'wp-ultimate-csv-importer') . " - </b>" . $data_array['post_date'];
         } else {
             $data_array['post_date'] = date('Y-m-d H:i:s', strtotime($data_array['post_date']));
             $this->detailedLog[$currentLimit]['postdate'] = "<b>" . __('Date', 'wp-ultimate-csv-importer') . " - </b>" . $data_array['post_date'];
         }
         if (isset($data_array['post_slug'])) {
             $data_array['post_name'] = $data_array['post_slug'];
         }
         //add global password
         if ($data_array) {
             if ($ret_array['importallwithps'] == 3) {
                 $data_array['post_password'] = $ret_array['globalpassword_txt'];
                 $this->detailedLog[$currentLimit]['poststatus'] = "<b>" . __('Status', 'wp-ultimate-csv-importer') . " - </b>" . __('protected with password', 'wp-ultimate-csv-importer') . $ret_array['globalpassword_txt'];
             }
         }
         if ($data_array) {
             if ($this->MultiImages == 'true') {
                 // Inline image import feature by fredrick marks
                 $inlineImagesObj = new WPImporter_inlineImages();
                 $postid = wp_insert_post($data_array);
                 $post_id = $inlineImagesObj->importwithInlineImages($postid, $currentLimit, $data_array, $this, $importinlineimageoption, $extractedimagelocation, $sample_inlineimage_url);
                 //	$inline_shortcode = $inlineImagesObj->capture_all_shortcodes($data_array['post_content']);
             } else {
                 $post_id = wp_insert_post($data_array);
                 $this->detailedLog[$currentLimit]['post_id'] = "<b>" . __('Created Post_ID', 'wp-ultimate-csv-importer') . " - </b>" . $post_id . " - success";
             }
         }
         unset($postauthor);
         if ($post_id) {
             $uploaded_file_name = $session_arr['uploadedFile'];
             $real_file_name = $session_arr['uploaded_csv_name'];
             //                                $version = $session_arr['currentfileversion'];
             $action = $data_array['post_type'];
             /*				$version_arr=array();
             						$version_arr=explode("(",$uploaded_file_name);
             						$version_arr=explode(")",$version_arr[1]);
             						$version=$version_arr[0]; */
             $get_imported_feature_image = array();
             $get_imported_feature_image = get_option('IMPORTED_FEATURE_IMAGES');
             if (is_array($get_imported_feature_image)) {
                 $imported_feature_img = array_merge($get_imported_feature_image, $imported_feature_img);
             } else {
                 $imported_feature_img = $imported_feature_img;
             }
             update_option('IMPORTED_FEATURE_IMAGES', $imported_feature_img);
             $created_records[$action][] = $post_id;
             if ($action == 'post') {
                 $imported_as = 'Post';
             }
             if ($action == 'page') {
                 $imported_as = 'Page';
             }
             if ($action != 'post' && $action != 'page') {
                 $imported_as = 'Custom Post';
             }
             $keyword = $action;
             $this->insPostCount++;
             if (isset($sticky) && $sticky) {
                 stick_post($post_id);
             }
             if (!empty($custom_array)) {
                 foreach ($custom_array as $custom_key => $custom_value) {
                     update_post_meta($post_id, $custom_key, $custom_value);
                 }
             }
             // Import post formats added by fredrick marks
             if (isset($post_format)) {
                 wp_set_object_terms($post_id, $post_format, 'post_format');
             }
             //Import SEO Values
             if (!empty($seo_custom_array)) {
                 $this->importSEOfields($seo_custom_array, $post_id);
             }
             // Create custom taxonomy to post
             if (!empty($smack_taxo)) {
                 foreach ($smack_taxo as $taxo_key => $taxo_value) {
                     if (!empty($taxo_value)) {
                         $split_line = explode('|', $taxo_value);
                         wp_set_object_terms($post_id, $split_line, $taxo_key);
                     }
                 }
             }
             // Create/Add tags to post
             if (!empty($tags)) {
                 $this->detailedLog[$currentLimit]['tags'] = "";
                 foreach ($tags as $tag_key => $tag_value) {
                     $this->detailedLog[$currentLimit]['tags'] .= $tag_value . "|";
                     wp_set_post_tags($post_id, $tag_value);
                 }
                 $this->detailedLog[$currentLimit]['tags'] = "<b>" . __('Tags', 'wp-ultimate-csv-importer') . " - </b>" . substr($this->detailedLog[$currentLimit]['tags'], 0, -1);
             }
             // Create/Add category to post
             if (!empty($categories)) {
                 $this->detailedLog[$currentLimit]['category'] = "";
                 $assigned_categories = array();
                 $split_cate = explode('|', $categories['post_category']);
                 foreach ($split_cate as $key => $val) {
                     if (is_numeric($val)) {
                         $split_cate[$key] = 'uncategorized';
                         $assigned_categories['uncategorized'] = 'uncategorized';
                     }
                     $assigned_categories[$val] = $val;
                 }
                 foreach ($assigned_categories as $cateKey => $cateVal) {
                     $this->detailedLog[$currentLimit]['category'] .= $cateKey . "|";
                 }
                 $this->detailedLog[$currentLimit]['category'] = "<b>" . __('Category', 'wp-ultimate-csv-importer') . " - </b>" . substr($this->detailedLog[$currentLimit]['category'], 0, -1);
                 wp_set_object_terms($post_id, $split_cate, 'category');
             }
             // Add featured image
             if (!empty($file)) {
                 //$wp_filetype = wp_check_filetype(@basename($file ['guid']), null);
                 $wp_upload_dir = wp_upload_dir();
                 $attachment = array('guid' => $file['guid'], 'post_mime_type' => 'image/jpeg', 'post_title' => preg_replace('/[^a-zA-Z0-9._\\s]/', '', @basename($file['guid'])), 'post_content' => '', 'post_status' => 'inherit');
                 if ($get_media_settings == 1) {
                     $generate_attachment = $dirname . '/' . $fimg_name;
                 } else {
                     $generate_attachment = $fimg_name;
                 }
                 $uploadedImage = $wp_upload_dir['path'] . '/' . $fimg_name;
                 /*$attach_id = wp_insert_attachment($attachment, $generate_attachment, $post_id);
                 		$attach_data = wp_generate_attachment_metadata($attach_id, $uploadedImage);
                 		wp_update_attachment_metadata($attach_id, $attach_data);*/
                 $existing_attachment = array();
                 $query = $wpdb->get_results("select post_title from {$wpdb->posts} where post_type = 'attachment' and post_mime_type = 'image/jpeg'");
                 foreach ($query as $key) {
                     $existing_attachment[] = $key->post_title;
                 }
                 if (!in_array($fimg_name, $existing_attachment)) {
                     $attach_id = wp_insert_attachment($attachment, $generate_attachment, $post_id);
                     $attach_data = wp_generate_attachment_metadata($attach_id, $uploadedImage);
                     wp_update_attachment_metadata($attach_id, $attach_data);
                 } else {
                     $query2 = $wpdb->get_results("select ID from {$wpdb->posts} where post_title = '{$fimg_name}' and post_type = 'attachment'");
                     foreach ($query2 as $key2) {
                         $attach_id = $key2->ID;
                     }
                 }
                 set_post_thumbnail($post_id, $attach_id);
             }
         } else {
             $skippedRecords[] = $_SESSION['SMACK_SKIPPED_RECORDS'];
         }
         $this->detailedLog[$currentLimit]['verify_here'] = "<b>Verify Here -</b> <a href='" . get_permalink($post_id) . "' title='" . esc_attr(sprintf(__('View &#8220;%s&#8221;'), $data_array['post_title'])) . "' rel='permalink' target='_blank'>" . __('Web View', 'wp-ultimate-csv-importer') . "</a> | <a href='" . get_edit_post_link($post_id, true) . "' title='" . esc_attr(__('Edit this item', 'wp-ultimate-csv-importer')) . "' target='_blank'>" . __('Admin View', 'wp-ultimate-csv-importer') . "</a>";
     }
     unset($data_array);
 }
Example #20
0
function linkmarklet_post()
{
    global $linkmarklet_debug;
    $settings = get_option(LINKMARKLET_PREFIX . 'settings');
    // set our time (if applicable)
    $timeframe_min = !isset($settings['future_publish']['min']) || $settings['future_publish']['min'] === '' ? false : intval($settings['future_publish']['min']);
    $timeframe_max = !isset($settings['future_publish']['max']) || $settings['future_publish']['max'] === '' ? false : intval($settings['future_publish']['max']);
    $publish_start = !isset($settings['future_publish']['start']) || $settings['future_publish']['start'] === '' ? false : intval($settings['future_publish']['start']);
    $publish_end = !isset($settings['future_publish']['end']) || $settings['future_publish']['end'] === '' ? false : intval($settings['future_publish']['end']);
    // by default it'll be right now
    $timestamp = (int) current_time('timestamp');
    $timestamp_gmt = (int) current_time('timestamp', 1);
    if ($linkmarklet_debug) {
        error_log('$timestamp (source) = ' . $timestamp . ' ' . date('Y-m-d H:i:s', $timestamp));
        error_log('$timestamp_gmt (source) = ' . $timestamp_gmt . ' ' . date('Y-m-d H:i:s', $timestamp_gmt));
    }
    $future_publish = false;
    // check to see if we need to bump our publish time
    if ($timeframe_min !== false && $timeframe_max !== false) {
        // set the post date
        if ($linkmarklet_debug) {
            error_log('trigger: timeframe');
        }
        // figure out our start time which is either right now, or the future-most post
        $args = array('numberposts' => 1, 'post_status' => array('publish', 'pending', 'future'));
        $posts_array = get_posts($args);
        // if there are any posts, we can check it out
        $post_timestamp = false;
        if ($posts_array) {
            if ($linkmarklet_debug) {
                error_log('found post');
            }
            foreach ($posts_array as $post) {
                setup_postdata($post);
                $post_timestamp = strtotime($post->post_date);
                // local time
                $post_timestamp_gmt = strtotime($post->post_date_gmt);
                if ($linkmarklet_debug) {
                    error_log(print_r($post, true));
                    error_log('======================');
                }
            }
            if ($linkmarklet_debug) {
                error_log('$post_timestamp = ' . $post_timestamp . ' ' . date('Y-m-d H:i:s', $post_timestamp));
                error_log('$timestamp = ' . $timestamp . ' ' . date('Y-m-d H:i:s', $timestamp));
            }
        }
        // get the future-most timestamp and use that
        if ($post_timestamp + $timeframe_min * 60 > $timestamp) {
            // $timestamp is still now() in local time
            $future_publish = true;
            if ($linkmarklet_debug) {
                error_log('FUTURE PUBLISH');
            }
            // our timestamps need to be adjusted
            $timestamp = $post_timestamp;
            $timestamp_gmt = $post_timestamp_gmt;
            if ($linkmarklet_debug) {
                error_log('$timestamp (before 1) = ' . $timestamp . ' ' . date('Y-m-d H:i:s', $timestamp));
                error_log('$timestamp_gmt (before 1) = ' . $timestamp_gmt . ' ' . date('Y-m-d H:i:s', $timestamp_gmt));
            }
            // determine how many seconds we'll offset
            $offset = rand($timeframe_min * 60, $timeframe_max * 60);
            if ($linkmarklet_debug) {
                error_log('$offset (in seconds) = ' . $offset);
            }
            // the post is scheduled so we need to offset both
            $timestamp = $timestamp + $offset;
            $timestamp_gmt = $timestamp_gmt + $offset;
            if ($linkmarklet_debug) {
                error_log('$timestamp (after) = ' . $timestamp . ' ' . date('Y-m-d H:i:s', $timestamp));
                error_log('$timestamp_gmt (after) = ' . $timestamp_gmt . ' ' . date('Y-m-d H:i:s', $timestamp_gmt));
                error_log('NEW FUTURE PUBLISH TIME: ' . date('Y-m-d H:i:s', $timestamp));
            }
        }
    }
    // we need to check to see if we're within the posting window (if set)
    if ($publish_start !== false && $publish_end !== false) {
        if ($linkmarklet_debug) {
            error_log('checking publish window...');
        }
        // our publish window needs to be put within today's context
        $publish_start = date('U', strtotime(date('Y-m-d') . ' ' . $publish_start . ':00:00'));
        $publish_end = date('U', strtotime(date('Y-m-d') . ' ' . $publish_end . ':00:00'));
        if ($linkmarklet_debug) {
            error_log('window: ' . $publish_start . ' - ' . $publish_end);
        }
        // check to see if we're too early
        if ($timestamp < $publish_start) {
            if ($linkmarklet_debug) {
                error_log('too early');
            }
            $future_publish = true;
            $timestamp = $publish_start;
            $timestamp_gmt = $publish_start - get_option('gmt_offset') * HOUR_IN_SECONDS;
            if ($linkmarklet_debug) {
                error_log('$timestamp (after) = ' . $timestamp . ' ' . date('Y-m-d H:i:s', $timestamp));
                error_log('$timestamp_gmt (after) = ' . $timestamp_gmt . ' ' . date('Y-m-d H:i:s', $timestamp_gmt));
            }
        }
        // check to see if we're too late
        if ($timestamp > $publish_end) {
            if ($linkmarklet_debug) {
                error_log('too late');
            }
            // need to push it to tomorrow's start time
            $future_publish = true;
            $timestamp = $publish_start + 24 * 60 * 60;
            $timestamp_gmt = $publish_start + 24 * 60 * 60 - get_option('gmt_offset') * HOUR_IN_SECONDS;
            if ($linkmarklet_debug) {
                error_log('$timestamp (after) = ' . $timestamp . ' ' . date('Y-m-d H:i:s', $timestamp));
                error_log('$timestamp_gmt (after) = ' . $timestamp_gmt . ' ' . date('Y-m-d H:i:s', $timestamp_gmt));
            }
        }
    }
    $settings = get_option(LINKMARKLET_PREFIX . 'settings');
    $post = get_default_post_to_edit();
    $post = get_object_vars($post);
    $post_ID = $post['ID'] = intval($_POST['post_id']);
    if (!current_user_can('edit_post', $post_ID)) {
        wp_die(__('You are not allowed to edit this post.'));
    }
    // set our category
    $post['post_category'] = !empty($settings['category']) ? intval($settings['category']) : 0;
    // set our post properties
    $post['post_title'] = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : '';
    $content = isset($_POST['content']) ? $_POST['content'] : '';
    // Markdown on Save?
    if (is_plugin_active('markdown-on-save/markdown-on-save.php') && !empty($settings['markdown'])) {
        // we need to set up our post data to tell Markdown on Save we want to use it
        $post['cws_using_markdown'] = 1;
        $post['_cws_markdown_nonce'] = wp_create_nonce('cws-markdown-save');
    }
    // see if we need to process any images
    $images = array();
    // $markdown_pattern = "/(!\\[(.*?)\\]\\s?\\([ \\n]*(?:<(\\S*)>|(.*?))[ \\n]*(([\\'\"])(.*?)\\6[ \\n]*)?\\))/ui";
    $markdown_pattern = "/(!\\[(.*?)\\]\\s?\\([ \\n]*(?:<(\\S*)>|(.*?))[ \\n]*?\\))/ui";
    preg_match_all($markdown_pattern, $content, $images);
    $upload = false;
    if (isset($images[4]) && !empty($images[4]) && current_user_can('upload_files')) {
        if ($linkmarklet_debug) {
            error_log('attempting sideload');
        }
        foreach ($images[4] as $key => $image) {
            // see if files exist in content - we don't want to upload non-used selected files.
            if (strpos($content, htmlspecialchars($image)) !== false) {
                if ($linkmarklet_debug) {
                    error_log('image: ' . $image);
                }
                $upload = media_sideload_image($image, $post_ID, '');
                if (!is_wp_error($upload)) {
                    // we only want to strip out the URL at this point so we need just the URL of the upload
                    $new_image = array();
                    preg_match("~https?://.*/(.*?).(jpe?g|gif|png)~ui", $upload, $new_image);
                    if (!empty($new_image[0])) {
                        $url = esc_url($_POST['url']);
                        if (is_plugin_active('markdown-on-save/markdown-on-save.php') && !empty($settings['markdown'])) {
                            $hosted_image_final = str_replace($image, $new_image[0], $images[0][$key]);
                        } else {
                            $hosted_image_final = '<img src="' . esc_url($new_image[0]) . '" alt="' . esc_attr($images[2][$key]) . '" />';
                        }
                        $hosted_image = '<a href="' . esc_url($url) . '">' . $hosted_image_final . '</a>';
                        // swap out the ORIGINAL (offsite) Markdown with our linked, hosted version
                        $content = str_replace($images[0][$key], $hosted_image, $content);
                        if ($linkmarklet_debug) {
                            error_log('upload: ' . $new_image[0]);
                        }
                    }
                }
            }
        }
    }
    // set the post_content and status
    $post['post_content'] = wp_kses_post($content);
    $post['post_status'] = 'draft';
    // set our post format
    if (isset($settings['post_format'])) {
        if (current_theme_supports('post-formats', $settings['post_format'])) {
            set_post_format($post_ID, $settings['post_format']);
        } else {
            set_post_format($post_ID, false);
        }
    }
    // set the category
    $post['post_category'] = array_map('absint', array($post['post_category']));
    // set the slug
    $post['post_name'] = sanitize_title($_POST['slug']);
    // update what we've set
    $post_ID = wp_update_post($post);
    // we also need to add our custom field link
    $custom_field = isset($settings['custom_field']) ? sanitize_key($settings['custom_field']) : false;
    if (!empty($custom_field)) {
        update_post_meta($post_ID, $custom_field, esc_url($_POST['url']));
    }
    // set our post tags if applicable
    if (!empty($settings['support_tags']) && !empty($_POST['tags'])) {
        wp_set_post_tags($post_ID, $_POST['tags']);
    }
    // mark as published if that's the intention
    if (isset($_POST['publish']) && current_user_can('publish_posts')) {
        if ($future_publish) {
            $post['post_status'] = 'future';
            if ($linkmarklet_debug) {
                error_log('*** altering timestamps');
            }
            $post['edit_date'] = date('Y-m-d H:i:s', $timestamp);
            $post['post_date'] = date('Y-m-d H:i:s', $timestamp);
            $post['post_date_gmt'] = date('Y-m-d H:i:s', $timestamp_gmt);
            if ($linkmarklet_debug) {
                error_log(print_r($post, true));
                error_log('======================');
            }
        } else {
            $post['post_status'] = 'publish';
        }
    }
    // our final update
    $post_ID = wp_update_post($post);
    return $post_ID;
}
Example #21
0
 function save_post()
 {
     check_ajax_referer('ajaxnonce', '_inline_edit');
     if (!is_user_logged_in()) {
         die('<p>' . __('Error: not logged in.', 'p2') . '</p>');
     }
     $post_id = $_POST['post_ID'];
     $post_id = substr($post_id, strpos($post_id, '-') + 1);
     if (!current_user_can('edit_post', $post_id)) {
         die('<p>' . __('Error: not allowed to edit post.', 'p2') . '</p>');
     }
     $categories = get_the_category($post_id);
     $category_slug = isset($categories[0]) ? $categories[0]->slug : '';
     $new_post_content = $_POST['content'];
     $new_post_content = p2_list_creator($new_post_content);
     /* Add the quote citation to the content if it exists */
     if (!empty($_POST['citation']) && 'quote' == $category_slug) {
         $new_post_content = '<p>' . $new_post_content . '</p><cite>' . $_POST['citation'] . '</cite>';
     }
     $new_tags = $_POST['tags'];
     $new_post_title = isset($_POST['title']) ? $_POST['title'] : '';
     if (!empty($new_post_title)) {
         $post_title = $new_post_title;
     } else {
         $post_title = p2_title_from_content($new_post_content);
     }
     $post = wp_update_post(array('post_title' => $post_title, 'post_content' => $new_post_content, 'post_modified' => current_time('mysql'), 'post_modified_gmt' => current_time('mysql', 1), 'ID' => $post_id));
     $tags = wp_set_post_tags($post_id, $new_tags);
     $post = get_post($post);
     if (!$post) {
         die('-1');
     }
     if ('quote' == $category_slug) {
         $content = apply_filters('p2_get_quote_content', $post->post_content);
     } else {
         $content = apply_filters('the_content', $post->post_content);
     }
     echo json_encode(array('title' => $post->post_title, 'content' => $content, 'tags' => get_tags_with_count($post, '', __('<br />Tags:', 'p2') . ' ', ', ', ' &nbsp;')));
 }
Example #22
0
/**
 * save popular search terms as tags in monthly basis
 **/
function pk_stt2_function_save_tags()
{
    if ('1' == get_option('pk_stt2_auto_tag') && !empty($post->ID)) {
        $day_diff = ceil((strtotime(date('F j, Y')) - strtotime(get_post_meta($id, 'stt2_update_tags', true)) + 1) / (60 * 60 * 24));
        if (30 < $day_diff) {
            global $post;
            $tags = pk_stt2_db_get_popular_tags($post->ID);
            wp_set_post_tags($post->ID, $tags, true);
            update_post_meta($post->ID, 'stt2_update_tags', date('F j, Y'));
        }
    }
}
Example #23
0
 function do_tweet_post($tweet)
 {
     global $wpdb;
     remove_action('publish_post', 'aktt_notify_twitter', 99);
     $data = array('post_content' => $wpdb->escape(aktt_make_clickable($tweet->tw_text)), 'post_title' => $wpdb->escape(trim_add_elipsis($tweet->tw_text, 30)), 'post_date' => get_date_from_gmt(date('Y-m-d H:i:s', $tweet->tw_created_at)), 'post_category' => array($this->blog_post_category), 'post_status' => 'publish', 'post_author' => $wpdb->escape($this->blog_post_author));
     $data = apply_filters('aktt_do_tweet_post', $data, $tweet);
     // return false here to not make a blog post
     if (!$data) {
         return;
     }
     $post_id = wp_insert_post($data);
     add_post_meta($post_id, 'aktt_twitter_id', $tweet->tw_id, true);
     wp_set_post_tags($post_id, $this->blog_post_tags);
     add_action('publish_post', 'aktt_notify_twitter', 99);
 }
Example #24
0
 $project_location = $term->slug;
 $arr_cats = array();
 $arr_cats[] = $project_location;
 if (!empty($_POST['subloc'])) {
     $term = get_term($_POST['subloc'], 'project_location');
     $jb_category2 = $term->slug;
     $arr_cats[] = $jb_category2;
 }
 if (!empty($_POST['subloc2'])) {
     $term = get_term($_POST['subloc2'], 'project_location');
     $jb_category2 = $term->slug;
     $arr_cats[] = $jb_category2;
 }
 wp_set_object_terms($pid, $arr_cats, 'project_location');
 //***********************************************
 wp_set_post_tags($pid, $project_tags);
 // set project details, as meta post
 update_post_meta($pid, "Location", $project_location_addr);
 // set project location
 update_post_meta($pid, "price", ProjectTheme_get_budget_name_string_fromID($_POST['budgets']));
 // set project price
 update_post_meta($pid, "paid", "0");
 update_post_meta($pid, "views", '0');
 update_post_meta($pid, "budgets", $_POST['budgets']);
 // IF TIME NOT SELECTED THEN 30 DAYS
 if (empty($end)) {
     $ending = current_time('timestamp', 0) + 30 * 3600 * 24;
 } else {
     $ending = strtotime($end, current_time('timestamp', 0));
 }
 $projectTheme_project_period = get_option('projectTheme_project_period');
Example #25
0
 $my_post = array();
 $my_post['ID'] = $pid;
 $my_post['post_content'] = $job_description;
 $my_post['post_title'] = $job_title;
 $PricerrTheme_admin_approve_job = get_option('PricerrTheme_admin_approve_job');
 if ($PricerrTheme_admin_approve_job == "yes") {
     $my_post['post_status'] = 'draft';
     update_post_meta($pid, 'under_review', "1");
 } else {
     $my_post['post_status'] = 'publish';
     update_post_meta($pid, 'under_review', "0");
 }
 wp_update_post($my_post);
 $term = get_term($_POST['job_cat_cat'], 'job_cat');
 $job_cat = $term->slug;
 wp_set_post_tags($pid, $job_tags);
 wp_set_object_terms($pid, array($job_cat), 'job_cat');
 update_post_meta($pid, "max_days", $max_days);
 update_post_meta($pid, "has_video", "0");
 update_post_meta($pid, "shipping", trim($_POST['shipping']));
 for ($i = 1; $i <= 3; $i++) {
     $y_link = htmlspecialchars($_POST['youtube_link' . $i]);
     update_post_meta($pid, "youtube_link" . $i, trim($y_link));
     update_post_meta($pid, "has_video", "1");
 }
 $job_saved = 1;
 /**************************************************************/
 $PricerrTheme_new_job_listing_fee = get_option('PricerrTheme_new_job_listing_fee');
 update_post_meta($pid, 'featured', "0");
 $featured = get_post_meta($pid, 'featured', true);
 $paid = get_post_meta($pid, 'paid', true);
 /**
  * function to map the xml file and process it
  *
  * @return post_id
  */
 function processDataInWP($get_details, $currentLimit, $user = null, $img, $duptitle, $dupcontent, $authtype)
 {
     require_once ABSPATH . "wp-includes/pluggable.php";
     require_once ABSPATH . 'wp-admin/includes/image.php';
     $postmeta_terms = $to_post = $post_data = $post_arr = $ex_type = array();
     $cur_prev_ids = $tag_name = $img_url = $local_parent_id = $post_exist = $post_id = $type = $img_url = $zip_img_url = $guid = '';
     $sample = array('is_normal_post', 'is_custom_post', 'is_sticky', 'terms', 'postmeta', 'comments', 'is_page', 'post_id', 'attachment_url', 'guid', 'post_parent');
     $un_comments = array('comment_user_id', 'comment_id', 'commentmeta');
     if (is_array($get_details['posts'])) {
         $post_arr = $get_details['posts'];
         $post_data = $post_arr[$currentLimit];
         if (is_array($post_data)) {
             foreach ($post_data as $post_key => $post_val) {
                 if (isset($post_key) && $post_key == 'post_author') {
                     if ($authtype != 'simple') {
                         if (!empty($user) && is_numeric($user)) {
                             $post_data['post_author'] = $user;
                         }
                     } else {
                         if ($authtype == 'simple') {
                             $post_data['post_author'] = $this->get_author_id($post_val);
                         }
                     }
                     $postmeta_terms = $post_data;
                     $to_post = $post_data;
                 }
                 if (isset($post_key) && $post_key == 'status') {
                     $to_post['post_status'] = $post_val;
                     if (empty($post_val) && $post_val == 'null' && $post_val == '') {
                         $to_post['post_status'] = 'publish';
                     }
                 }
                 if (in_array($post_key, $sample, TRUE)) {
                     unset($to_post['is_normal_post']);
                     unset($to_post['is_custom_post']);
                     unset($to_post['is_sticky']);
                     unset($to_post['terms']);
                     unset($to_post['postmeta']);
                     unset($to_post['comments']);
                     unset($to_post['is_page']);
                     unset($to_post['post_id']);
                     unset($to_post['attachment_url']);
                     unset($to_post['guid']);
                     unset($to_post['post_parent']);
                 }
                 if (isset($post_key) && $post_key == 'post_type') {
                     $ex_type = $this->to_import();
                     if (is_array($ex_type)) {
                         if (!in_array($post_val, $ex_type, TRUE)) {
                             return false;
                         } else {
                             $to_post = $this->exclude_list($post_val, $to_post);
                         }
                     }
                     if ($duptitle == 'true' || $dupcontent == 'true') {
                         $type = 'title';
                         $post_exist = $this->duplicateChecks($type, $post_data['post_title'], $post_data['post_type']);
                         if ($post_exist != 0) {
                             $this->detailedLog[$currentLimit]['verify_here'] = "<b>" . $post_data['post_title'] . " </b> is already exist<br>";
                             return false;
                         }
                     }
                     if ($post_val == 'attachment') {
                         if ($img == 'no') {
                             $img_url = $post_data['attachment_url'];
                             $zip_img_url = $this->get_img_from_zip($img_url);
                             $guid = $this->get_attachment($zip_img_url, $currentLimit);
                         } else {
                             $guid = $this->get_attachment($post_data['attachment_url'], $currentLimit);
                         }
                         $filename = $guid;
                         $parent_post_id = $post_data['post_parent'];
                         $filetype = wp_check_filetype(basename($filename), null);
                         $wp_upload_dir = wp_upload_dir();
                         $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($filename), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit');
                         $attach_id = wp_insert_attachment($attachment, $filename, $parent_post_id);
                         $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
                         wp_update_attachment_metadata($attach_id, $attach_data);
                         set_post_thumbnail($parent_post_id, $attach_id);
                         $attach_details = $attach_id . '|' . $parent_post_id;
                         $_SESSION['attach_id'][$currentLimit] = $attach_details;
                         if (!empty($filename)) {
                             $this->detailedLog[$currentLimit]['verify_here'] = " <span style = 'padding:5px;'><b> Image - </b>" . basename($filename) . "</span><br>";
                         } else {
                             $this->detailedLog[$currentLimit]['verify_here'] = "<span style ='padding:5px;'><b> Image - </b>" . basename($filename) . "</span><br>";
                         }
                         $to_post['guid'] = $guid;
                         return false;
                         //     $to_post['attachment_url'] = $guid;
                     } else {
                         $local_post_id = $post_data['post_id'];
                     }
                 }
             }
         }
         $post_id = wp_insert_post($to_post);
         if (isset($to_post) && $to_post['post_type'] != 'attachement') {
             $cur_prev_ids = $post_id . '|' . $local_post_id;
             $_SESSION['post_id'][$currentLimit] = $cur_prev_ids;
         }
         if (isset($postmeta_terms['terms'])) {
             foreach ($postmeta_terms['terms'] as $tag_key) {
                 if (isset($tag_key['domain']) && $tag_key['domain'] == 'post_tag') {
                     $tag_name = $tag_key['slug'];
                     wp_set_post_tags($post_id, $tag_name);
                 } else {
                     if (isset($tag_key['domain']) && $tag_key['domain'] == 'category') {
                         $cat[] = $tag_key['slug'];
                         wp_set_object_terms($post_id, $cat, 'category');
                     } else {
                         if (isset($tag_key['domain']) && $tag_key['domain'] == 'post_format') {
                             wp_set_object_terms($post_id, $tag_key['slug'], 'post_format');
                         }
                     }
                 }
                 if (is_array($tag_key)) {
                     foreach ($tag_key as $term_key => $term_val) {
                     }
                 }
             }
         }
         if ($post_val != 'attachment') {
             if (is_array($postmeta_terms['postmeta'])) {
                 foreach ($postmeta_terms['postmeta'] as $pkey => $pval) {
                     update_post_meta($post_id, $pval['key'], $pval['value']);
                 }
             }
         }
         if (isset($postmeta_terms['comments'])) {
             foreach ($postmeta_terms['comments'] as $ckey) {
                 foreach ($ckey as $unkey => $unval) {
                     if (in_array($unkey, $un_comments, TRUE)) {
                         unset($ckey[$unkey]);
                     }
                 }
                 $ckey['comment_post_ID'] = $post_id;
                 wp_insert_comment($ckey);
             }
         }
     }
     $this->detailedLog[$currentLimit]['verify_here'] = "<span style = 'padding:5px;'> The  <b>  " . $to_post['post_title'] . " </b> has been created Verify Here - <a href='" . get_permalink($post_id) . "' title='" . esc_attr(sprintf(__('View &#8220;%s&#8221;'), $to_post['post_title'])) . "' rel='permalink'>" . __('Web View') . "</a> | <a href='" . get_edit_post_link($post_id, true) . "' title='" . esc_attr(__('Edit this item')) . "'>" . __('Admin View') . "</a> </span><br>";
     //			$this->detailedLog[$currentLimit]['verify_here'] = $to_post;
     unset($to_post);
     return $post_id;
 }
 function process_post($post)
 {
     global $wpdb;
     $post_ID = (int) $this->get_tag($post, 'wp:post_id');
     if ($post_ID && !empty($this->post_ids_processed[$post_ID])) {
         // Processed already
         return 0;
     }
     set_time_limit(60);
     // There are only ever one of these
     $post_title = $this->get_tag($post, 'title');
     $post_date = $this->get_tag($post, 'wp:post_date');
     $post_date_gmt = $this->get_tag($post, 'wp:post_date_gmt');
     $comment_status = $this->get_tag($post, 'wp:comment_status');
     $ping_status = $this->get_tag($post, 'wp:ping_status');
     $post_status = $this->get_tag($post, 'wp:status');
     $post_name = $this->get_tag($post, 'wp:post_name');
     $post_parent = $this->get_tag($post, 'wp:post_parent');
     $menu_order = $this->get_tag($post, 'wp:menu_order');
     $post_type = $this->get_tag($post, 'wp:post_type');
     $post_password = $this->get_tag($post, 'wp:post_password');
     $is_sticky = $this->get_tag($post, 'wp:is_sticky');
     $guid = $this->get_tag($post, 'guid');
     $post_author = $this->get_tag($post, 'dc:creator');
     $post_excerpt = $this->get_tag($post, 'excerpt:encoded');
     $post_excerpt = preg_replace_callback('|<(/?[A-Z]+)|', array(&$this, '_normalize_tag'), $post_excerpt);
     $post_excerpt = str_replace('<br>', '<br />', $post_excerpt);
     $post_excerpt = str_replace('<hr>', '<hr />', $post_excerpt);
     $post_content = $this->get_tag($post, 'content:encoded');
     $post_content = preg_replace_callback('|<(/?[A-Z]+)|', array(&$this, '_normalize_tag'), $post_content);
     $post_content = str_replace('<br>', '<br />', $post_content);
     $post_content = str_replace('<hr>', '<hr />', $post_content);
     preg_match_all('|<category domain="tag">(.*?)</category>|is', $post, $tags);
     $tags = $tags[1];
     $tag_index = 0;
     foreach ($tags as $tag) {
         $tags[$tag_index] = $wpdb->escape(html_entity_decode(str_replace(array('<![CDATA[', ']]>'), '', $tag)));
         $tag_index++;
     }
     preg_match_all('|<category>(.*?)</category>|is', $post, $categories);
     $categories = $categories[1];
     $cat_index = 0;
     foreach ($categories as $category) {
         $categories[$cat_index] = $wpdb->escape(html_entity_decode(str_replace(array('<![CDATA[', ']]>'), '', $category)));
         $cat_index++;
     }
     $post_exists = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $post_title . "' && post_status = 'publish'", 'ARRAY_N');
     if ($post_exists) {
         echo '<li>';
         printf(__('Post <em>%s</em> already exists.', 'wordpress-importer'), stripslashes($post_title));
         $comment_post_ID = $post_id = $post_exists;
     } else {
         // If it has parent, process parent first.
         $post_parent = (int) $post_parent;
         if ($post_parent) {
             // if we already know the parent, map it to the local ID
             if (isset($this->post_ids_processed[$post_parent])) {
                 $post_parent = $this->post_ids_processed[$post_parent];
                 // new ID of the parent
             } else {
                 // record the parent for later
                 $this->orphans[intval($post_ID)] = $post_parent;
             }
         }
         echo '<li>';
         $post_author = $this->checkauthor($post_author);
         //just so that if a post already exists, new users are not created by checkauthor
         $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_excerpt', 'post_title', 'post_status', 'post_name', 'comment_status', 'ping_status', 'guid', 'post_parent', 'menu_order', 'post_type', 'post_password');
         $postdata['import_id'] = $post_ID;
         if ($post_type == 'attachment') {
             $remote_url = $this->get_tag($post, 'wp:attachment_url');
             if (!$remote_url) {
                 $remote_url = $guid;
             }
             $comment_post_ID = $post_id = $this->process_attachment($postdata, $remote_url);
             if (!$post_id or is_wp_error($post_id)) {
                 return $post_id;
             }
         } else {
             printf(__('Importing post <em>%s</em>...', 'wordpress-importer') . "\n", stripslashes($post_title));
             $comment_post_ID = $post_id = wp_insert_post($postdata);
             if ($post_id && $is_sticky == 1) {
                 stick_post($post_id);
             }
         }
         if (is_wp_error($post_id)) {
             return $post_id;
         }
         // Memorize old and new ID.
         if ($post_id && $post_ID) {
             $this->post_ids_processed[intval($post_ID)] = intval($post_id);
         }
         // Add categories.
         if (count($categories) > 0) {
             $post_cats = array();
             foreach ($categories as $category) {
                 if ('' == $category) {
                     continue;
                 }
                 $slug = sanitize_term_field('slug', $category, 0, 'category', 'db');
                 $cat = get_term_by('slug', $slug, 'category');
                 $cat_ID = 0;
                 if (!empty($cat)) {
                     $cat_ID = $cat->term_id;
                 }
                 if ($cat_ID == 0) {
                     $category = $wpdb->escape($category);
                     $cat_ID = wp_insert_category(array('cat_name' => $category));
                     if (is_wp_error($cat_ID)) {
                         continue;
                     }
                 }
                 $post_cats[] = $cat_ID;
             }
             wp_set_post_categories($post_id, $post_cats);
         }
         // Add tags.
         if (count($tags) > 0) {
             $post_tags = array();
             foreach ($tags as $tag) {
                 if ('' == $tag) {
                     continue;
                 }
                 $slug = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
                 $tag_obj = get_term_by('slug', $slug, 'post_tag');
                 $tag_id = 0;
                 if (!empty($tag_obj)) {
                     $tag_id = $tag_obj->term_id;
                 }
                 if ($tag_id == 0) {
                     $tag = $wpdb->escape($tag);
                     $tag_id = wp_insert_term($tag, 'post_tag');
                     if (is_wp_error($tag_id)) {
                         continue;
                     }
                     $tag_id = $tag_id['term_id'];
                 }
                 $post_tags[] = intval($tag_id);
             }
             wp_set_post_tags($post_id, $post_tags);
         }
     }
     // Now for comments
     preg_match_all('|<wp:comment>(.*?)</wp:comment>|is', $post, $comments);
     $comments = $comments[1];
     $num_comments = 0;
     $inserted_comments = array();
     if ($comments) {
         foreach ($comments as $comment) {
             $comment_id = $this->get_tag($comment, 'wp:comment_id');
             $newcomments[$comment_id]['comment_post_ID'] = $comment_post_ID;
             $newcomments[$comment_id]['comment_author'] = $this->get_tag($comment, 'wp:comment_author');
             $newcomments[$comment_id]['comment_author_email'] = $this->get_tag($comment, 'wp:comment_author_email');
             $newcomments[$comment_id]['comment_author_IP'] = $this->get_tag($comment, 'wp:comment_author_IP');
             $newcomments[$comment_id]['comment_author_url'] = $this->get_tag($comment, 'wp:comment_author_url');
             $newcomments[$comment_id]['comment_date'] = $this->get_tag($comment, 'wp:comment_date');
             $newcomments[$comment_id]['comment_date_gmt'] = $this->get_tag($comment, 'wp:comment_date_gmt');
             $newcomments[$comment_id]['comment_content'] = $this->get_tag($comment, 'wp:comment_content');
             $newcomments[$comment_id]['comment_approved'] = $this->get_tag($comment, 'wp:comment_approved');
             $newcomments[$comment_id]['comment_type'] = $this->get_tag($comment, 'wp:comment_type');
             $newcomments[$comment_id]['comment_parent'] = $this->get_tag($comment, 'wp:comment_parent');
         }
         // Sort by comment ID, to make sure comment parents exist (if there at all)
         ksort($newcomments);
         foreach ($newcomments as $key => $comment) {
             // if this is a new post we can skip the comment_exists() check
             if (!$post_exists || !comment_exists($comment['comment_author'], $comment['comment_date'])) {
                 if (isset($inserted_comments[$comment['comment_parent']])) {
                     $comment['comment_parent'] = $inserted_comments[$comment['comment_parent']];
                 }
                 $comment = wp_filter_comment($comment);
                 $inserted_comments[$key] = wp_insert_comment($comment);
                 $num_comments++;
             }
         }
     }
     if ($num_comments) {
         printf(' ' . _n('(%s comment)', '(%s comments)', $num_comments, 'wordpress-importer'), $num_comments);
     }
     // Now for post meta
     preg_match_all('|<wp:postmeta>(.*?)</wp:postmeta>|is', $post, $postmeta);
     $postmeta = $postmeta[1];
     if ($postmeta) {
         foreach ($postmeta as $p) {
             $key = $this->get_tag($p, 'wp:meta_key');
             $value = $this->get_tag($p, 'wp:meta_value');
             $this->process_post_meta($post_id, $key, $value);
         }
     }
     do_action('import_post_added', $post_id);
     print "</li>\n";
 }
Example #28
0
function set_tags_from_s9y($item, $key, $post_id)
{
    if (!empty($item)) {
        wp_set_post_tags($post_id, $item, TRUE);
    }
}
Example #29
0
/**
 * Adds tags to a post.
 *
 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
 *
 * @package WordPress
 * @subpackage Post
 * @since 2.3.0
 *
 * @param int $post_id Post ID
 * @param string $tags The tags to set for the post, separated by commas.
 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
 */
function wp_add_post_tags($post_id = 0, $tags = '')
{
    return wp_set_post_tags($post_id, $tags, true);
}
Example #30
0
/**
 * Insert tweets as posts
 *
 * @param array $tweets   Array of tweet objects
 * @return array          Array of stats about the insertion
 */
function ozh_ta_insert_tweets($tweets)
{
    // Flag as importing : this will cut some queries in the process, regarding (ping|track)backs
    if (!defined('WP_IMPORTING')) {
        define('WP_IMPORTING', true);
    }
    global $ozh_ta;
    $inserted = $skipped = $tagged = $num_tags = 0;
    $user = array();
    if (ozh_ta_is_debug()) {
        $num_sql_batch = new ozh_ta_query_count();
    }
    foreach ((array) $tweets as $tweet) {
        if (ozh_ta_is_debug()) {
            $num_sql_post = new ozh_ta_query_count();
        }
        // Current tweet
        $tid = (string) $tweet->id_str;
        $text = ozh_ta_linkify_tweet($tweet);
        $date = date('Y-m-d H:i:s', strtotime($tweet->created_at) + 3600 * get_option('gmt_offset'));
        $source = $tweet->source;
        $has_hashtags = count($tweet->entities->hashtags) > 0;
        $reply_to_name = $tweet->in_reply_to_screen_name;
        $reply_to_tweet = (string) $tweet->in_reply_to_status_id_str;
        // Info about Twitter user
        if (!$user) {
            $user = array('tweet_counts' => $tweet->user->statuses_count, 'followers' => $tweet->user->followers_count, 'following' => $tweet->user->friends_count, 'listed_count' => $tweet->user->listed_count, 'profile_image_url' => $tweet->user->profile_image_url, 'tweeting_since' => date('Y-m-d H:i:s', strtotime($tweet->user->created_at)));
        }
        // Check for duplicate posts before inserting
        global $wpdb;
        $sql = "SELECT post_id\n\t\t        FROM `{$wpdb->postmeta}`\n\t\t\t\tWHERE `meta_key` = 'ozh_ta_id' AND `meta_value` = '{$tid} ' LIMIT 0,1";
        // Yeah, trusting api.twitter.com so we don't sanitize the SQL query, yeeeha
        if (!$wpdb->get_var($sql)) {
            // Insert tweet as new post
            $post = array('post_title' => strip_tags($text), 'post_content' => $text, 'post_date' => $date, 'post_category' => array($ozh_ta['post_category']), 'post_status' => 'publish', 'post_author' => $ozh_ta['post_author'], 'guid' => home_url() . '/?tid=' . $tid);
            // Post format
            if ('standard' != $ozh_ta['post_format']) {
                $post['tax_input'] = array('post_format' => array('post-format-' . $ozh_ta['post_format']));
            }
            // Plugins: hack here
            $post = apply_filters('ozh_ta_insert_tweets_post', $post);
            $post_id = wp_insert_post($post);
            // Apply post format when line 294-296 failed process the request
            if ('standard' != $ozh_ta['post_format']) {
                set_post_format($post_id, $ozh_ta['post_format']);
            }
            // Insert post meta data
            add_post_meta($post_id, 'ozh_ta_id', $tid);
            if ($source) {
                add_post_meta($post_id, 'ozh_ta_source', $source);
            }
            if ($reply_to_name) {
                add_post_meta($post_id, 'ozh_ta_reply_to_name', $reply_to_name);
            }
            if ($reply_to_tweet) {
                add_post_meta($post_id, 'ozh_ta_reply_to_tweet', $reply_to_tweet);
            }
            ozh_ta_debug(" Inserted #{$post_id} (tweet id: {$tid}, tweet: " . ozh_ta_trim_long_string($text, 100) . ')');
            if (ozh_ta_is_debug()) {
                ozh_ta_debug('  Import query cost: ' . $num_sql_post->stop());
            }
            // Tag post if applicable
            if ($has_hashtags && $ozh_ta['add_hash_as_tags'] == 'yes') {
                $hashtags = ozh_ta_get_hashtags($tweet);
                $num_tags += count($hashtags);
                $hashtags = implode(', ', $hashtags);
                ozh_ta_debug("  Tagging post {$post_id} with " . $hashtags);
                $tagged++;
                if (ozh_ta_is_debug()) {
                    $num_sql_tag = new ozh_ta_query_count();
                }
                wp_set_post_tags($post_id, $hashtags);
                if (ozh_ta_is_debug()) {
                    ozh_ta_debug('   Tagging query cost: ' . $num_sql_tag->stop());
                }
            }
            $inserted++;
        } else {
            // This tweet has already been imported ?!
            ozh_ta_debug(" Skipping tweet {$tid}, already imported?!");
            $skipped++;
        }
    }
    if (ozh_ta_is_debug()) {
        ozh_ta_debug('Batch import query cost: ' . $num_sql_batch->stop());
    }
    return array('inserted' => $inserted, 'skipped' => $skipped, 'tagged' => $tagged, 'num_tags' => $num_tags, 'user' => $user);
}