Getting the attachment URL instead of the ID (Wordpress) - wordpress

I have a script that allows me to upload an image to wordpress from the front end. I then need it to post the file to the post_meta. Right now it's working fine, BUT I end up with the Attachment ID and need the LINK to the file.
Here's the code that is handling this particular function.
if ($_FILES) {
foreach ($_FILES as $k => $v) {
if ($k != 'poster_has_paid' && $k != 'featured_image') {
if ($_FILES[$k]) {
wpo_poster_insert_attachment($k, $post_id, false, $k);
}
}
}
}
And here is the function wpo_poster_insert_attachment
function wpo_poster_insert_attachment($file_handler, $post_id, $setthumb = 'false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) {
__return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload($file_handler, $post_id);
if ($setthumb) {
update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
if (!$setthumb && $post_meta != '') {
update_post_meta($post_id, $post_meta, $attach_id);
}
return $attach_id;
Again, it's updating the field with the attach_id, and I'd like it to update the attach_url
PS I will give thanks when I have enough posts to do so. Thanks in advance.

Something like this should work
function wpo_poster_insert_attachment($file_handler,$post_id,$setthumb='false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) {
update_post_meta($post_id,'_thumbnail_id',$attach_id);
// Get the attachment/thumbnail source, and add it to the post meta as well.
$src = wp_get_attachment_image_src($thumbnail_id, 'full');
update_post_meta($post_id,'_thumbnail_src', #$src[0]);
}
if(!$setthumb && $post_meta!=''){
update_post_meta($post_id, $post_meta, $attach_id);
}
return $attach_id;
}
But normally, since you already have the thumbnail_id stored in the post meta, you might want to pull the attachment source at run-time:
if($thumbnail_id = get_post_meta($post->ID, '_thumbnail_id', true)) {
$attachment_size = 'full';
$src = wp_get_attachment_image_src($thumbnail_id, $attachment_size);
if(!$src) {
$src = array('http://mysite.com/path/to/default-image.png', 640, 480);
}
echo '<img src="'.esc_url($src[0]).'" alt="" />';
}

Related

Functions.php to set all external links with rel:="nofollow"

when i use the code:
add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');
function my_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}
function my_nofollow_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {
$link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
} elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
$link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
}
return $link;
}
only in the_content and the_excerpt the links get a nofollow attribute. How i can edit the code, that the whole wordpress site use this functions (footer, sidebar...)
Thank you
a good script which allows to add nofollow automatically and to keep the other attributes
function nofollow(string $html, string $baseUrl = null) {
return preg_replace_callback(
'#<a([^>]*)>(.+)</a>#isU', function ($mach) use ($baseUrl) {
list ($a, $attr, $text) = $mach;
if (preg_match('#href=["\']([^"\']*)["\']#', $attr, $url)) {
$url = $url[1];
if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) {
if (preg_match('#rel=["\']([^"\']*)["\']#', $attr, $rel)) {
$relAttr = $rel[0];
$rel = $rel[1];
}
$rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"';
$attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel;
$a = '<a ' . $attr . '>' . $text . '</a>';
}
}
return $a;
},
$html
);
}
The idea is to add your action in the full html buffer, once everything is loaded and filtered, not only in the 'content' area.
BE VERRY CAREFULL WITH THIS !!!! This action is verry RAW and low-level... You can really mess up everything with theses buffer actions. But it's also very nice to know ;-)
It works like this :
add_action( 'wp_loaded', 'buffer_start' ); function buffer_start() { ob_start( "textdomain_nofollow" ); }
add_action( 'shutdown', 'buffer_end' ); function buffer_end() { ob_end_flush(); }
Then do the replace action and setup the callback :
Juste imagine the $buffer variable as your full site in HTML, as it will load.
function textdomain_nofollow( $buffer ) {
return preg_replace_callback( '/<a[^>]+/', 'textdomain_nofollow_callback', $buffer );
}
Here is how I do the href checking (read my comments) :
function textdomain_nofollow_callback( $matches ) {
$link = $matches[0];
// if you need some specific external domains to exclude, just use :
//$exclude = '('. home_url() .'|(http|https)://([^.]+\.)?(domain-to-exclude.org|other-domain-to-exclude.com)|/)';
// By default, just exclude your own domain, and your relative urls that starts by a '/' (if you use relatives urls)
$exclude = '('. home_url() .'|/)';
if ( preg_match( '#href=\S('. $exclude .')#i', $link ) )
return $link;
if ( strpos( $link, 'rel=' ) === false ) {
$link = preg_replace( '/(?<=<a\s)/', 'rel="nofollow" ', $link );
} elseif ( preg_match( '#rel=\S(?!nofollow)#i', $link ) ) {
$link = preg_replace( '#(?<=rel=.)#', 'nofollow ', $link );
}
return $link;
}
It works well in my experience...
Q

move_uploaded_file() not working on wordpress front end

