function media_sideload_image_1($file, $post_id, $desc = null, $return = 'html') { if (!empty($file)) { // Set variables for storage, fix file filename for query strings. preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $file, $matches); $file_array = array(); $file_array['name'] = basename($matches[0]); // Download file to temp location. $file_array['tmp_name'] = download_url($file); // If error storing temporarily, return the error. if (is_wp_error($file_array['tmp_name'])) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink. if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } /*$fullsize_path = get_attached_file( $id ); // Full path if (function_exists('ewww_image_optimizer')) { ewww_image_optimizer($fullsize_path, $gallery_type = 4, $converted = false, $new = true, $fullsize = true); }*/ $src = wp_get_attachment_url($id); } if (!empty($src)) { //update_post_meta($post_id, 'image_value', $src); set_post_thumbnail($post_id, $id); //update_post_meta($post_id, 'Thumbnail', $src); return get_post_meta($post_id, 'image_value', true); } else { return new WP_Error('image_sideload_failed'); } }
function programmatically_create_post() { $url = 'http://widgets.pinterest.com/v3/pidgets/boards/bradleyblose/my-stuff/pins/'; $json_O = json_decode(file_get_contents($url), true); $id = $json_O['data']['pins'][0]['id']; $titlelink = 'https://www.pinterest.com/pin/' . $id . '/'; $title = get_title($titlelink); var_dump($title); $original = $json_O['data']['pins'][0]['images']['237x']['url']; $image_url = preg_replace('/237x/', '736x', $original); $description = $json_O['data']['pins'][0]['description']; // Initialize the page ID to -1. This indicates no action has been taken. $post_id = -1; // Setup the author, slug, and title for the post $author_id = 1; $mytitle = get_page_by_title($title, OBJECT, 'post'); var_dump($mytitle); // If the page doesn't already exist, then create it if (NULL == get_page_by_title($title, OBJECT, 'post')) { // Set the post ID so that we know the post was created successfully $post_id = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_name' => $title, 'post_title' => $title, 'post_content' => $description, 'post_status' => 'publish', 'post_type' => 'post')); //upload featured image $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $filename = basename($image_url); if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; $path = $upload_dir['path'] . '/'; } else { $file = $upload_dir['basedir'] . '/' . $filename; $path = $upload_dir['basedir'] . '/'; } file_put_contents($file, $image_data); //edit featured image to correct specs to fit theme $pngfilename = $filename . '.png'; $targetThumb = $path . '/' . $pngfilename; $img = new Imagick($file); $img->scaleImage(250, 250, true); $img->setImageBackgroundColor('None'); $w = $img->getImageWidth(); $h = $img->getImageHeight(); $img->extentImage(250, 250, ($w - 250) / 2, ($h - 250) / 2); $img->writeImage($targetThumb); unlink($file); //Attach featured image $wp_filetype = wp_check_filetype($pngfilename, null); $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($pngfilename), 'post_content' => '', 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $targetThumb, $post_id); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $targetThumb); wp_update_attachment_metadata($attach_id, $attach_data); set_post_thumbnail($post_id, $attach_id); // Otherwise, we'll stop } else { // Arbitrarily use -2 to indicate that the page with the title already exists $post_id = -2; } // end if }
/** * If a YouTube or Vimeo video is added in the post content, grab its thumbnail and set it as the featured image */ function wds_set_media_as_featured_image($post_id, $post) { $content = isset($post->post_content) ? $post->post_content : ''; // Only check the first 1000 characters of our post. $content = substr($content, 0, 800); // Props to @rzen for lending his massive brain smarts to help with the regex $do_video_thumbnail = isset($post->ID) && !has_post_thumbnail($post_id) && $content && (preg_match('/\\/\\/(www\\.)?youtube\\.com\\/(watch|embed)\\/?(\\?v=)?([a-zA-Z0-9\\-\\_]+)/', $content, $youtube_matches) || preg_match('#https?://(.+\\.)?vimeo\\.com/.*#i', $content, $vimeo_matches)); if (!$do_video_thumbnail) { return update_post_meta($post_id, '_is_video', false); } $video_thumbnail_url = false; $youtube_id = $youtube_matches[4]; $vimeo_id = preg_replace("/[^0-9]/", "", $vimeo_matches[0]); if ($youtube_id) { // Check to see if our max-res image exists $file_headers = get_headers('http://img.youtube.com/vi/' . $youtube_id . '/maxresdefault.jpg'); $video_thumbnail_url = $file_headers[0] !== 'HTTP/1.0 404 Not Found' ? 'http://img.youtube.com/vi/' . $youtube_id . '/maxresdefault.jpg' : 'http://img.youtube.com/vi/' . $youtube_id . '/hqdefault.jpg'; } elseif ($vimeo_id) { $vimeo_data = wp_remote_get('http://www.vimeo.com/api/v2/video/' . intval($vimeo_id) . '.php'); if (isset($vimeo_data['response']['code']) && '200' == $vimeo_data['response']['code']) { $response = unserialize($vimeo_data['body']); $video_thumbnail_url = isset($response[0]['thumbnail_large']) ? $response[0]['thumbnail_large'] : false; } } // If we found an image... $attachment_id = $video_thumbnail_url && !is_wp_error($video_thumbnail_url) ? wds_ms_media_sideload_image_with_new_filename($video_thumbnail_url, $post_id, sanitize_title(get_the_title())) : 0; // If attachment wasn't created, bail if (!$attachment_id) { return; } // Woot! we got an image, so set it as the post thumbnail set_post_thumbnail($post_id, $attachment_id); update_post_meta($post_id, '_is_video', true); }
function smamo_sync_thumb($post_id) { $img_id = get_post_meta($post_id, 'img', true); if (isset($img_id)) { set_post_thumbnail($post_id, $img_id); } }
static function setMediaData() { global $easy_metadata; $attach_ids = get_option('easy_demo_images'); if (!$attach_ids) { return; } $pattern = '(\\bhttps?:\\/\\/\\S+?\\.(?:jpg|png|gif))'; $fn_i = array(); foreach ($attach_ids as $key => $id) { $fn_i[] = wp_get_attachment_image_src($id, 'full'); } $image_metas = explode(',', $easy_metadata['data']->post_meta_replace); $mi = count($image_metas); $post_types = explode(',', $easy_metadata['data']->post_type); $wp_query = new WP_Query(array("post_type" => $post_types, "posts_per_page" => -1)); while ($wp_query->have_posts()) { $wp_query->the_post(); $id = get_the_ID(); set_post_thumbnail($id, $attach_ids[0]); if ($easy_metadata['data']->force_image_replace == "yes") { $content = get_the_content(); $content = preg_replace($pattern, addslashes($fn_i[0][0]), $content); wp_update_post(array("ID" => $id, "post_content" => $content)); } for ($i = 0; $i < $mi; $i++) { update_post_meta($id, $image_metas[$i], $fn_i[0][0]); } } }
function creatProject() { // echo '<pre>'; // print_r($_POST); // print_r($_FILES); // exit; if ($_POST) { $post_id = wp_insert_post(array('post_author' => get_current_user_id(), 'post_title' => $_POST['tieudeduan'], 'post_content' => $_POST['mieutanoidung'], 'post_type' => 'du-an', 'post_status' => 'publish')); if ($_FILES['anhdaidien']['name']) { require_once ABSPATH . '/wp-admin/includes/media.php'; require_once ABSPATH . '/wp-admin/includes/file.php'; require_once ABSPATH . '/wp-admin/includes/image.php'; $attachmentId = media_handle_upload('anhdaidien', $post_id); set_post_thumbnail($post_id, $attachmentId); } // So luoc chien dich add_post_meta($post_id, 'wpcf-dia-diem-du-an', $_POST['diadiemduan']); add_post_meta($post_id, 'wpcf-so-tien-quyen-gop', $_POST['sotienquyengop']); add_post_meta($post_id, 'wpcf-thoi-gian-bat-dau', strtotime($_POST['thoigianbatdau'])); add_post_meta($post_id, 'wpcf-thoi-gian-ket-thuc', strtotime($_POST['thoigianketthuc'])); add_post_meta($post_id, 'wpcf-mieu-ta-ngan', $_POST['mieutangan']); //thong tin lien he add_post_meta($post_id, 'wpcf-ho-va-ten', $_POST['hoten']); add_post_meta($post_id, 'wpcf-email', $_POST['email']); add_post_meta($post_id, 'wpcf-dia-chi', $_POST['diachi']); add_post_meta($post_id, 'wpcf-so-dien-thoai', $_POST['sodt']); add_post_meta($post_id, 'wpcf-so-goi-khan-cap', $_POST['sodtkhac']); add_post_meta($post_id, 'wpcf-link-facebook', $_POST['facebook_url']); add_post_meta($post_id, 'wpcf-so-tai-khoan', $_POST['sotk']); add_post_meta($post_id, 'wpcf-ngay-sinh', strtotime($_POST['ngaysinh'])); echo json_encode(array('msg' => 'Giử yêu cầu thành công', 'err' => 0)); exit; } }
/** * Cache images on post's saving */ function check_post_for_images($post_ID, $ablog, $item) { // Get the post so we can edit it. $post = get_post($post_ID); $images = $this->get_remote_images_in_content($post->post_content); if (!empty($images)) { // Include the file and media libraries as they have the functions we want to use require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; foreach ($images as $image) { preg_match('/[^\\?]+\\.(jpe?g|jpe|gif|png)\\b/i', $image, $matches); if (!empty($matches)) { $this->grab_image_from_url($image, $post_ID); } } // Set the first image as the featured one - from a snippet at http://wpengineer.com/2460/set-wordpress-featured-image-automatically/ $imageargs = array('numberposts' => 1, 'order' => 'ASC', 'post_mime_type' => 'image', 'post_parent' => $post_ID, 'post_status' => NULL, 'post_type' => 'attachment'); $cachedimages = get_children($imageargs); if (!empty($cachedimages)) { foreach ($cachedimages as $image_id => $image) { set_post_thumbnail($post_ID, $image_id); } } } // Returning the $post_ID even though it's an action and we really don't need to return $post_ID; }
/** * Save the new field data for the nav menu. * * @param $menu_id * @param $menu_item_db_id * @param $args */ public function update_nav_fields($menu_id, $menu_item_db_id, $args) { // Hide on mobile. if (isset($_POST['hide-menu-on-mobile'][$menu_item_db_id])) { update_post_meta($menu_item_db_id, 'hide_menu_on_mobile', empty($_POST['hide-menu-on-mobile'][$menu_item_db_id]) ? false : 'on'); } else { delete_post_meta($menu_item_db_id, 'hide_menu_on_mobile'); } // Image. if (isset($_POST['menu-item-image']) && is_array($_POST['menu-item-image'])) { if (!isset($_POST['menu-item-image'][$menu_item_db_id]) || !$_POST['menu-item-image'][$menu_item_db_id]) { delete_post_thumbnail($menu_item_db_id); } if (isset($_POST['menu-item-image'][$menu_item_db_id])) { set_post_thumbnail($menu_item_db_id, absint($_POST['menu-item-image'][$menu_item_db_id])); } } if (isset($_POST['menu-item-icon']) && is_array($_POST['menu-item-icon'])) { if (isset($_POST['menu-item-icon'][$menu_item_db_id])) { update_post_meta($menu_item_db_id, '_menu_item_icon', sanitize_text_field($_POST['menu-item-icon'][$menu_item_db_id])); } } if (isset($_POST['menu-item-widget-area']) && isset($_POST['menu-item-widget-area'][$menu_item_db_id]) && is_array($_POST['menu-item-widget-area'])) { update_post_meta($menu_item_db_id, '_menu_item_widget_area', sanitize_text_field($_POST['menu-item-widget-area'][$menu_item_db_id])); } }
function frontier_clone_post($fpost_sc_parms = array()) { //extract($fpost_sc_parms); //echo "CLONE POST<br>"; $frontier_permalink = get_permalink(); $concat = get_option("permalink_structure") ? "?" : "&"; if (isset($_POST['task'])) { $post_task = $_POST['task']; } else { if (isset($_GET['task'])) { $post_task = $_GET['task']; } else { $post_task = "notaskset"; } } $post_action = isset($_POST['action']) ? $_POST['action'] : "Unknown"; if ($post_task == "clone" && $_REQUEST['postid']) { $old_post = get_post($_REQUEST['postid']); $old_post_id = $old_post->ID; //double check current user can add a post with this post type if (frontier_can_add($old_post->post_type)) { require_once ABSPATH . '/wp-admin/includes/post.php'; global $current_user; //Get permalink from old post $old_permalink = get_permalink($old_post_id); // lets clone it $thispost = get_default_post_to_edit($fpost_sc_parms['frontier_add_post_type'], true); $new_post_id = $thispost->ID; $tmp_post = array('ID' => $new_post_id, 'post_type' => $old_post->post_type, 'post_title' => __("CLONED from", "frontier-post") . ': <a href="' . $old_permalink . '">' . $old_post->post_title . '</a>', 'post_content' => __("CLONED from", "frontier-post") . ': <a href="' . $old_permalink . '">' . $old_post->post_title . '</a><br>' . $old_post->post_content, 'post_status' => "draft", 'post_author' => $current_user->ID); //**************************************************************************************************** // Apply filter before update of post // filter: frontier_post_clone // $tmp_post Array that holds the updated fields // $old_post The post being cloed (Object) //**************************************************************************************************** $tmp_post = apply_filters('frontier_post_clone', $tmp_post, $old_post); // save post wp_update_post($tmp_post); //Get the updated post $new_post = get_post($new_post_id); //get all current post terms ad set them to the new post draft $taxonomies = get_object_taxonomies($old_post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag"); foreach ($taxonomies as $taxonomy) { $post_terms = wp_get_object_terms($old_post_id, $taxonomy, array('fields' => 'slugs')); wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false); } // Set featured image: $post_thumbnail_id = get_post_thumbnail_id($old_post_id); if (intval($post_thumbnail_id) > 0) { set_post_thumbnail($new_post_id, $post_thumbnail_id); } // Add/Update message frontier_post_set_msg(__("Post Cloned and ready edit", "frontier-post") . ": " . $new_post->post_title); frontier_post_set_msg(__("Post status set to Draft", "frontier-post")); frontier_user_post_list($fpost_sc_parms); } } }
/** * Set the post thumbnail when the user sets it on the front end * * @since 0.1 * * @param array $data Sanitized data to use for saving. * * @return bool Always returns true. */ public function upload($data) { $postid = isset($data['postid']) ? $data['postid'] : false; $image_id = isset($data['image_id']) ? absint($data['image_id']) : false; set_post_thumbnail($postid, $image_id); do_action('lasso_featured_image_set', $postid, $image_id, get_current_user_ID()); return true; }
function ph_migrate_post_attachment_field_handler($post, $fields) { $elem = $fields; if (isset($elem['attachment:path']) && !is_array($elem['attachment:path'])) { foreach ($fields as $key => $value) { $elem[$key] = array($value); } } $attachments = array(); foreach ($elem as $key => $values) { for ($i = 0; $i < count($values); $i++) { if (!isset($attachments[$i])) { $attachments[$i] = new Stdclass(); $attachments[$i]->parent = $post['ID']; } $destkey = substr($key, strlen('attachment:')); $attachments[$i]->{$destkey} = $values[$i]; } } $destination = new ph_attachment_destination(); $data = array('post_parent' => $post['ID'], 'post_type' => 'attachment'); $old_attachments = get_children($data); foreach ($old_attachments as $id => $obj) { $item = $destination->getItemByID($id); $destination->deleteItem($item); } $update_post = false; foreach ($attachments as $attachment) { if (isset($attachment->path) && $attachment->path != '' && $attachment->path != null && file_exists($attachment->path)) { echo "attachment: " . $attachment->path . "\n"; $id = $destination->save($attachment); if (is_object($id)) { //saving this item did not work. continue; } if (1 == isset($attachment->isTeaser) && $attachment->isTeaser) { set_post_thumbnail($post['ID'], $id); } if (isset($attachment->replaceToken) && $attachment->replaceToken != '') { $string = $post['post_content']; $string = str_replace($attachment->replaceToken, $id, $string); $post['post_content'] = $string; $update_post = true; } if (isset($attachment->sourceURL) && $attachment->sourceURL != '') { $url = wp_get_attachment_image_src($id, 'medium'); $string = $post['post_content']; $attr = 'src="' . $url[0] . '" width="' . $url[1] . '" height="' . $url[2] . '"'; $string = str_replace($attachment->sourceURL, $attr, $string); $post['post_content'] = $string; $update_post = true; } } } if ($update_post) { wp_update_post($post); } }
public function setImage($post_id, $image_id, $meta_key) { $post = get_post($post_id); // Attach to custom meta field if ($meta_key) { add_post_meta($post_id, $meta_key, $image_id, false); } else { set_post_thumbnail($post, $image_id); } }
function wpmp_add_product() { if (isset($_POST['__product_wpmp']) && wp_verify_nonce($_POST['__product_wpmp'], 'wpmp-product') && $_POST['task'] == '') { //echo "here";exit; if ($_POST['post_type'] == "wpmarketplace") { global $current_user, $wpdb; get_currentuserinfo(); $settings = get_option('_wpmp_settings'); $pstatus = $settings['fstatus'] ? $settings['fstatus'] : "draft"; $my_post = array('post_title' => $_POST['product']['post_title'], 'post_content' => $_POST['product']['post_content'], 'post_excerpt' => $_POST['product']['post_excerpt'], 'post_status' => $pstatus, 'post_author' => $current_user->ID, 'post_type' => "wpmarketplace"); if ($_POST['id']) { //update post $my_post['ID'] = $_REQUEST['id']; wp_update_post($my_post); $postid = $_REQUEST['id']; } else { //insert post $postid = wp_insert_post($my_post); } update_post_meta($postid, "wpmp_list_opts", $_POST['wpmp_list']); //set the product type wp_set_post_terms($postid, $_POST['product_type'], "ptype"); foreach ($_POST['wpmp_list'] as $k => $v) { update_post_meta($postid, $k, $v); } if ($_POST['wpmp_list']['fimage']) { $wp_filetype = wp_check_filetype(basename($_POST['wpmp_list']['fimage']), null); $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($_POST['wpmp_list']['fimage'])), 'post_content' => '', 'guid' => $_POST['wpmp_list']['fimage'], 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $_POST['wpmp_list']['fimage'], $postid); // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $_POST['wpmp_list']['fimage']); wp_update_attachment_metadata($attach_id, $attach_data); set_post_thumbnail($postid, $attach_id); } //send admin email if ($pstatus == "draft") { //get user emai global $current_user; get_currentuserinfo(); mail($current_user->user_email, "New Product Added", "Your product is successfully added and is waiting to admin review. You will be notified if your product is accepetd or rejected."); //now send notification to site admin about newly added product $admin_email = get_bloginfo('admin_email'); mail($admin_email, "Product Review", "New Product is added by user " . $current_user->user_login . ". Please review this product to add your store."); //add a new post meta to identify only drafted post if (!update_post_meta($postid, '_z_user_review', '1')) { add_post_meta($postid, '_z_user_review', '1', true); } } } header("Location: " . $_SERVER['HTTP_REFERER']); die; } }
/** * Add track details when a post is saved. * * @param int $post_id The post ID. * @param post $post The post object. * @param bool $update Whether this is an existing post being updated or not. */ function soundpress_add_track_details_to_post($post_id, $post, $update) { $trackurl = get_post_meta($post_id, 'soundpress_soundcloud_url', true); if (wp_is_post_revision($post_id)) { return; } if ($trackurl) { $track_details = soundcloud_remote_get($trackurl); if (is_object($track_details)) { // Check for thumbnail. If not present, get the board Image if (!has_post_thumbnail($post_id)) { $thumbnailurl = $track_details->artwork_url; if (empty($thumbnailurl)) { $thumbnailurl = $track_details->user->avatar_url; } $tmp = download_url($thumbnailurl); if (is_wp_error($tmp)) { } $desc = get_the_title($post_id); $file_array = array(); // Set variables for storage // fix file filename for query strings preg_match('/[^\\?]+\\.(jpg|jpe|jpeg|gif|png)/i', $thumbnailurl, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if (is_wp_error($tmp)) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload($file_array, $post_id, $desc); // If error storing permanently, unlink if (is_wp_error($id)) { @unlink($file_array['tmp_name']); return $id; } set_post_thumbnail($post_id, $id); } // Check for Description if ("" == get_the_content()) { $postcontentarray = array('ID' => $post_id, 'post_content' => $track_details->description); // Update the post into the database wp_update_post($postcontentarray); } // Get The Duration $durationseconds = $track_details->duration / 1000; update_post_meta($post_id, 'podcast_duration', esc_attr($durationseconds)); if (TRUE == $track_details->downloadable) { $download_url = esc_attr($track_details->download_url); update_post_meta($post_id, 'podcast_download_url', $download_url); } } } }
public function save_meta($post_id, $post) { if (!isset($_POST['life-control-series-nonce']) || !wp_verify_nonce($_POST['life-control-series-nonce'], plugin_basename(__FILE__))) { return; } if (!current_user_can('edit_post', $post_id)) { return; } if ('serie' != $post->post_type) { return; } $imdb_id = sanitize_text_field($_POST['imdb_id']); $tvrage_id = absint($_POST['tvrage_id']); $streamallthis = sanitize_text_field($_POST['streamallthis']); update_post_meta($post_id, 'imdb_id', $imdb_id); update_post_meta($post_id, 'tvrage_id', $tvrage_id); update_post_meta($post_id, 'streamallthis_name', $streamallthis); if ($this->extra_meta_data) { foreach ($this->extra_meta_data as $key => $value) { if ('thumbnail') { $attachment_id = Life_Control::$updater->load_thumbnail($post_id, $value, $post->post_title); if ($attachment_id) { set_post_thumbnail($post_id, $attachment_id); } } else { update_post_meta($post_id, $key, $value); } } } if ($tvrage_id) { $args = array('post_type' => 'episode', 'post_parent' => $post_id, 'posts_per_page' => 1); $episodes = get_posts($args); if (!$episodes) { $episodes = Life_Control::$updater->load_episodes($tvrage_id); if ($episodes) { foreach ($episodes as $episode) { $args = array('post_title' => $post->post_title . ': ' . $episode['title'], 'post_content' => '', 'post_status' => 'publish', 'post_parent' => $post_id, 'post_type' => 'episode', 'post_date' => $episode['date']); $episode_id = wp_insert_post($args); if (!is_wp_error($episode_id)) { update_post_meta($episode_id, 'season', $episode['season']); update_post_meta($episode_id, 'episode', $episode['episode']); if ($streamallthis) { $code = sprintf('s%02de%02d', $episode['season'], $episode['episode']); $url = 'http://streamallthis.me/watch/' . $streamallthis . '/' . $code . '.html'; $response = wp_remote_head($url); if (!is_wp_error($response) && 200 == wp_remote_retrieve_response_code($response)) { update_post_meta($episode_id, 'streamallthis', $url); } } } } } } } }
public function save_post($post_id, $post) { if (!is_object($post)) { return; } if (!is_numeric($post_id)) { return; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } if (defined('DOING_AJAX') && DOING_AJAX) { return; } if (in_array($post->post_type, $this->no_save_posttypes)) { return; } /* Get current video list */ $videos = unserialize(get_post_meta($post_id, 'wpusavevideos_videos', 1)); if (!is_array($videos)) { $videos = array(); } /* Add new videos */ $new_videos = $this->extract_videos_from_text($post->post_content); require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; /* Extract video details */ foreach ($new_videos as $id => $new_video) { if (!array_key_exists($id, $videos)) { $new_video['thumbnail'] = $this->retrieve_thumbnail($new_video['url'], $post_id); if ($new_video['thumbnail'] !== false) { $videos[$id] = $new_video; } } } /* Remove inexistant videos */ $saved_videos = array(); foreach ($videos as $id => $video) { if (array_key_exists($id, $new_videos)) { $saved_videos[$id] = $video; } } /* Set post thumbnail */ if (apply_filters('wpusavevideos_set_post_thumbnail', false) && !has_post_thumbnail($post_id)) { foreach ($saved_videos as $video) { if (isset($video['thumbnail']) && is_numeric($video['thumbnail'])) { set_post_thumbnail($post_id, $video['thumbnail']); break; } } } /* Save video list */ update_post_meta($post_id, 'wpusavevideos_videos', serialize($saved_videos)); }
function auto_post_after_image_upload($attachId) { $attachment = get_post($attachId); $post_category = isset($_SESSION['upload_category']) ? $_SESSION['upload_category'] : 0; $postData = array('post_title' => $attachment->post_title, 'post_type' => 'post', 'post_content' => '', 'post_category' => array($post_category), 'post_status' => 'publish'); $post_id = wp_insert_post($postData); // attach media to post wp_update_post(array('ID' => $attachId, 'post_parent' => $post_id)); set_post_thumbnail($post_id, $attachId); return $attachId; }
function setUp() { parent::setUp(); add_theme_support('post-thumbnails'); $filename = DIR_TESTDATA . '/images/waffles.jpg'; $contents = file_get_contents($filename); $upload = wp_upload_bits(basename($filename), null, $contents); $this->attachment_id = $this->_make_attachment($upload, self::$post_id); $this->attachment_data = get_post($this->attachment_id, ARRAY_A); set_post_thumbnail(self::$post_id, $this->attachment_id); }
function auto_featured_image() { global $post; if (!has_post_thumbnail($post->ID)) { $attached_image = get_children("post_parent={$post->ID}&post_type=attachment&post_mime_type=image&numberposts=1"); if ($attached_image) { foreach ($attached_image as $attachment_id => $attachment) { set_post_thumbnail($post->ID, $attachment_id); } } } }
function setUp() { parent::setUp(); add_theme_support('post-thumbnails'); $this->post_id = wp_insert_post(array('post_title' => rand_str(), 'post_content' => rand_str(), 'post_status' => 'publish')); $filename = DIR_TESTDATA . '/images/waffles.jpg'; $contents = file_get_contents($filename); $upload = wp_upload_bits(basename($filename), null, $contents); $this->attachment_id = $this->_make_attachment($upload, $this->post_id); $this->attachment_data = get_post($this->attachment_id, ARRAY_A); set_post_thumbnail($this->post_id, $this->attachment_id); }
function test_get_oembed_response_data_with_thumbnail() { $post = self::factory()->post->create_and_get(); $file = DIR_TESTDATA . '/images/canola.jpg'; $attachment_id = self::factory()->attachment->create_object($file, $post->ID, array('post_mime_type' => 'image/jpeg')); set_post_thumbnail($post, $attachment_id); $data = get_oembed_response_data($post, 400); $this->assertArrayHasKey('thumbnail_url', $data); $this->assertArrayHasKey('thumbnail_width', $data); $this->assertArrayHasKey('thumbnail_height', $data); $this->assertTrue(400 >= $data['thumbnail_width']); }
public function set_feautured_image($data, $item_id) { if ($item_id) { require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $this->attachment_id = media_handle_upload($data, $item_id); set_post_thumbnail($item_id, $this->attachment_id); } else { return false; } }
public function create() { $error_obj = ""; if (isset($this->TP_title)) { if ($this->TP_type == 'page') { $post = get_page_by_title($this->TP_title, 'OBJECT', $this->TP_type); } else { $post = get_page_by_title($this->TP_title, 'OBJECT', $this->TP_type); } $post_data = array('post_title' => wp_strip_all_tags($this->TP_title), 'post_name' => $this->TP_slug, 'post_content' => $this->TP_content, 'post_status' => $this->TP_status, 'post_type' => $this->TP_type, 'post_author' => $this->TP_auth_id, 'post_category' => $this->TP_category, 'page_template' => $this->TP_template, 'post_date' => $this->TP_date); if (!isset($post)) { $this->TP_current_post_id = wp_insert_post($post_data, $error_obj); $this->TP_current_post = get_post((int) $this->TP_current_post_id, 'OBJECT'); $this->TP_current_post_permalink = get_permalink((int) $this->TP_current_post_id); $terms = array(); $terms_array = explode(',', $this->TP_terms); foreach ($terms_array as $singleterm) { $term = get_term_by('slug', $singleterm, 'essential_grid_category'); $terms[] = $term->term_id; } wp_set_post_terms($this->TP_current_post_id, $terms, 'essential_grid_category'); if (!empty($this->TP_post_tags)) { wp_set_post_terms($this->TP_current_post_id, $this->TP_post_tags, 'post_tag'); } foreach ($this->TP_meta as $meta_key => $meta_value) { if ($meta_key == 'eg-clients-icon' && !empty($meta_value)) { $attach_id = $this->create_image('client.png'); $meta_value = $attach_id; } if ($meta_key == 'eg-clients-icon-dark' && !empty($meta_value)) { $attach_id = $this->create_image('client_dark.png'); $meta_value = $attach_id; } update_post_meta($this->TP_current_post_id, $meta_key, $meta_value); } global $imagenr; if ($imagenr == 4) { $imagenr = 1; } $attach_id = $this->create_image('demoimage' . $imagenr++ . '.jpg'); set_post_thumbnail($this->TP_current_post_id, $attach_id); return $this->TP_current_post_id; } else { //$this->update(); $this->errors[] = 'That page already exists. Try updating instead. Control passed to the update() function.'; return FALSE; } } else { $this->errors[] = 'Title has not been set.'; return FALSE; } }
function set_first_as_featured($attachment_ID) { $post_ID = get_post($attachment_ID)->post_parent; if (!has_post_thumbnail($post_ID)) { set_post_thumbnail($post_ID, $attachment_ID); } }
public function process_submit_new() { if (!wp_verify_nonce($_POST['hackgov_submit_new'], 'hackgov_submit_new_nonce')) { wp_die('not auth'); } $defaults = array('featured_image' => '', 'title' => '', 'problem' => '', 'recommendation' => '', 'priority' => '', 'category' => '', 'latitude' => '', 'longitude' => '', 'location_address' => ''); $data = (object) wp_parse_args($_POST, $defaults); // Create post object $new_post = array('post_title' => $data->title, 'post_content' => $data->problem, 'post_status' => 'pending', 'post_author' => get_current_user_id()); global $hackgov_messages; if (empty($hackgov_messages)) { $hackgov_messages = array(); } // Insert the post into the database $post_id = wp_insert_post($new_post); if ($post_id) { // set the post thumbnail if (!empty($data->featured_image)) { set_post_thumbnail($post_id, $data->featured_image); } // set meta type update_post_meta($post_id, '_post_recommendation', $data->recommendation); update_post_meta($post_id, '_category_priority', $data->priority); update_post_meta($post_id, '_category_category', $data->category); update_post_meta($post_id, '_latitude', $data->latitude); update_post_meta($post_id, '_longitude', $data->longitude); update_post_meta($post_id, '_location', $data->location_address); do_action('hackgov_success_create_pending_post', $post_id, $data); $hackgov_messages[] = array('type' => 'success', 'message' => __('Konten berhasil di kirim.', 'hackgov')); } else { do_action('hackgov_failed_create_pending_post'); $hackgov_messages[] = array('type' => 'error', 'message' => __('Konten gagal di kirim.', 'hackgov')); } }
function import_attachment_by_articles() { wp_reset_postdata(); query_posts(array('post_status' => 'publish', 'orderby' => 'menu_order', 'order' => 'DESC', 'posts_per_page' => '-1')); if (have_posts()) { $i = 1; while (have_posts()) { the_post(); $post_meta = get_post_meta(get_the_ID()); if (!empty($post_meta['headerImages'])) { $post_meta_headerImages = unserialize($post_meta['headerImages'][0]); foreach ($post_meta_headerImages as $key => $header_images) { $metaPostID = $media_item = null; echo get_the_ID() . "--" . $header_images . "--"; $metaPostID = get_post_id_by_meta_key_and_value('post_id', get_the_ID()); $media_item = get_permalink($metaPostID); if (!empty($metaPostID) && !empty($media_item)) { echo "{$metaPostID} available <br>"; set_post_thumbnail(get_the_ID(), $metaPostID); update_post_meta(get_the_ID(), 'post_promo-image_thumbnail_id', $metaPostID); continue; } else { //print_r($metaPostID); echo " {$metaPostID} not attachment {$media_item} <br>"; } $attachment_id = null; if ($key == "header" || $key == "promoSmall" || $key == "homepage") { add_image_size('promo-small', 288, 9999); } elseif ($key == "promoLarge" || $key == 'imagegroup') { add_image_size('promo-large', 650, 317); add_image_size('promo-small', 288, 9999); } $filename = get_attachment_details_from_table($key, get_the_ID(), $header_images); if (empty($filename)) { $filename = $header_images . '-' . $key . '.jpg'; } $url = "http://image.adam.automotive.com/f/{$header_images}/{$filename}"; $attachment_id = download_attachment($url, $filename, get_the_ID()); if (!empty($attachment_id)) { update_post_meta($attachment_id, 'post_id', get_the_ID()); update_post_meta($attachment_id, 'imageType', $key); //if($key=="header"){ set_post_thumbnail(get_the_ID(), $attachment_id); update_post_meta(get_the_ID(), 'post_promo-image_thumbnail_id', $attachment_id); //} echo "Success"; } else { echo "Fail"; } echo "<br>"; } } // echo "<pre>"; // print_r($post_meta['headerImages']); // echo "</pre>"; // echo "<br>"; } wp_reset_postdata(); } }
function wpmp_add_product() { if (wp_verify_nonce($_POST['__product_wpmp'], 'wpmp-product') && $_POST['task'] == '') { if ($_POST['post_type'] == "wpmarketplace") { global $current_user, $wpdb; get_currentuserinfo(); $my_post = array('post_title' => $_POST['product']['post_title'], 'post_content' => $_POST['product']['post_content'], 'post_excerpt' => $_POST['product']['post_excerpt'], 'post_status' => "draft", 'post_author' => $current_user->ID, 'post_type' => "wpmarketplace"); //echo $_POST['id']; if ($_POST['id']) { //update post $my_post['ID'] = $_REQUEST['id']; wp_update_post($my_post); $postid = $_REQUEST['id']; } else { //insert post $postid = wp_insert_post($my_post); } update_post_meta($postid, "wpmp_list_opts", $_POST['wpmp_list']); foreach ($_POST['wpmp_list'] as $k => $v) { update_post_meta($postid, $k, $v); } //echo $_POST['wpmp_list']['fimage']; if ($_POST['wpmp_list']['fimage']) { $wp_filetype = wp_check_filetype(basename($_POST['wpmp_list']['fimage']), null); $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($_POST['wpmp_list']['fimage'])), 'post_content' => '', 'guid' => $_POST['wpmp_list']['fimage'], 'post_status' => 'inherit'); $attach_id = wp_insert_attachment($attachment, $_POST['wpmp_list']['fimage'], $postid); set_post_thumbnail($postid, $attach_id); } } //echo $_SERVER['HTTP_REFERER']; header("Location: " . $_SERVER['HTTP_REFERER']); die; } }
function save_images($image_url, $post_id, $i) { //set_time_limit(180); //每个图片最长允许下载时间,秒 $file = file_get_contents($image_url); $fileext = substr(strrchr($image_url, '.'), 1); $fileext = strtolower($fileext); if ($fileext == "" || strlen($fileext) > 4) { $fileext = "jpg"; } $savefiletype = array('jpg', 'gif', 'png', 'bmp'); if (!in_array($fileext, $savefiletype)) { $fileext = "jpg"; } $im_name = date('YmdHis', time()) . $i . mt_rand(10, 20) . '.' . $fileext; $res = wp_upload_bits($im_name, '', $file); if (isset($res['file'])) { $attach_id = insert_attachment($res['file'], $post_id); } else { return; } if (ot_get_option('auto_save_image_thumb') == 'on' && $i == 1) { set_post_thumbnail($post_id, $attach_id); } return $res; }
/** * Loop through all posts, setting the first attached image as the featured images * * ## OPTIONS * * ## EXAMPLES * * wp auto-thumbnail * */ public function __invoke($args, $assoc_args) { set_time_limit(0); // Get all public post types $get_post_types = get_post_types(array('public' => true)); // Post types array that will be used by default $post_types = array(); foreach ($get_post_types as $post_type) { // Only add post types that support if (post_type_supports($post_type, 'thumbnail')) { $post_types[] = $post_type; } } // Default values for wp query $defaults = array('post_type' => $post_types, 'posts_per_page' => -1, 'post_status' => 'any'); // Merge user args with defaults $assoc_args = wp_parse_args($assoc_args, $defaults); // The Query $the_query = new WP_Query($assoc_args); // Number of posts returned by query $found_posts = $the_query->found_posts; // Generate progess bar $progress = new \cli\progress\Bar('Progress', $found_posts); // Counter for number of post successfully processed $counter_success = 0; // Counter for number of post processed $counter_processed = 0; // The Loop while ($the_query->have_posts()) { $the_query->the_post(); // Move the processbar on $progress->tick(); $has_thumb = has_post_thumbnail(get_the_ID()); if (!$has_thumb) { $attached_image = get_children("post_parent=" . get_the_ID() . "&post_type=attachment&post_mime_type=image&numberposts=1"); if ($attached_image) { foreach ($attached_image as $attachment_id => $attachment) { set_post_thumbnail(get_the_ID(), $attachment_id); $counter_success++; } } $counter_processed++; } } $progress->finish(); /* Restore original Post Data * NB: Because we are using new WP_Query we aren't stomping on the * original $wp_query and it does not need to be reset. */ wp_reset_postdata(); if ($found_posts == 0) { WP_CLI::error("No posts found"); } elseif ($counter_processed == 0) { WP_CLI::error("No posts processed"); } elseif ($counter_success == 0) { WP_CLI::success("Unable to processed any posts"); } else { WP_CLI::success("Processing compelete. {$counter_success} of {$counter_processed} where processed successfully."); } }
/** * ajax_add_thumbnail() * * Adds a thumbnail to user meta and returns thumbnail html * */ public function ajax_add_thumbnail() { if (!current_user_can('upload_files')) { die(''); } $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0; $user_id = isset($_POST['user_id']) ? absint($_POST['user_id']) : 0; $thumbnail_id = isset($_POST['thumbnail_id']) ? absint($_POST['thumbnail_id']) : 0; if ($post_id == 0 || $user_id == 0 || $thumbnail_id == 0 || 'mt_pp' !== get_post_type($post_id)) { die(''); } check_ajax_referer("mt-update-post_{$post_id}"); //Save user meta update_user_option($user_id, 'metronet_post_id', $post_id); update_user_option($user_id, 'metronet_image_id', $thumbnail_id); //Added via this thread (Props Solinx) - https://wordpress.org/support/topic/storing-image-id-directly-as-user-meta-data set_post_thumbnail($post_id, $thumbnail_id); if (has_post_thumbnail($post_id)) { $thumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'thumbnail', false, ''); $post_thumbnail = sprintf('<img src="%s" width="150" height="150" title="%s" />', esc_url($thumb_src[0]), esc_attr__("Upload or Change Profile Picture", 'metronet-profile-picture')); $crop_html = $this->get_post_thumbnail_editor_link($post_id); $thumb_html = sprintf('<a href="#" class="mpp_add_media">%s</a>', $post_thumbnail); $thumb_html .= sprintf('<a id="metronet-remove" class="dashicons dashicons-trash" href="#" title="%s">%s</a>', esc_attr__('Remove profile image', 'metronet-profile-picture'), esc_html__("Remove profile image", "metronet-profile-picture")); die(json_encode(array('thumb_html' => $thumb_html, 'crop_html' => $crop_html, 'has_thumb' => true))); } die(json_encode(array('thumb_html' => '', 'crop_html' => '', 'has_thumb' => false))); }