Am using Unveil plugin to lazy load images in wordpress. I would like to change the img attributes to something like this.
<img data-src="http://lorempixel.com/g/800/500/city/10" data-src-retina="http://lorempixel.com/g/1280/800/city/10" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" />
With this link I was able to achieve src now I kindly request someone to help on how to generate data-src and data-src-retina attributes.
Later I want to use them in my function in funtions.php
Bellow is my code snippet, but its not working only the src
function image_tag($html, $id, $alt, $title) {
//generate data url
$type = pathinfo($img, PATHINFO_EXTENSION);
$data = file_get_contents($img);
$src = 'data:image/' . $type . ';base64,' . base64_encode($data);
return preg_replace(array(
'/'.str_replace('//','//',get_bloginfo('url')).'/i',
'/s+width="d+"/i',
'/s+height="d+"/i',
'/alt=""/i'
),
array(
'data-src=" "',
'src="'.$src.'"',
'data-src-retina=" "',
'alt="' . $title . '"'
),
$html);
}
add_filter('get_image_tag', 'image_tag', 0, 4);
Related
I'm writing a WP shortcode to disaply random images from a path that's given by input.
[random-image pag="" class=""]
The code works nicely, but returns the correct url + the page i've put the shortcode.
Example:
I'm currently renovating my website locally.
The actual URL is: https://localhost/z/
But after I've finished coding it will become https://localhost/
If I put the shortcode on /prova page ( https://localhost/z/prova/ )
the image src will show "wp-content/themes/generatepress_child/img/home/2.jpg" which is correct but if I mouse over it it shows the full path like this:
"https://localhost/z**/prova/**wp-content/themes/generatepress_child/img/home/2.jpg" instead of "https://localhost/z/wp-content/themes/generatepress_child/img/home/2.jpg"
I've tried changing the $imagesDir in
$imagesDir = get_site_url() . 'wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';
or $imagesDir = 'z/wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';
or even: $imagesDir = 'https://localhost/z/wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';
But all of these return with
// Random img
function random_image( $atts, $content = null ) {
$values = shortcode_atts( array(
'pag' => 'home',
'class' => 'imgrnd',
), $atts );
$imagesDir = 'wp-content/themes/generatepress_child/img/' . esc_attr($values['pag']) .'/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
return '<img src="' . $randomImage . '" class="' . esc_attr($values['class']) . '">';
}
add_shortcode( 'random-image', 'random_image' );
I've solved this by changing the return output with
'<img src="' . '/z/' . $randomImage . '" class="' . esc_attr($values['class']) . '">';
But i still don't like this solution, is there a better way to fix it?
I have a function in wordpress which finds links and changes them.
//FINDS ALL IMAGE LINKS
preg_match_all('/\S*\bwww\.tradingview\.com\S*/', $data['post_content'], $matches);
//FOR EACH IMAGE LINK IN THE CONTENT...
foreach( $matches[0] as $imgURL ):
I'm trying to make it so that it ignores any link that is commented out like this:
<!-- https://www.tradingview.com -->
I'm not sure how to accomplish this. I'm very new to web dev so apologies if I've left anything out.
Edit: I made a typo and added the ! in the first part of the comment
Edit: Here's the rest of my code, including the print statement.
function customPostSave($data , $postarr) {
// INCLUDES REQUIRED WP FILES
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
//FINDS ALL IMAGE LINKS
preg_match_all('/\S*\bwww\.tradingview\.com\S*/', $data['post_content'], $matches);
echo '<pre>', print_r($matches[0]), '</pre>';
//FOR EACH IMAGE LINK IN THE CONTENT...
foreach( $matches[0] as $imgURL ):
// REMOVES ALL SPACES AROUND THE URL
$imgURL = trim($imgURL);
// STORE ORIGINAL URL
$imgURLoriginal = $imgURL;
// PREPARES FILE INFORMATIONS
$file_array = array();
$file_array['name'] = basename($imgURL);
if( !preg_match('/(\.png)$/i', $imgURL) ) $file_array['name'] .= '.png';
$file_array['tmp_name'] = download_url($imgURL);
// DOWNLOADS THE IMAGE AND UPLOADS IT LOCALLY
$id = media_handle_sideload($file_array, $postarr['post_ID']);
$localURL = wp_get_attachment_url($id);
// GRABS THE POST TAGS
$tags = wp_get_object_terms($postarr['post_ID'], 'post_tag');
$imgTags = array();
if( !empty($tags) ):
foreach( $tags as $tag ):
array_push($imgTags, $tag->name);
endforeach;
endif;
// REPLACES THE IMAGE URL IN THE CONTENT, WITH <IMG> TAGS WITH SPECIFIC STYLES
$data['post_content'] = str_replace(
$imgURL,
'<!-- '.$imgURLoriginal.' -->
<p style="text-align:center"><img src="' . $localURL . '" alt="' . implode($imgTags, ', ') . '" style="width:100%;"></p>',
$data['post_content']
);
endforeach;
return $data;
} add_filter('wp_insert_post_data' , 'customPostSave' , '99', 2);
It is hard to provide you with a good answer due to lack of infomation. You should update your question with output from echo '<pre>', print_r($matches[0]), '</pre>'; so we know what data you are working with.
If all start with "<--", you can do it like this:
foreach($matches[0] as $imgURL) {
if(substr($imgURL, 0, 3) !== "<--") {
echo $imgURL;
}
}
I'm trying to create a plugin that will delete pictures and additional info from database on deleting custom post (sp_venue) via admin panel (wp-admin/edit-tags.php)
In the plugin I'm using this to catch the event:
add_action( 'delete_post', 'kg_delete_post' );
function kg_delete_post($postId) {
$post = get_post($postId);
if ($post->post_type != 'attachment') {
return false;
}
$url = str_replace($dirs['baseurl'],'',$post->guid);
$urlParts = explode("/",$url);
$numberOfParts = sizeof($urlParts) - 1;
$dirs = wp_upload_dir();
$fileNameParts = explode(".", $urlParts[$numberOfParts]);
$fileName = str_replace('.' . end($fileNameParts), '', $urlParts[$numberOfParts]) . "-*." . end($fileNameParts);
$path =$dirs['basedir'] ."/". $urlParts[$numberOfParts-2] . "/" . $urlParts[$numberOfParts-1] . "/";
$fullPath = $path . $urlParts[$numberOfParts];
$fullPathSearch = $path . $fileName;
#unlink($fullPath);
foreach (glob($fullPathSearch) as $filename) {
#unlink($path . $filename);
}
}
It works with:
wp_delete_post($Id, true)
But looks like the event on deleting via admin panel is no the same.
What should i use to make it works?
Thank you.
Solved by adding my js on in admin panel to customize the click on delete button.
I try to show image as follows:
function part_profile_record_pdf_form()
{
$sql = "SELECT * FROM part_profile WHERE part_id=" . arg(2);
$query = db_query($sql);
$dataFormDb = db_fetch_object($query);
$url = '../../../' . $dataFormDb->image;
$css_file = drupal_get_path('module', 'part_profile') . '/css/part_profile_pdf.css';
$output = "<style>" . file_get_contents($css_file) . "</style>";
$output .= "<html><body ><div id=\"wrapper\">";
$output.= '<img height="156" width="128" id="img_profile" src="'.$url.'">';
$output.="</div></body></html>";
return $output;
}
I can see the image by the following function:
function part_profile_make_pdf() {
$css_file = drupal_get_path('module', 'part_profile') . '/css/part_profile_pdf.css';
$output= part_profile_record_pdf_form();
print $output;
}
But when I try to make pdf as follows , no image is shown giving 'x' and 'image not readable or empty':
function part_profile_make_pdf() {
$css_file = drupal_get_path('module', 'part_profile') . '/css/part_profile_pdf.css';
$output= part_profile_record_pdf_form();
// print $output;
require_once(realpath(".") . "/sites/all/libraries/dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload');
if (isset($_SESSION['indv_report_file_name']) && !empty($_SESSION['indv_report_file_name'])) {
$filename = $_SESSION['indv_report_file_name'];
} else {
$rand_val = rand(0, 1000);
$filename = "eureka_" . $rand_val . ".pdf";
$_SESSION['indv_report_file_name'] = $filename;
}
$dompdf = new DOMPDF();
$dompdf->load_html($output);
// $dompdf->set_paper(DEFAULT_PDF_PAPER_SIZE, 'a4');
// "a4" => array(0,0,595.28,841.89),
$dompdf->set_paper(array(0, 0, 595.28, 420), "portrait"); // 12" x 12"
$dompdf->render();
$dompdf->stream("participant-profile.pdf", array("Attachment" => false));
exit(0);
}
I already set DOMPDF_ENABLE_REMOTE to true in my config dompdf_config.inc.php. have any idea. Thanks in advance.
After a little testing in my own DOMPDF environment, I reckon this will be due to the relative path to your image. Currently you're using
$url = '../../../' . $dataFormDb->image;
Which is fine for the preview in HTML, the browser can find the image.
But when DOMPDF tries to process the HTML and find the image, it's doing so from a system perspective, like PHP would if you were doing a file_exists(). So you need to add the full path:
$url = $_SERVER['DOCUMENT_ROOT'] . '/path/to/dir/' . $dataFormDb->image;
or just hardcode it
$url = '/home/username/sitename/public_html/images/' . $dataFormDb->image;
So you might need some logic to say: am I doing a preview? Then use relative path. Or am I doing a PDF render? Then use full path. But I'll leave that to you!
I am currently working on a multiple image uploader with file directory. I am wanting to store file name inside my MySQL.
How can I store these variables(image names) inside my table through php ?
How can I retrieve the variables through php?
URL Generate by uploader:
http://www.website.com/imageupload/index.php?i=4ff4bfd02c241.jpg
http://www.website.com/imageupload/index.php?i=4ff4bfd02c242.jpg
Filename:
4ff4bfd02c241.jpg
4ff4bfd02c242.jpg
Table Name: urlimage
id: autoincrement
image_name
I am able to echo out the path and the name through this:
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
foreach ($images as $image) {
echo '<div><p>' . $path . $image . '</p><img src="' . $path . $image . '" /></div>';
}
?>
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
if(is_array($images)){
$sql = "INSERT INTO `urlimage` (`image_name`) VALUES ";
foreach ($images as $image) {
//echo '<div><p>' . $path . $image . '</p><img src="' . $path . $image . '" /></div>';
$value[] = "(".$path.$image.")"; // collect imagenames
}
$sql .= implode(',', $value).";"; //build query
//don't know how you send queries, you should use a kind of mysqli-functionality
queryfunction($sql);
}
Addiontally: you should think of using $_POST rather than $_GET becaus there's a length limit depending on the browser (some of them cut URLs after 255 chars).
Also never put in userdefined content directly into you DB. You'll need some kind of escaping ( http://php.net/manual/en/function.mysql-real-escape-string.php ).