Load More Button With PHP DirectoryIterator? - php

I have a number of "image gallery" style pages within my WordPress site. I'm trying to find out whether or not it's possible, using the method that I'm using, to create a 'Load More' button so that only 15 (for example, can be whatever) thumbnails load at a time.
To gather the files that should be displayed I'm using PHP's DirectoryIterator. I use the same custom function for every page, but the function itself is a bit long and messy. Essentially, I need to be able to just drop files into the appropriate directory and have them automatically detected and have the thumbnail shown with a link to the full-size image.
I already have this set up and working. Half of the function also checks for any sub-directories and repeats the process for those so that I can have any number of "galleries", each with any number of images, on a single page simply by creating directories and uploading files.
It's rather long, but for reference I feel like I need to paste the full function when asking this question so that people know what I'm working with. The type of content I'm working with is video game screenshots.
function display_screenshots() {
global $post;
$post_data = get_post($post->post_parent);
$parent_slug = $post_data->post_name;
$img_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/';
$thumb_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/thumb/';
$img_list_directory = getcwd() . '/wp-content/uploads/screenshots/' . $parent_slug . '/';
if(is_dir($img_list_directory)) {
$found_shots = array();
echo '<div class="screenshot-thumbs-outer">';
echo '<div class="screenshot-thumbs-inner">';
foreach(new DirectoryIterator($img_list_directory) as $file) {
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$filetypes = array(
"png",
"PNG"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes )) {
$found_shots[] = array(
"fileName" => $fileName
);
}
}
asort($found_shots);
foreach($found_shots as $file) {
$filename = $file['fileName'];
$thumbname = substr($filename, 0, -3).'jpg';
echo '<a href="#" data-featherlight="'.$img_directory.$filename.'" rel="nofollow">';
echo '<img src="'.$thumb_directory.$thumbname.'"/>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
if(is_dir($img_list_directory)) {
foreach(new DirectoryIterator($img_list_directory) as $dir) {
if($dir->isDir() && $dir != '.' && $dir != '..' && $dir != 'thumb') {
$dir_h2 = substr($post->post_title, 0, -12) . ' - ' . str_replace(array('Hd ', ' Hd ', ' Of ', ' The ', ' A ', ' To '), array('HD ', ' HD ', ' of ', ' the ', ' a ', ' to '), ucwords(str_replace("-", " ", $dir))) . ' Screenshots';
$img_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/';
$thumb_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/thumb/';
$img_list_directory = getcwd() . '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/';
$found_shots = array();
echo '<hr />';
echo '<h2>' . $dir_h2 . '</h2>';
echo '<div class="screenshot-thumbs-outer">';
echo '<div class="screenshot-thumbs-inner">';
foreach(new DirectoryIterator($img_list_directory) as $file) {
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$filetypes = array(
"png",
"PNG"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes )) {
$found_shots[] = array(
"fileName" => $fileName
);
}
}
asort($found_shots);
foreach($found_shots as $file) {
$filename = $file['fileName'];
$thumbname = substr($filename, 0, -3).'jpg';
echo '<a href="#" data-featherlight="'.$img_directory.$filename.'" rel="nofollow">';
echo '<img src="'.$thumb_directory.$thumbname.'"/>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
}
}
}
Again, this function is working as intended, I just want to find some way to add 'Load More' functionality so that if there are 150 images, only 15 will load at a time. I'll also need to duplicate the code for the 'Load More' button in the second half of the function so that it's happening for any additional galleries on the page as well.
I realize that this is a lot for someone else to dive into, but I've put a lot of time into combing answers on this site as well as searching Google and I haven't been able to find a solution that's really relevant to the function I'm using to gather/display these images.
Any help will definitely be appreciated.
Thanks!

Related

array_key_exists() expects parameter 2 to be array, null given in wp theme

I was updating my client's website and I encountered this error.
I looked in the file where the error was and it's this code:
function asset_path($filename) {
$dist_path = get_template_directory_uri() . '/dist/';
$directory = dirname($filename) . '/';
$file = basename($filename);
static $manifest;
if (empty($manifest)) {
$manifest_path = get_template_directory() . '/dist/' . 'assets.json';
$manifest = new JsonManifest($manifest_path);
}
if (array_key_exists($file, $manifest->get())) {
return $dist_path . $directory . $manifest->get()[$file];
} else {
return $dist_path . $directory . $file;
}
}
especially, this code in question
if (array_key_exists($file, $manifest->get())) {
return $dist_path . $directory . $manifest->get()[$file];
} else {
return $dist_path . $directory . $file;
}
What's wrong with this code above and how do I fix it?

How to get the file name and file size for the attachment of my custom post type

I am making a plugin with a custom post_type called circular I use a meta box to upload PDF or image file now I can retrive the url of the file but how can I get the file name and size from my custom post_type meta field .
Here is my Meta Box code
function add_custom_meta_boxes() {
// Define the custom attachment for posts
add_meta_box(
'wp_custom_attachment',
'Custom Attachment',
'wp_custom_attachment',
'circular',
'side'
);
} // end add_custom_meta_boxes
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" />';
echo $html;
} // end wp_custom_attachment
function save_custom_meta_data($id) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['wp_custom_attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $id;
} // end if
if('circular' == $_POST['post_type']) {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} else {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} // end if
/* - end security verification - */
// Make sure the file array isn't empty
if(!empty($_FILES['wp_custom_attachment']['name'])) {
// Setup the array of supported file types. In this case, it's just PDF.
$supported_types = array('application/pdf');
// Get the file type of the upload
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
// Check if the type is supported. If not, throw an error.
if(in_array($uploaded_type, $supported_types)) {
// Use the WordPress API to upload the file
$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);
} // end if/else
} else {
wp_die("The file type that you've uploaded is not a PDF.");
} // end if/else
} // end if
} // end save_custom_meta_data
add_action('save_post', 'save_custom_meta_data');
function update_edit_form() {
echo ' enctype="multipart/form-data"';
} // end update_edit_form
add_action('post_edit_form_tag', 'update_edit_form');
do out put the link of that file
<?php $img = get_post_meta(get_the_ID(), 'wp_custom_attachment', true); ?>
Download PDF Here
First need to get the file url the we can get the size and name . here wp_custom_attachment is the custom field id.
// retrieve file of the custom field
$file = get_post_meta(get_the_ID(), 'wp_custom_attachment', true);
//get the url
$url = $file['url'];
//Replace url to directory path
$path = str_replace( site_url('/'), ABSPATH, esc_url( $url) );
if ( is_file( $path ) ){
$filesize = size_format( filesize( $path ) );
$filename = basename($path);
}
echo '<p>Name: ' . $filename . '</p>';
echo '<p>Size: ' . $filesize . '</p>';
If you can get the attachment ID number ($attachment_id below) you should be able to do something like this to get the name/size:
$attachment_id = 'YOUR_PDF_ID';
$attahment_file = get_attached_file( $attachment_id );
function getSize($file) {
$bytes = filesize($file);
$s = array('b', 'Kb', 'Mb', 'Gb');
$e = floor(log($bytes)/log(1024));
return sprintf( '%.2f ' . $s[$e], ( $bytes/pow( 1024, floor($e) ) ) );
}
echo '<p>Name: ' . basename( $attahment_file ) . '</p>';
echo '<p>Size: ' . getSize( $attahment_file ) . '</p>';
I found the "getSize" function on another post here. It was more accurate than using the native PHP "filesize" function in terms of matching the size shown in the WP media library meta.

