wp_get_attachment_url() process full file path like
http://example.com/wp-content/uploads/2014/12/aura.mp3
I want the url without http://example.com/
So, I want above example as wp-content/uploads/2014/12/aura.mp3 instead of http://example.com/wp-content/uploads/2014/12/aura.mp3. How to do it?
You can really easily explode it by / and then take the part with index 3. Example
$url = wp_get_attachment_url(id); //id is file's id
$urllocal = explode(site_url(), $url)[1]; //output local path
Here is the WordPress way using WordPress functions (avoid hacking):
$fullsize_path = get_attached_file( $attachment_id ); // Full path
$filename_only = basename( get_attached_file( $attachment_id ) ); // Just the file name
WordPress has tons of functions, so first try to find the function on the docs: https://developer.wordpress.org/reference/functions/get_attached_file/
You can use PHP's function explode.
Here is the code:
<?php
$image_url = wp_get_attachment_url( 9 ); //ID of your attachment
$my_image_url = explode('/',$image_url,4);
echo $my_image_url[3];
?>
You can implode your entire url on / and array_slice from the end, then implode it back in on /.
$url = wp_get_attachment_url($item->ID); //id is file's id
$url_relative = implode(array_slice(explode('/', $url),-3,3),'/');
//Returns: 2019/08/image.jpg
That way if your WordPress is on a subdomain or localhost or the images are on S3 it won't crash.
Related
After creating new post I need to generate and store the .vcf file in storage. I don't know how I can do this after post save. Didn't find help to develop such function. Please help!
Try this :
On "save_post" hook you can write function. That will create .vcf file with the name of post_title at specified directory.
function my_project_create_vCard( $post_id ) {
$vpost = get_post($post->ID);
$filename = strtolower(str_replace(" ","-",$vpost->post_title)).".vcf";
header('Content-type: text/x-vcard; charset=utf-8');
header("Content-Disposition: attachment; filename=".$filename);
$data=null;
$data.="BEGIN:VCARD\n";
$data.="VERSION:2.1\n";
$data.="FN:".$vpost->post_title."\n"; // get post title
$data.="EMAIL:" .get_field('email',$vpost->ID)."\n"; // get acf field value
$data.="END:VCARD";
$filePath = get_template_directory()."/".$filename; // you can specify path here where you want to store file.
$file = fopen($filePath,"w");
fwrite($file,$data);
fclose($file);
}
add_action( 'save_post', 'my_project_create_vCard' );
I am working on my personal wordpress site that distribute images.
In single post page, I registered several images via ACF(Advanced Custom Fields) and I know how to get image path/filename through get_field ACF function.
I just googled then found this page, but how can I apply this technique to wordpress site?
Download multiple images into zip
Now I am stuck...
On single post page, place the url of download_zip.php file, where you will place all your code for creating zip.
On single post page:
Download ZIP
In variable 'model_id', place the post id of the single post.
Now create a download_zip.php file on the root of your wordpress setup, where wp-config.php file exists.
Here is the code of download_zip.php file.
<?php
/*File for downloading the gallery zip files*/
$post_id = $_GET['model_id'];
require_once('wp-blog-header.php');
require_once('/wp-admin/includes/file.php');
WP_Filesystem();
$files_to_zip = array();
$zip = new ZipArchive();
$title = get_the_title($post_id);
$destination = wp_upload_dir();
//var_dump($destination);
$destination_path = $destination['basedir'];
$DelFilePath = str_replace(" ","_",$title).'_'.$post_id.'_'.time().'.zip' ;
$zip_destination_path = $destination_path."/".$DelFilePath;
if(file_exists($destination_path."/".$DelFilePath)) {
unlink ($destination_path."/".$DelFilePath);
}
if ($zip->open($destination_path."/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
die ("Could not open archive");
}
//this is only for retrieving Repeater Image custom field
$row1 = get_field('acf_field_name1',$post_id);
$row1 = get_field('acf_field_name2',$post_id);
$rows = array($row1,$row2);
if($rows) {
foreach($rows as $row): ?>
<?php
$explode = end(explode("uploads",$row));
$index_file = array($destination_path,$explode);
$index_file = implode("",$index_file);
$new_index_file = basename($index_file);
$zip->addFile($index_file,$new_index_file);
endforeach;
}
$zip->close();
if(file_exists($zip_destination_path)) {
send_download($zip_destination_path);
}
//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u",filesize($file));
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$basename.'"');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
ob_clean();
flush();
readfile($file); // "Outputs" the file.
unlink($file);
}
?>
Please modify this code according to your requirement such as get_field(), place your image field name inside it, & define your upload directory, so that you can break the url in $explode variable for defining path of image in $index_file variable.
And please also check your destination path stored in $destination_path variable is correct or not.
Hope, this may be helpful to you.
I am in a mesh and need some help.
There are three actor evolved.
Live Site / Production Site (wordpress)
Local Site / Stage / Testing Site (wordpress)
Third party analytic
Background:
I know its very bad but the fact is that the production sites and local sites content are not synced. i.e post id 1 in production can be as post id 24 in local.
Problem Definition:
I was assigned to use the third party's API to grab the list of top post with maximum hits and show it in our website.
$result = file_get_contents($url);
$result_json = json_decode($result, true);
The above lines did that for me easily.
Error:
Since the 3rd party did not had post excerpt, they send URL, image_link, hit_count, post title and author information as JSON.
So on my site I was able to show all these fields very well. But the problem started when my manager added post excerpt to the list.
I tried converting URL to postid and got the post excerpt using:
get_the_excerpt(url_to_postid($top_posts['link']))
It worked for live site. but in the stage and local its not working.
Well post URL has its domain name. Even when I replaced the domain name with my local or stage domain. its not showing any thing. and for some post when it shows the excerpt its not from the same article.
Guys need some idea.
Is there some way that I can get slug from URL?
I tried using explode() function. But sometime the slug is not the last item in array.
Thank you for reading it all. I appreciate you help.
For now I came with a solution. Primarily Using the URL to get post ID, if not found using post title to get the post id.
public static function get_excerpt ( $id = null ) {
$post = get_post($id);
if ( empty($post) ) {
return '';
}
if ( strlen($post->post_excerpt) ) {
// Use the excerpt
$excerpt = $post->post_excerpt;
$excerpt = apply_filters('the_excerpt', $excerpt);
} else {
// Make excerpt
$content = $post->post_content;
$content = strip_shortcodes($content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[…]');
$excerpt = wp_trim_words($content, $excerpt_length, $excerpt_more);
$excerpt = wpautop($excerpt);
}
return apply_filters('wp_trim_excerpt', $excerpt);
}
Called this function to get the excerpt.
$postid = url_to_postid($top_posts['link']);
$postid = $postid!=0 ? $postid : get_page_by_title($post_title, OBJECT, 'post')->ID;
$excerpt = self::get_excerpt($postid);
This worked in my case as I didn't have posts with same title.
I am still waiting for some better solution to my problem.
I'm using the WP function: get_the_author_meta('user_url');
When I echo that to the browser it automatically prepends 'http://' to the URL. How can I avoid this, so that my URLs show exactly as they are entered on the user settings page.
Thanks is advance.
$author_url = get_the_author_meta('user_url'); // e.g. http://www.example.com
$to_remove = array( 'http://', 'https://' );
foreach ( $to_remove as $item ) {
$author_url = str_replace($item, '', $author_url); // to: www.example.com
}
echo $author_url; // now it will not have the http:// part you wish to avoid.
str_replace is probably the most efficient way of doing this.
$author_url = str_replace(array( 'http://', 'https://' ), '', get_the_author_meta('user_url'));
Other URL modification techniques.
For more complicated string replacements which match you could look at using preg_replace .
There is a function called http-build-url() which is included in the php_http.dll extension which might be more suitable for some use cases.
i have create a redir.php and placed in the home directory of wordpress to do the redirect. I want to pass in the post id and then retrieve a custom field value of the post and feed into header('location:'.$url);
www.mysite.com/redir.php?id=30
in redir.php will retrieve post id=30 custom field value and pass it into $url.
this is what I have, but it's not working. It gives me "Parse error: parse error in \redir.php on line 5".
it looks like wordpress environment is not being loaded.
<?php
require('./wp-blog-header.php');
$id = $_GET['id'];
$url= get_field('deal_http_link',post->$id);
header('Location:'.$url);
?>
thanks
Your script has multiple issues:
There is whitespace before the opening <?php tag, so the redirect wouldn't work because the headers will have already been sent. Instead, <?php should be the very first thing in the file.
post->$id is invalid syntax. You probably meant the $id variable which you defined in the preceding line.
To retrieve the value of a custom field, use get_post_meta(), not get_field().
Try something like this instead:
<?php
require('./wp-blog-header.php');
$id = $_GET['id'];
$url = get_post_meta($id, 'deal_http_link', true);
header('Location: ' . $url);
exit();