So, I have the following to add an image in the wordpress post:
<?php
global $current_user;
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
$custom_field_1 = $_POST['custom_1'];
$custom_field_2 = $_POST['custom_2'];
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => $_POST['cat'],
'tags_input' => $tags,
'post_status' => 'publish',
'post_type' => $_POST['post_type']
);
$pid = wp_insert_post($post);
add_post_meta($pid, 'rh_content', $custom_field_1, true);
add_post_meta($pid, 'rh_item', $custom_field_2, true);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
wp_redirect( home_url() );
}
do_action('wp_insert_post', 'wp_insert_post');
?>
So, it allows an image to be uploaded which can be shown by get_the_post_thumbnail.
<?php if ( has_post_thumbnail() ) { ?>
<div class="rhmi_thumb">
<?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'rh_site') ?>
</div>
<?php } ?>
However, even without the image uploaded (ie. there is no thumbnail), it still shows class="rhmi_thumb". So, I am guessing that the whether an image is uploaded or not, the post thinks that there is a thumbnail.
What modification should be made in the post upload form?
Thanks
For uploading image into page/post you have to use wp_insert_attachment(). I have added the link of wordpress site from there you can get the example that how you can implement that. Thanks!
Related
I'm using the below script in the functions.php file to upload a PDF to a custom post type, however I am unsure of how to then retrieve the PDF URL within the WordPress Loop:
function add_custom_meta_boxes() {
add_meta_box('wp_custom_attachment', 'PDF Newsletter', 'wp_custom_attachment', 'newsletter', 'normal', 'high');
}
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_custom_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your PDF here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25">';
$filearray = get_post_meta( get_the_ID(), 'wp_custom_attachment', true );
$this_file = $filearray['url'];
if($this_file != ""){
$html .= '<div>Current file:<br>"' . $this_file . '"</div>';
}
echo $html;
}
add_action('save_post', 'save_custom_meta_data');
function save_custom_meta_data($id) {
if(!empty($_FILES['wp_custom_attachment']['name'])) {
$supported_types = array('application/pdf');
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
if(in_array($uploaded_type, $supported_types)) {
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
}
}
else {
wp_die("The file type that you've uploaded is not a PDF.");
}
}
}
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');
Here is the loop I am using, including my failed attempt of adding the PDF url:
<?php
$args = array( 'post_type' => 'newsletter', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content(); ?>
<?php
$news_pdf = get_post_meta( $post_id, 'wp_custom_attachment', true );
$news_pdf['url']
?>
<?php echo '</div>';
endwhile;
?>
Please first change $post_id to get_the_ID() within your loop.
Change $news_pdf['url'] to:
echo $news_pdf['url'];
Thanks
I can successfully create a post and also update or insert the data to the custom fields.
But i've no Idea how to update or check the multiselect checkboxes.
Below is the code for creating a post with featured image and inserting custom fields.
Please suggest me to add also the multiple select checboxes.
<?php
error_reporting(E_ALL);
#ini_set('display_errors', 1);
require('wp-load.php');
global $user_ID;
$title = $_REQUEST['title'];
$content = $_REQUEST['content'];
$status = $_REQUEST['status'];
$date = $_REQUEST['date'];
$type = $_REQUEST['type'];
$bedrooms = $_REQUEST['bedrooms'];
$bathrooms = $_REQUEST['bathrooms'];
$floor = $_REQUEST['floor'];
$sqft = $_REQUEST['sqft'];
$afterfee = $_REQUEST['afterfee'];
$sp = $_REQUEST['saleprice'];
echo $title;
echo $content;
echo $status;
echo $type;
echo $bedrooms;
echo $bathrooms;
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => $status,
'post_date' => $date,
'post_author' => $user_ID,
'post_type' => $type,
'post_category' => array(0)
);
$id = wp_insert_post($new_post);
update_post_meta($id,'fave_property_bedrooms',$bedrooms);
update_post_meta($id,'fave_property_bathrooms',$bathrooms);
update_post_meta($id,'fave_video_url','www.google.com');
update_post_meta($id,'fave_property_price_postfix',$afterfee);
update_post_meta($id,'fave_property_land_postfix',$sqft);
update_post_meta($id,'fave_property_land',$floor);
update_post_meta($id,'fave_property_price_prefix','Start From');
update_post_meta($id,'fave_property_price_postfix','Per Month');
update_post_meta($id,'fave_property_price',$sp);
$post_id=$id;
// only need these if performing outside of admin environment
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// example image
$image = 'https://clevertechie.com/img/main/php-curl-tutorial.png';
// magic sideload image returns an HTML image, not an ID
$media = media_sideload_image($image, $post_id);
// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
);
// reference new image to set as featured
$attachments = get_posts($args);
if(isset($attachments) && is_array($attachments)){
foreach($attachments as $attachment){
// grab source of full size images (so no 300x150 nonsense in path)
$image = wp_get_attachment_image_src($attachment->ID, 'full');
// determine if in the $media image we created, the string of the URL exists
if(strpos($media, $image[0]) !== false){
// if so, we found our image. set it as thumbnail
set_post_thumbnail($post_id, $attachment->ID);
// only want one image
break;
}
}
}
}
?>
I'm using a wp theme which comes with an ajax search feature to get live suggestions. However the suggestion element displays the post type (under the resulted title) such as "Portfolio item" and I would like to replace it with the post (portfolio item's) category. Any solution? Thanks in advance!
$suggestions=array();
global $post;
foreach ($posts as $post): setup_postdata($post);
// Initialise suggestion array
$suggestion = array();
$suggestion['label'] = esc_html($post->post_title);
$suggestion['link'] = get_permalink();
$suggestion['image'] = (has_post_thumbnail( $post->ID )) ? get_the_post_thumbnail($post->ID, 'thumbnail', array('title' => '')) : '<i class="icon-salient-pencil"></i>' ;
if(get_post_type($post->ID) == 'post'){
$suggestion['post_type'] = __('Story',NECTAR_THEME_NAME);
} else if(get_post_type($post->ID) == 'page'){
$suggestion['post_type'] = __('Page',NECTAR_THEME_NAME);
} else if(get_post_type($post->ID) == 'portfolio'){
$suggestion['post_type'] = __('Portfolio item',NECTAR_THEME_NAME);
//show custom thumbnail if in use
$custom_thumbnail = get_post_meta($post->ID, '_nectar_portfolio_custom_thumbnail', true);
if(!empty($custom_thumbnail) ){
$attachment_id = pn_get_attachment_id_from_url($custom_thumbnail);
$suggestion['image'] = wp_get_attachment_image($attachment_id,'portfolio-widget');
}
} else if(get_post_type($post->ID) == 'product'){
$suggestion['post_type'] = __('Product',NECTAR_THEME_NAME);
}
I have a plugin that adds a meta box with file upload form, the plugin works perfectly, displays the link of the image in the meta box (View Image), load the file, and once published the post, it views in the theme. (in the example I'm using an image file):
<?php
/* Plugin Name: Custom Meta Upload Template*/
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_upload() {
add_meta_box( 'meta_upload', __( 'Upload Image', 'meta_upload_domain' ),'meta_upload_callback', 'post' );}
add_action( 'add_meta_boxes', 'custom_upload' );
function meta_upload_callback( $post ) {
global $post;
$custom = get_post_custom($post->ID);
$download_image01 = get_post_meta($post->ID, '_image01', true);
echo '<p><label for="document_file">Upload document:</label><br />';
echo '<input type="file" name="document_file" id="document_file" /></p>';
echo '</p>';
if(!empty($download_image01) && $download_image01 != '0') {
echo '<p>View Image</p>';
}
}
function meta_upload_save( $post_id ) {
global $post;
if(strtolower($_POST['post_type']) === 'page') {
if(!current_user_can('edit_page', $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
if(!empty($_FILES['document_file'])) {
$file = $_FILES['document_file'];
$upload = wp_handle_upload($file, array('test_form' => false));
if(!isset($upload['error']) && isset($upload['file'])) {
$title = $file['name'];
$ext = strrchr($title, '.');
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
'post_mime_type' => 'image',
'post_title' => addslashes($title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post->ID
);
$attach_key = '_image01';
$attach_id = wp_insert_attachment($attachment, $upload['file']);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
add_action( 'save_post', 'meta_upload_save' );
and he called the file in the theme:
<?php
$download_image01 = get_post_meta($post->ID, '_image01', true);
if(!empty($download_image01) && $download_image01 != '0') { ?>
<div class="section-content">
<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />
</div>
<?php }?>
I repeat, the plugin works, but the problem is that I can not place a button or a checkbox that deletes the file when, for example, I want to edit the post, and delete the file, and of course the link "View Image" disappears
Any idea!!
Whenever you want to edit these fields echo the value of the custom fields look like this...
<input type="" value="<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />">
When you edit the post it's get the value and show the uploaded image's to you.
I don't know if that can help, but I use this code to exclude Attachment when I delete a Custom Post:
add_action('before_delete_post', 'delete_all_attached_media');
function delete_all_attached_media($post_id)
{
if (get_post_type($post_id) == "your-custom-post-type") {
$attachments = get_attached_media('', $post_id);
foreach ($attachments as $attachment) {
wp_delete_attachment($attachment->ID, 'true');
}
}
}
This could be a duplicate question, but not one of these similiar questions has touched the get_attached_media part, which is what I need help with.
If I don't have any Featured Image in the post, I want to use the image attached in the content of the post, as a Featured Image.
Here is what I'm trying and failing:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
if(get_post_thumbnail_id() == TRUE) {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
}
else {
$image_url = wp_get_attachment_image_src( get_attached_media('image'), 'backstretch');
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo $image_url[0]; ?>">
I've realised I need to fetch the url of get_attached_media('image') for it to work. But even with using foreach I've not managed this:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
function get_image($arr) {
$images = get_attached_media('image');
$arr = [];
foreach($images as $image) {
$url = wp_get_attachment_url($image->ID);
$image_url = wp_get_attachment_image_src($url, 'backstretch');
$arr[] = $image_url;
}
return $arr;
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo get_image($arr[0]); ?>">
My url becomes this:
http://site.loc/wp/2016/01/05/postname/%3Cbr%20/%3E%3Cfont%20size='1'%3E%3Ctable%20class='xdebug-error%20xe-notice'%20dir='ltr'%20border='1'%20cellspacing='0'%20cellpadding='1'%3E%3Ctr%3E%3Cth%20align='left'%20bgcolor='
Which clearly states that it gets image attributes as url. I've googled and played with the code, and I just can't find realize the problem.
I really appreciate your help.
Also if you still find this as a duplicate, I apologize!
I use this function to get all available images from a WordPress post:
function get_post_images( $post = null ) {
if ( $post === null ) {
global $post;
}
/* Get the featured image of the post */
if ( has_post_thumbnail() ) {
$images[] = get_post_thumbnail_id( $post->ID );
}
/* If the post contains galleries, get all images from them */
if( has_shortcode( $post->post_content, 'gallery' ) ) {
$galleries = get_post_galleries( $post, false );
foreach ( $galleries as $gallery ) {
$ids = explode( ',', $gallery['ids'] );
$images = array_merge( $images, $ids );
}
}
/* Get all single images in the post */
preg_match_all("/wp-image-(\d+)/", $post->post_content, $imgs );
foreach ($imgs[1] as $img) {
$images[] = $img;
}
/* get all images attached to the post
* not sure if this is a good idea, there might be images attached
* which were not supposed to be published */
$post_images = get_posts( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'numberposts' => -1,
'post_mime_type' => 'image',
'exclude' => $images ) );
foreach ( $post_images as $image ) {
$images[] = $image->ID;
}
/* As a fallback, add a predefined default image */
if ( sizeof( $images ) == 0 && $this->default_image != null) {
$images[] = $this->default_image;
}
/* remove duplicated images */
$images = array_unique( $images );
return $images;
}
The function returns an array containing all image IDs related to the given post, if you only need one you can extract that easily:
$images = get_post_images();
echo wp_get_attachment_image( array_shift( $images ) );
Well, I fixed the problem. I tried to use the popular get_that_image plugin, but it didn't fix my problem. At the end of the day I trashed the get_attached_media, and used this function which I found here.
function crisp_catch_that_image() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
if (!empty($image_url)) {
return $image_url[0];
}
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (empty($matches[1])) {
return '';
}
return $matches[1][0];
return $first_img;
}