PHP - reading folder, all subfolders, and files in subfolders

I have a folder named "inspections" which has a number of subfolders named "location 1", "location 2", "location 3", etc. each with around 10-20 .png images in it.
What I am trying to do, is to read the directories of the "inspections" folder, and then read all the image files in each of the folders before returning them as a gallery on my index.php site. The problem is that I get no error message but the script doesnt return anything. I believe the problem is with generating the $files variable for each subfolder as I deploy the same script for reading folder content on another site.
Perhaps someone can point me in the right direction?
<?php
$dir = './inspections/';
if ($handle = opendir($dir))
{
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle)))
{
if (!in_array($folder, $blacklist))
{
if (file_exists($dir . $folder . '/desc.txt'))
{
while (false !== ($file = readdir($handle)))
{
if (!in_array($file, $blacklist))
{
$chain = file_get_contents($dir . $folder . '/chain.txt');
$website = file_get_contents($dir . $folder . '/website.txt');
$location = file_get_contents($dir . $folder . '/location.txt');
$desc = file_get_contents($dir . $folder . '/desc.txt', NULL, NULL, 0, 250) . '...';
echo "
<!-- Post -->
<div class=\"post\">
<div class=\"user-block\">
<img class=\"img-circle img-bordered-sm\" src=\"../dist/img/logo/logo_".$chain."\" alt=\"\">
<span class=\"username\">
".$folder."
</span>
<span class=\"description\"><i class=\"fa fa-map-pin\"></i> ".$location." - Posted on ". $date . "</span>
</div>
<!-- /.user-block -->
<p>".$desc."</p>
<div class=\"lightBoxGallery\">
<img src=\"".$dir . $folder . "/".$file."\" style=\"height:100px; width:100px;\">
</div>
";
}
}
}
}
}
closedir($handle);
}
?>
EDIT:
following #JazZ suggestion, I have adjusted the code and it works well now, however, assuming that one does not want to display the resized pictures itself, but rather thumbnails stored in a subfolder (eg. ./location1/thumbs/), how would I go about this?
<?php
$dir = './inspections/';
if ($handle = opendir($dir)) {
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle))) {
if (!in_array($folder, $blacklist)) {
echo "
<!-- Post -->
<div class=\"post\">
<div class=\"user-block\">
<img class=\"img-circle img-bordered-sm\" src=\"../dist/img/logo/gallery_icon_".$chain.".jpg\" alt=\"\">
<span class=\"username\">
".$hotel_name."".$status."
</span>
<span class=\"description\"><i class=\"fa fa-map-pin\"></i> ".$location." - Posted on ".date('jS F, Y - H:m', strtotime($posted_on))."</span>
</div>
<!-- /.user-block -->
<p>".$desc."</p>
<div class=\"lightBoxGallery\">
";
foreach (glob($dir . $folder . "/*.jpg") as $filename) {
echo "
<img src=\"".$filename."\" style=\"height:100px; width:100px;\">";
}
echo "</div>
</div>
<!-- /. POST -->
";
}
}
closedir($handle);
}
?>
I think your issue comes from here :
while (false !== ($file = readdir($handle))) // it reads again the same directory as it did in the first while loop
Try to replace it with
if ($sub_handle = opendir($dir . $folder)) {
while (false !== ($file = readdir($sub_handle))) {
...
}
closedir($sub_handle);
}
Also, in your case, I would use php glob() function
See a working example for your case :
$dir = './inspections/';
if ($handle = opendir($dir)) {
$blacklist = array('.', '..', 'default', 'default.php', 'desc.txt');
while (false !== ($folder = readdir($handle))) {
if (!in_array($folder, $blacklist)) {
foreach (glob($dir . $folder . "/*.png") as $filename) {
echo "$filename was found !";
echo "\r\n";
}
}
}
closedir($handle);
}
Output :
./inspections/location_4/img_1.png was found !
./inspections/location_4/img_2.png was found !
./inspections/location_4/img_3.png was found !
./inspections/location_4/img_4.png was found !
./inspections/location_4/img_5.png was found !
./inspections/location_4/img_6.png was found !
./inspections/location_3/img_1.png was found !
./inspections/location_3/img_2.png was found !
./inspections/location_3/img_3.png was found !
./inspections/location_3/img_4.png was found !
./inspections/location_3/img_5.png was found !
./inspections/location_3/img_6.png was found !
./inspections/location_2/img_1.png was found !
./inspections/location_2/img_2.png was found !
./inspections/location_2/img_3.png was found !
./inspections/location_2/img_4.png was found !
./inspections/location_2/img_5.png was found !
./inspections/location_2/img_6.png was found !
./inspections/location_1/img_1.png was found !
./inspections/location_1/img_2.png was found !
./inspections/location_1/img_3.png was found !
./inspections/location_1/img_4.png was found !
./inspections/location_1/img_5.png was found !
./inspections/location_1/img_6.png was found !
EDIT
To loop in the /inspections/location1/thumbs/ directories, this would work :
foreach (glob($dir . $folder . "/thumbs/*.png") as $filename) {
echo "$filename was found !";
echo "\r\n";
}
RE-EDIT
To glob multiple folders with the glob() function, your code should look like :
foreach (glob($dir.$folder."{/thumbs/*.png,/*.png}", GLOB_BRACE) as $filename) {
echo "$filename was found !";
echo "\r\n";
}
Perhaps the Function below helps. It is also somewhat commented. It scans a directory recursively (in this case, extracting image files from each directory/sub-directory).
<?php
$rootPath = './inspections/';
$regex = "#(\.png$)|(\.jpg$)|(\.jpeg$)|(\.tiff$)|(\.gif$)#";
/**
* #param string $directory => DIRECTORY TO SCAN
* #param string $regex => REGULAR EXPRESSION TO BE USED IN MATCHING FILE-NAMES
* #param string $get => WHAT DO YOU WANT TO GET? 'dir'= DIRECTORIES, 'file'= FILES, 'both'=BOTH FILES+DIRECTORIES
* #param bool $useFullPath => DO YOU WISH TO RETURN THE FULL PATH TO THE FOLDERS/FILES OR JUST THEIR BASE-NAMES?
* #param array $dirs => LEAVE AS IS: USED DURING RECURSIVE TRIPS
* #return array
*/
function scanDirRecursive($directory, $regex=null, $get="file", $useFullPath=false, &$dirs=[], &$files=[]) {
$iterator = new DirectoryIterator ($directory);
foreach($iterator as $info) {
$fileDirName = $info->getFilename();
if ($info->isFile () && !preg_match("#^\..*?#", $fileDirName)) {
if($get == 'file' || $get == 'both'){
if($regex) {
if(preg_match($regex, $fileDirName)) {
if ($useFullPath) {
$files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName;
}
else {
$files[] = $fileDirName;
}
}
}else{
if($useFullPath){
$files[] = $directory . DIRECTORY_SEPARATOR . $fileDirName;
}else{
$files[] = $fileDirName;
}
}
}
}else if ($info->isDir() && !$info->isDot()) {
$fullPathName = $directory . DIRECTORY_SEPARATOR . $fileDirName;
if($get == 'dir' || $get == 'both') {
$dirs[] = ($useFullPath) ? $fullPathName : $fileDirName;
}
scanDirRecursive($fullPathName, $regex, $get, $useFullPath, $dirs, $files);
}
}
if($get == 'dir') {
return $dirs;
}else if($get == 'file'){
return $files;
}
return ['dirs' => $dirs, 'files' => $files];
}
$images = scanDirRecursive($rootPath, $regex, 'file', true);
var_dump($images);