I have working code that uploads an image from the front end and sets it as a featured image and custom field photo for a custom post type but I am unable to figure out how to set the upload path.
Essentially if I have an employee I would like to use the custom field last_first to generate a folder path:
"wp-content/uploads/employee_mug/[last_first]/"
which would contain a photo of the employee. I require this as the folder structure is required for another page. The code is in my functions.php file but is simply in an if statement.
I've attempted to use move_uploaded_file with no success.
if (isset($_POST['last_first']) && is_user_logged_in()){
$my_post = array (
'post_type' => 'employee',
'post_status' => 'publish', // can also draft, private or publish
'post_title' => $_POST['last_first'],
);
$postID = wp_insert_post($my_post);
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$attach_id = media_handle_upload( $file, $postID );
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
update_field('date_of_birth', $_POST['dob'], $postID);
update_field('sex', $_POST['sex'], $postID);
die;}
I would like that when a file is attached the end result be:
"wp-content/uploads/employee_mug/[last_first]/1.jpg"
UPDATE 1.0
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$path = "./wp-content/uploads/mug_shots/";
$path .= $name;
if ( wp_mkdir_p( $path ) ) {
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
} else {
wp_mkdir_p( $path );
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
}
}
now checks to see if a folder was create and if not it will make one with the employee name but the move_uploaded file is not moving the photo into the generator folder. I simply need to find a way to make the file move to the generated folder at this point, Any help would be greatly appreciated!
UPDATE 2.0
the bellow code moves the file to wp-content/uploads/employee_mug/ but will not move it into the generated folder with the employee is name. I'm very close here I simply need the file moved into the employee is named folder at this point!
$name = $_POST['last_first'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
//for MKDIR FOR CREATION
$path = "./wp-content/uploads/employee_mug/";
$path .= $name;
//FOR MOVING UPLOADED IMAGE
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $name;
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
if ( wp_mkdir_p( $path ) ) {
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
} else {
wp_mkdir_p( $path );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
}
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
////////////////////////////////////////////////////////////////////////////////////////////
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
UPDATE 3.0 SOLVED ******
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $_POST['last_first'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}

Why $_FILES['uploadfiles'] not working and running blank?

I am trying to upload image through custom.php in wordpress when i print the
`$_FILES['uploadfiles'];`
its not showing any thing the same code i have used before one day in another wordpress site the code is working good over there on ec2 my current wordpress is on ec2 and have bitnami image i have checked all configuration like in php.ini file upload_tmp_dir=/opt/bitnami/php/tmp ,file_uploads=on,upload_max_filesize=40M.
i am not using any form i have just added upload field in one hook that display that field on one page.
I am using thesis theme.so any boday have any idea why this happening with this code on while one copy of same code work on another wordpress with guru theme.
Bellow is the code i am using to upload image.
<input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" />
<?php
$uploadfiles = $_FILES['uploadfiles'];
print_r ($uploadfiles);
if (is_array($uploadfiles)) {
echo "1";
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
echo $attach_data;
echo $filedest;
wp_update_attachment_metadata( $attach_id, $attach_data );
//echo wp_get_attachment_url( $attach_id );
//exit();
$urlimage=wp_get_attachment_url( $attach_id );
$_SESSION["oldurl"]=$urlimage;
echo $_SESSION["oldurl"];
}
}
}
?>

Rename file while uploading?

I have the following code in my Wordpress. I need to add every uploaded image a counting number like, image_1, image_2, image_3 and so on..
The purpose of this is that every uploaded image attached to post, gets post ID name, and counting number in end to it.
It would be great if some one help me with this. Thanks!
<?php
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_25894_handle_upload');
function wpse_25894_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $file;
}
function wpse_25894_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $fileinfo;
}
function wpse_25894_custom_upload_dir($path)
{
/*
* Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
*/
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path; //error or uploading not from a post/page/cpt
/*
* Save uploads in ID based folders
*
*/
$customdir = '/' . $_REQUEST['post_id'];
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'wpse_123240_rename_intermediates' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Build our new image name
$postid = $_REQUEST['post_id'];
$random = rand(1,5);
$new_name = $dir . $postid . '_' . $random . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
?>
Now this code generates images named postid_randomnumber.jpg
I just need to add 20 images at maximum, so if I can have numbers from 1-20, that is also working fine with my purposes.
-- UPDATE --
I canged the last part of code to this, it is not maybe the cleanest solution, but it works:
function wpse_123240_rename_intermediates( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
//$count = get_option( 'wpa59168_counter', 1 );
// Build our new image name
$postid = $_REQUEST['post_id'];
$increment = 1;
$new_name = $dir . $postid . '_1' . $ext;
while(is_file($new_name)) {
$increment++;
$new_name = $dir . $postid . '_' . $increment . $ext;
}
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}

Wordpress change media upload directory

I manage to upload my medias using the below code. Unfortunately, the media are saving on the same month as the front-end form post date (/2014/09/). This is to upload the users profile image, not attached to any post. Hope someone can help out cause i couldnt find any resources online. Thank you!
// UPLOAD USER IMAGE
function upload_user_image($user, $nonce_name, $input_name, $field_name ) {
if (
isset( $_POST[$nonce_name] )
&& wp_verify_nonce( $_POST[$nonce_name], $input_name )
) {
$arr_file_type = wp_check_filetype(basename($_FILES[$input_name]['name']));
$uploaded_file_type = $arr_file_type['type'];
$allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png');
if(in_array($uploaded_file_type, $allowed_file_types)) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload( $input_name, 0 );
if ( is_wp_error( $attachment_id ) ) {
$upload_feedback = 'There was a problem with your upload.';
} else {
$upload_feedback = false;
}
update_user_meta( $user, $field_name, $attachment_id );
} else {
$upload_feedback = 'Please upload only image files (jpg, gif or png).';
}
} else {
$upload_feedback = 'Security check failed';
}
}

Resources