PHP - How to use functions from another directory file?

I have this function in $root/content/plugins/musicplayer/includes/player.php
public function head_script( $id, $playlist_id, $songs, $in_popup, $autoplay = false ) {
$output = '';
$playlist = '';
$artist = '';
$free = null;
$external = 0;
if ( $songs ) {
$ogg = '';
foreach ( $songs as $song ) {
$free = $song->free;
if ( $song->poster ) {
$poster = esc_url( $song->poster );
} else {
$poster = $this->get_default_playlist_poster( $playlist_id );
}
$playlist .= '{ title : "' . $song->name . '", mp3:"'. esc_url( $song->mp3 ) .'"';
if ( $song->artist )
$playlist .= ', artist : "' . $song->artist . '" ';
if ( $free != 'on' ) {
$playlist .= ',poster : "' . $poster . '" ';
$playlist .= ' },';
}
$playlist = substr( $playlist, 0, -1 );
$output .= '<script type="text/javascript">//<![CDATA[';
$output .= "\n";
$output .= 'jQuery(document).ready(function($) {
new jPlayerPlaylist( {
jPlayer: "#jquery_jplayer_' . $id . '",
cssSelectorAncestor: "#jp_container_' . $id . '" },
['.$playlist.'], {
swfPath: "' . WOLF_JPLAYER_PLUGIN_URL . '/assets/js/src",
wmode: "window", ';
$output .= '});'; // end playlist
if ( ! $in_popup )
$output .= $this->popup();
$output .= '});'; // end document ready playlist
$output .= '//]]></script>';
}
echo $output;
}
How can I use it in $root/content/themes/bigwolf/index.php, with it still being able to call all the functions that are originally and normally called in the native directory, without any problem?
You can include it. That's how you do it.
f1.php
<?php
function func1()
{
echo 'hi';
}
f2.php
<?php
require_once('f1.php'); // require
//include 'f1.php'; // or include
func1();
Obviously musicplayer is a plugin. If it's properly formatted, WordPress will automatically include it. So in the main file of your plugin put
require_once __DIR__ . "/includes/player.php';
That will bring your player.php in and give you access to the functions in it.
HTH,
=C=

How to display the Facebook profile photo in my php project

In my project I am signing in with a Facebook account, but the profile page displays the image from gravatar.com. I want to display the profile image from www.facebook.com of registered users.
In my local system I have the following code to display profile photo from www.gravatar.com
public function gravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = FALSE, $atts = array())
{
$url = 'https://secure.gravatar.com/avatar/'
. md5(strtolower(trim( $email)))
. "?s=$s&d=$d&r=$r";
if ($img)
{
$url = '<img src="' . $url . '"';
foreach ($atts as $key => $val)
{
$url .= ' ' . $key . '="' . $val . '"';
}
$url .= ' />';
}
return $url;
}
How can I display the Facebook profile photo instead of gravatar.com profile photo?
You can link to https://graph.facebook.com/usernameOrId/picture.
Something like this:
function facebookAvatar($uid, $img = FALSE, $atts = array())
{
$url = 'https://graph.facebook.com/'.trim($uid).'/picture';
if ($img)
{
$url = '<img src="' . $url . '"';
foreach ($atts as $key => $val)
{
$url .= ' ' . $key . '="' . $val . '"';
}
$url .= ' />';
}
return $url;
}
and to get the Image use:
<?php echo facebookAvatar('UsernameOrUserID', TRUE, array('width'=>'80px', 'height'=>'80px')); ?>
UsernameOrUserID you've to change to the UserID:
1234321
if the url is:
http://facebook.com/profile.php?id=1234321
or to the username:
my.name
if the facebook url is http://facebook.com/my.name
If you are using PHP SDK you can get the userId of the current logged in USer and display the user Image.
You can do like this:
require_once 'path/to/facebookSDK.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
//this will ouptput your current logged in user facebook image
echo getFacebookPhotoAvatar ($user);
function getFacebookPhotoAvatar ($user) {
if($user) {
$photoUrl = "https://graph.facebook.com/".$user."/picture";
$facebookPhoto = '<img src="'.$photoUrl.'" alt="FacebookUserImage"/>';
} else {
$facebookPhoto = '';
}
return $facebookPhoto ;
}
Hope this helps :)

Categories