WordPress Plugin: PHP Best Practice - php

I have written a wordpress plugin which reads the value from an ACF field and outputs an image. The image is fetched through a shortcode.
I am a beginner and have some questions about this:
Is this approach heavy on performance?
Which solution would be best practice or more efficient?
Is there a possibility to optimize the code of the plugin?
For example, wouldnt it be better to set the images "globally".
If an image changes, I have to change it everywhere, and that's a lot of work.
$auswahl = get_field('dunstesse_energielabel');
if( $auswahl == 'A'){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-A-re.png">' ;
} else if ( $auswahl == 'B' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-B-re.png">' ;
} else if ( $auswahl == 'C' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-C-re.png">' ;
} else if ( $auswahl == 'D' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-D-re.png">' ;
} else if ( $auswahl == 'E' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-E-re.png">' ;
} else if ( $auswahl == 'F' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-F-re.png">' ;
} else if ( $auswahl == 'G' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-G-re.png">' ;
}
return $result;
}
add_shortcode('getEnergieDunstesse' , 'get_energie_dunstesse');
function get_energie_flachschirmhaube() {
$auswahl = get_field('flachschimhaube_energielabel');
if( $auswahl == 'A'){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-A-re.png">' ;
} else if ( $auswahl == 'B' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-B-re.png">' ;
} else if ( $auswahl == 'C' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-C-re.png">' ;
} else if ( $auswahl == 'D' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-D-re.png">' ;
} else if ( $auswahl == 'E' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-E-re.png">' ;
} else if ( $auswahl == 'F' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-F-re.png">' ;
} else if ( $auswahl == 'G' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-G-re.png">' ;
}
return $result;
}
add_shortcode('getEnergieFlachschirmhaube' , 'get_energie_flachschirmhaube');
function get_energie_induktion() {
$auswahl = get_field('induktions-kochfeld_energielabel');
if( $auswahl == 'A'){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-A-re.png">' ;
} else if ( $auswahl == 'B' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-B-re.png">' ;
} else if ( $auswahl == 'C' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-C-re.png">' ;
} else if ( $auswahl == 'D' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-D-re.png">' ;
} else if ( $auswahl == 'E' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-E-re.png">' ;
} else if ( $auswahl == 'F' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-F-re.png">' ;
} else if ( $auswahl == 'G' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-G-re.png">' ;
}
return $result;
}
add_shortcode('getEnergieInduktion' , 'get_energie_induktion');
function get_energie_glaskeramik() {
$auswahl = get_field('glaskeramik-kochfeld_energielabel');
if( $auswahl == 'A'){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-A-re.png">' ;
} else if ( $auswahl == 'B' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-B-re.png">' ;
} else if ( $auswahl == 'C' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-C-re.png">' ;
} else if ( $auswahl == 'D' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-D-re.png">' ;
} else if ( $auswahl == 'E' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-E-re.png">' ;
} else if ( $auswahl == 'F' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-F-re.png">' ;
} else if ( $auswahl == 'G' ){
$result = '<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-G-re.png">' ;
}
return $result;
}
add_shortcode('getEnergieGlaskeramik' , 'get_energie_glaskeramik');

In the terms of the code readability you can refactor each function to this form:
function get_energie_induktion() {
$auswahl = get_field('induktions-kochfeld_energielabel');
$defaultValue = <your-default-value>
$allowedValues = ['A','B','C','D','E'];
return in_array($auswahl, $allowedValues) ?
'<img class="energie" src="/wp-content/uploads/EEK_Buttons_2021-'.$auswahl.'-re.png">'
: $defaultValue;
}
And for $defaultValue you need to specify what you want to return in case no allowed option has been chosen.
Regarding the performance it doesn't really matter. You don't optimize such things over readibility, because micro-optimization is bad optimization.

Related

Failed to load resource 406 (Not Acceptable)

I saw this error today, yesterday everything was good.
Issue based on hosting or i don't know when i run the files on the localhost everythings fine and working correctly. Maybe there is problem with hosting secure ?
If anyone has any tips I would be very grateful.
Failed to load resource: the server responded with a status of 406 (Not Acceptable)
<?php
if( isset($_SESSION["DATAGLOBAL"][0]) && !empty($_SESSION["DATAGLOBAL"][0]) )
$C->LANGUAGE = $_SESSION["DATAGLOBAL"][0];
$this->load_langfile('inside/dashboard.php');
$this->load_langfile('global/global.php');
if( $this->user->is_logged )
{
$D->is_logged = 1;
$errored = 0;
$txterror = '';
$action = 0;
$wsee = -1;
$txtstatus = $txtvalueatach = $txttypeattach = $id_wall = '';
$typeattach = $posted_in = 0;
if( isset($_POST["wseep"]) && $_POST["wseep"] != -1 )
{
$wsee = $this->db1->e($_POST["wseep"]);
}
if( $wsee == -1 )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror6');
}
if( $errored == 0 )
{
if( isset($_POST["pin"]) && $_POST["pin"] != '' )
{
$posted_in = $this->db1->e($_POST["pin"]);
}
if( isset($_POST["idw"]) && $_POST["idw"] != '' )
{
$id_wall = $this->db1->e($_POST["idw"]);
}
if( isset($_POST["newstatus"]) && $_POST["newstatus"] != '' )
{
$txtstatus = $this->db1->e(htmlspecialchars($_POST["newstatus"]));
}
if( isset($_POST["typeattach"]) && $_POST["typeattach"] != 0 )
{
$typeattach = $this->db1->e($_POST["typeattach"]);
}
if( isset($_POST["atach-value"]) && $_POST["atach-value"] != '' )
{
$txtvalueatach = $this->db1->e($_POST["atach-value"]);
}
$withattach = 0;
$endtxtatach = '';
$codep = uniqueCode(11, 1, 'posts', 'code');
if( $typeattach == 1 || $typeattach == 2 || $typeattach == 3 || $typeattach == 4 || $typeattach == 5 || $typeattach == 6 || $typeattach == 7 || $typeattach == 8 || $typeattach == 9 )
{
switch( $typeattach )
{
case 1:
$images_post = $_FILES['images_post'];
$numphotos = count($images_post['name']);
if( $images_post['name'][0] )
{
if( $numphotos > $C->NUM_PHOTOS_POST )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror1') . ' ' . $C->NUM_PHOTOS_POST;
}
else
{
$photos = array();
$tmp_photos = array();
for( $i = 0; $i < $numphotos; $i++ )
{
if( $images_post['size'][$i] > $C->SIZE_PHOTO || $images_post['size'][$i] == 0 )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror2') . ': ' . $images_post['name'][$i];
break;
}
$loadedtype = $images_post['type'][$i];
if( $loadedtype == "image/jpeg" || $loadedtype == "image/gif" || $loadedtype == "image/png" || $loadedtype == "video/m4v" )
{
switch( $loadedtype )
{
case "image/jpeg":
$uploadfile .= '.jpg';
$mfilename .= '.jpg';
break;
case "image/gif":
$uploadfile .= '.gif';
$mfilename .= '.gif';
break;
case "video/m4v":
$uploadfile .= '.gif';
$mfilename .= '.gif';
break;
case "image/png":
$uploadfile .= '.png';
$mfilename .= '.png';
break;
}
}
else
{
$errored = 1;
$txterror = $this->lang('global_post_txterror3') . ': ' . $images_post['name'][$i];
break;
}
$tmp_photos[] = $images_post['tmp_name'][$i];
$photos[] = $codep . '-' . $i . $extens;
}
if( $errored == 0 )
{
foreach( $photos as $key => $fname )
{
move_uploaded_file($tmp_photos[$key], '../' . $C->FOLDER_PHOTOS . $fname);
$thumbnail = new SmartImage('../' . $C->FOLDER_PHOTOS . $fname, true);
$thumbnail->mycrop($C->widthPhotoThumbail, $C->widthPhotoThumbail, 'center');
$thumbnail->saveImage('../' . $C->FOLDER_PHOTOS . 'min1/' . $fname);
$thumbnail->close();
}
unset($mythumb);
$txttypeattach = 'photo';
}
$endtxtatach = implode(',', $photos);
}
}
break;
case 2:
if( !empty($txtvalueatach) )
{
if( substr($txtvalueatach, 0, 20) == "https://youtube.com/" || substr($txtvalueatach, 0, 24) == "https://www.youtube.com/" || substr($txtvalueatach, 0, 16) == "www.youtube.com/" || substr($txtvalueatach, 0, 12) == "youtube.com/" || substr($txtvalueatach, 0, 19) == "http://youtube.com/" || substr($txtvalueatach, 0, 23) == "http://www.youtube.com/" || substr($txtvalueatach, 0, 16) == "http://youtu.be/" )
{
parse_str(parse_url($txtvalueatach, PHP_URL_QUERY), $my_array_of_vars);
if( substr($txtvalueatach, 0, 16) == 'http://youtu.be/' )
{
$endtxtatach = str_replace('http://youtu.be/', 'yt:', $txtvalueatach);
}
else
{
$endtxtatach = 'yt:' . $my_array_of_vars['v'];
}
}
elseif( substr($txtvalueatach, 0, 17) == "http://vimeo.com/" || substr($txtvalueatach, 0, 21) == "http://www.vimeo.com/" || substr($txtvalueatach, 0, 18) == "https://vimeo.com/" || substr($txtvalueatach, 0, 22) == "https://www.vimeo.com/" || substr($txtvalueatach, 0, 14) == "www.vimeo.com/" || substr($txtvalueatach, 0, 10) == "vimeo.com/" )
{
$endtxtatach = 'vm:' . (int) substr(parse_url($txtvalueatach, PHP_URL_PATH), 1);
}
else
{
$errored = 1;
$txterror = $this->lang('global_post_txterror4');
}
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 2;
$txttypeattach = 'video';
}
}
break;
case 3:
if( !empty($txtvalueatach) )
{
if( substr($txtvalueatach, 0, 23) == "https://soundcloud.com/" || substr($txtvalueatach, 0, 27) == "https://www.soundcloud.com/" || substr($txtvalueatach, 0, 22) == "http://soundcloud.com/" || substr($txtvalueatach, 0, 22) == "https://m.soundcloud.com/" || substr($txtvalueatach, 0, 22) == "http://soundcloud.com/" || substr($txtvalueatach, 0, 22) == "http://www.soundcloud.com/" || substr($txtvalueatach, 0, 15) == "soundcloud.com/" || substr($txtvalueatach, 0, 19) == "www.soundcloud.com/" )
{
$endtxtatach = 'sc:' . parse_url($txtvalueatach, PHP_URL_PATH);
}
else
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 3;
$txttypeattach = 'music';
}
}
break;
case 4:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 4;
$txttypeattach = 'map';
}
}
break;
case 5:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 5;
$txttypeattach = 'visited';
}
}
break;
case 6:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 6;
$txttypeattach = 'food';
}
}
break;
case 7:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 7;
$txttypeattach = 'movie';
}
}
break;
case 8:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 8;
$txttypeattach = 'book';
}
}
break;
case 9:
if( !empty($txtvalueatach) )
{
$endtxtatach = $this->db1->e(htmlspecialchars(trim(clearnl($txtvalueatach))));
if( !empty($endtxtatach) )
{
$withattach = 1;
$typeattach = 9;
$txttypeattach = 'game';
}
}
break;
}
}
}
if( $errored == 0 )
{
if( empty($txtstatus) && empty($endtxtatach) )
{
$errored = 1;
$txterror = $this->lang('global_post_txterror5');
}
else
{
$idwall = $this->network->idwall($id_wall, $posted_in);
$r = $this->db1->query("INSERT INTO posts SET code='" . $codep . "', iduser=" . $this->user->id . ", post='" . $txtstatus . "', typepost='" . $txttypeattach . "', posted_in=" . $posted_in . ", id_wall=" . $idwall . ",valueattach='" . $endtxtatach . "', who_see=" . $wsee . ", whendate='" . time() . "'");
$idpost = $this->db1->insert_id();
$this->db1->query('INSERT INTO activities SET iduser=' . $this->user->id . ', action=3, iditem=' . $idpost . ', typeitem=1, date="' . time() . '"');
if( $idwall != $this->user->id )
{
$this->db1->query("UPDATE users SET num_posts=num_posts+1 WHERE iduser=" . $this->user->id . " LIMIT 1");
$this->db1->query("UPDATE users SET num_posts_inwall=num_posts_inwall+1 WHERE iduser=" . $idwall . " LIMIT 1");
}
else
{
$this->db1->query("UPDATE users SET num_posts=num_posts+1, num_posts_inwall=num_posts_inwall+1 WHERE iduser=" . $this->user->id . " LIMIT 1");
}
preg_match_all('~([#])([^\s#]+)~', str_replace(array( '\r', '\n' ), ' ', $txtstatus), $matchedHashtags);
if( !empty($matchedHashtags[0]) )
{
foreach( $matchedHashtags[0] as $match )
{
$hashtag = str_replace('#', '', $match);
$hashtag = $this->db1->e(($hashtag));
$this->db1->query("INSERT INTO trends SET iduser=" . $this->user->id . ", trend='" . $hashtag . "', idpost=" . $idpost . ", whendate='" . time() . "'");
}
}
}
}
if( $errored == 1 )
{
$message = '0: ' . $txterror;
}
else
{
$onepost = $this->db2->fetch('
SELECT DISTINCT idpost, posts.code as pcode, whendate, posted_in, id_wall, typepost, valueattach, numlikes, numcomments, post, who_see, username, firstname, lastname, avatar, users.iduser as uiduser, users.code as ucode, verified
FROM posts, users
WHERE
(users.iduser=posts.iduser)
AND idpost=' . $idpost . '
LIMIT 1');
$D->isaPage = $D->isOnlyOne = $D->isaGroup = $D->isWithOther = 0;
if( $onepost->posted_in == 0 )
{
if( $onepost->uiduser == $onepost->id_wall )
{
$D->isOnlyOne = 1;
$D->codeUser = $onepost->ucode;
$D->userName = $onepost->username;
$D->nameUser = (empty($onepost->firstname) || empty($onepost->lastname)) ? $onepost->username : ($onepost->firstname . ' ' . $onepost->lastname);
$D->userAvatar = $onepost->avatar;
}
if( $onepost->uiduser != $onepost->id_wall )
{
$D->isWithOther = 1;
$D->codeUser = $onepost->ucode;
$D->userName = $onepost->username;
$D->nameUser = (empty($onepost->firstname) || empty($onepost->lastname)) ? $onepost->username : ($onepost->firstname . ' ' . $onepost->lastname);
$D->userAvatar = $onepost->avatar;
$wallsec = $this->network->infoBasicWall($onepost->posted_in, $onepost->id_wall);
$D->other_code = $wallsec->code;
$D->other_userName = $wallsec->username;
$D->other_nameUser = (empty($wallsec->firstname) || empty($wallsec->lastname)) ? $wallsec->username : ($wallsec->firstname . ' ' . $wallsec->lastname);
}
}
if( $onepost->posted_in == 1 )
{
$D->isaPage = 1;
$D->idPage = $onepost->id_wall;
$thePage = $this->db2->fetch('SELECT code, url, avatar_page, title FROM pages WHERE idpage=' . $D->idPage . ' LIMIT 1');
$D->pUserName = $thePage->url;
$D->pCode = $thePage->code;
$D->pAvatar = $thePage->avatar_page;
$D->pTitle = stripslashes($thePage->title);
}
if( $onepost->posted_in == 2 )
{
$D->isaGroup = 1;
}
$D->a_date = $onepost->whendate;
$D->codeUser = $onepost->ucode;
$D->valueattach = $onepost->valueattach;
$D->typepost = $onepost->typepost;
$D->idpost = $onepost->idpost;
$D->codepost = $onepost->pcode;
$D->idUser = $onepost->uiduser;
$D->numlikes = $onepost->numlikes;
$D->numcommentstotal = $onepost->numcomments;
$D->post = stripslashes($onepost->post);
$D->whosee = $onepost->who_see;
$D->post = str_replace('<script>', '< script >', $D->post);
$D->post = str_replace('</script>', '< \/script >', $D->post);
$txtpostreturn = '';
$txtpostreturn = $this->load_template('__one-post.php', FALSE);
unset($onePost);
$txtpostreturn = str_replace('<script>', '<script>', $txtpostreturn);
$txtpostreturn = str_replace('</script>', '</script>', $txtpostreturn);
$message = '1: ' . $txtpostreturn;
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.endPostear( '<?php echo $this->db1->e($message); ?>' );
</script>
From the documentation:
The HTTP 406 Not Acceptable client error response code indicates that a response matching the list of acceptable values defined in Accept-Charset and Accept-Language cannot be served.
Looks like you are using some language files, so maybe that's your issue. What do the server logs say?

Need to set default thumbnail image if the image is not uploaded or not set

i am working in a classified site..if a user has uploaded image it displays thumbnail but i want to add a default thumbnail image if image is not uploaded..i am new to php and am not able to code it in wp template..Thank You
View File
<div class="thumb">
<?php
colabs_image('key=image&width=150&height=154');
?>
</div>
function colabs_image($args) {
/* ------------------------------------------------------------------------- */
/* SET VARIABLES $key = get_option('colabs_custom_field_image');*/
/* ------------------------------------------------------------------------- */
global $post;
global $colabs_options;
//Defaults
if (get_option('colabs_custom_field_image')!=''){
$key = '<img border="0" src="http://mmpropertydevelopers.com/wp-content/uploads/2013/12/thumbnail-default.jpg" alt="Image" width="100" height="100" />';
}else{
$key = 'image';
}
$width = null;
$height = null;
$class = '';
$quality = 90;
$id = null;
$link = 'src';
$repeat = 1;
$offset = 0;
$before = '';
$after = '';
$single = false;
$force = true;
$return = false;
$is_auto_image = false;
$src = '';
$meta = '';
$alignment = '';
$size = '';
$play = false;
$alt = '';
$img_link = '';
$attachment_id = array();
$attachment_src = array();
if ( !is_array($args) )
parse_str( $args, $args );
extract($args);
// Set Play Icon
$playicon = '';
// Set post ID
if ( empty($id) ) {
$id = $post->ID;
}
$thumb_id = get_post_meta($id,'_thumbnail_id',true);
// Set alignment
if ( '' == $alignment)
$alignment = get_post_meta($id, '_image_alignment', true);
// Get standard sizes
if ( !$width && !$height ) {
$width = '100';
$height = '100';
}
/* ------------------------------------------------------------------------- */
/* FIND IMAGE TO USE */
/* ------------------------------------------------------------------------- */
// When a custom image is sent through
if ( $src != '' ) {
$custom_field = $src;
$link = 'img';
// WP 2.9 Post Thumbnail support
} elseif ( 'true' == get_option( 'colabs_post_image_support') AND !empty($thumb_id) ) {
if ( get_option( 'colabs_pis_resize') == "true") {
// Dynamically resize the post thumbnail
$vt_crop = get_option( 'colabs_pis_hard_crop' );
if ($vt_crop == "true") $vt_crop = true; else $vt_crop = false;
$vt_image = vt_resize( $thumb_id, '', $width, $height, $vt_crop );
// Set fields for output
$custom_field = $vt_image['url'];
$width = $vt_image['width'];
$height = $vt_image['height'];
} else {
// Use predefined size string
if ( $size )
$thumb_size = $size;
else
$thumb_size = array($width,$height);
$img_link = get_the_post_thumbnail($id,$thumb_size,array( 'class' => 'colabs-image ' . $class));
}
// Grab the image from custom field
} else {
$custom_field = get_post_meta($id, $key, true);
}
// Automatic Image Thumbs - get first image from post attachment
if ( empty($custom_field) && 'true' == get_option( 'colabs_auto_img') && empty($img_link) && !(is_singular() AND in_the_loop() AND $link == "src") ) {
if( $offset >= 1 )
$repeat = $repeat + $offset;
$attachments = get_children( array( 'post_parent' => $id,
'numberposts' => $repeat,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'DESC',
'orderby' => 'menu_order date')
);
// Search for and get the post attachment
if ( !empty($attachments) ) {
$counter = -1;
$size = 'large';
foreach ( $attachments as $att_id => $attachment ) {
$counter++;
if ( $counter < $offset )
continue;
if ( 'true' == get_option('colabs_post_image_support') AND get_option( 'colabs_pis_resize') == "true") {
// Dynamically resize the post thumbnail
$vt_crop = get_option( 'colabs_pis_hard_crop' );
if ($vt_crop == "true") $vt_crop = true; else $vt_crop = false;
$vt_image = vt_resize( $att_id, '', $width, $height, $vt_crop );
// Set fields for output
$custom_field = $vt_image['url'];
$width = $vt_image['width'];
$height = $vt_image['height'];
} else {
$src = wp_get_attachment_image_src($att_id, $size, true);
$custom_field = $src[0];
$attachment_id[] = $att_id;
$src_arr[] = $custom_field;
}
$thumb_id = $att_id;
$is_auto_image = true;
}
// Get the first img tag from content
} else {
$first_img = '';
$post = get_post($id);
ob_start();
ob_end_clean();
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if ( !empty($matches[1][0]) ) {
// Save Image URL
$custom_field = $matches[1][0];
// Search for ALT tag
$output = preg_match_all( '/<img.+alt=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if ( !empty($matches[1][0]) ) {
$alt = $matches[1][0];
}
}
}
}
// Check if there is YouTube embed
if ( empty($custom_field) && empty($img_link) ) {
$embed = get_post_meta($id, "colabs_embed", true);
if ( $embed ) {
$custom_field = colabs_get_video_image($embed);
// Set Play Icon
if($play == true){ $playicon = '<span class="playicon">Play</span>'; }
}
}
// Return if there is no attachment or custom field set
if ( empty($custom_field) && empty($img_link) ) {
// Check if default placeholder image is uploaded
$placeholder = get_option( 'framework_colabs_default_image' );
if ( $placeholder && !(is_singular() AND in_the_loop()) ) {
$custom_field = $placeholder;
// Resize the placeholder if
if ( 'true' == get_option('colabs_post_image_support') AND get_option( 'colabs_pis_resize') == "true") {
// Dynamically resize the post thumbnail
$vt_crop = get_option( 'colabs_pis_hard_crop' );
if ($vt_crop == "true") $vt_crop = true; else $vt_crop = false;
$vt_image = vt_resize( '', $placeholder, $width, $height, $vt_crop );
// Set fields for output
$custom_field = $vt_image['url'];
$width = $vt_image['width'];
$height = $vt_image['height'];
}
} else {
return;
}
}
if(empty($src_arr) && empty($img_link)){ $src_arr[] = $custom_field; }
/* ------------------------------------------------------------------------- */
/* BEGIN OUTPUT */
/* ------------------------------------------------------------------------- */
$output = '';
// Set output height and width
$set_width = ' width="' . $width .'" ';
$set_height = ' height="' . $height .'" ';
if($height == null OR '' == $height) $set_height = '';
// Set standard class
if ( $class ) $class = 'colabs-image ' . $class; else $class = 'colabs-image';
// Do check to verify if images are smaller then specified.
if($force == true){ $set_width = ''; $set_height = ''; }
// WP Post Thumbnail
if(!empty($img_link) ){
if( 'img' == $link ) { // Output the image without anchors
$output .= $before;
$output .= $img_link;
$output .= $after;
} elseif( 'url' == $link ) { // Output the large image
$src = wp_get_attachment_image_src($thumb_id, 'large', true);
$custom_field = $src[0];
$output .= $custom_field;
} else { // Default - output with link
if ( ( is_single() OR is_page() ) AND $single == false ) {
$rel = 'rel="lightbox"';
$href = false;
} else {
$href = get_permalink($id);
$rel = '';
}
$title = 'title="' . get_the_title($id) .'"';
$output .= $before;
if($href == false){
$output .= $img_link;
} else {
$output .= '<a '.$title.' href="' . $href .'" '.$rel.'>' . $img_link . '</a>';
}
$output .= $after;
}
}
// Use thumb.php to resize. Skip if image has been natively resized with vt_resize.
elseif ( 'true' == get_option( 'colabs_resize') && empty($vt_image['url']) ) {
foreach($src_arr as $key => $custom_field){
// Clean the image URL
$href = $custom_field;
$custom_field = cleanSource( $custom_field );
// Check if WPMU and set correct path AND that image isn't external
if ( function_exists( 'get_current_site') && strpos($custom_field,"http://") !== 0 ) {
get_current_site();
//global $blog_id; Breaks with WP3 MS
if ( !$blog_id ) {
global $current_blog;
$blog_id = $current_blog->blog_id;
}
if ( isset($blog_id) && $blog_id > 0 ) {
$imageParts = explode( 'files/', $custom_field );
if ( isset($imageParts[1]) )
$custom_field = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
//Set the ID to the Attachment's ID if it is an attachment
if($is_auto_image == true){
$quick_id = $attachment_id[$key];
} else {
$quick_id = $id;
}
//Set custom meta
if ($meta) {
$alt = $meta;
$title = 'title="'. $meta .'"';
} else {
if ('' == $alt AND get_post_meta($thumb_id, '_wp_attachment_image_alt', true) )
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
else
$alt = get_the_title($quick_id);
$title = 'title="'. get_the_title($quick_id) .'"';
}
// Set alignment parameter
if ($alignment <> '')
$alignment = '&a='.$alignment;
$img_link = '<img src="'. get_template_directory_uri(). '/functions/timthumb.php?src='. $custom_field .'&w='. $width .'&h='. $height .'&zc=1&q='. $quality . $alignment . '" alt="'.$alt.'" class="'. stripslashes($class) .'" '. $set_width . $set_height . ' />';
if( 'img' == $link ) { // Just output the image
$output .= $before;
$output .= $img_link;
$output .= $playicon;
$output .= $after;
} elseif( 'url' == $link ) { // Output the image without anchors
if($is_auto_image == true){
$src = wp_get_attachment_image_src($thumb_id, 'large', true);
$custom_field = $src[0];
}
$output .= $custom_field;
} else { // Default - output with link
if ( ( is_single() OR is_page() ) AND $single == false ) {
$rel = 'rel="lightbox"';
} else {
$href = get_permalink($id);
$rel = '';
}
$output .= $before;
$output .= '<a '.$title.' href="' . $href .'" '.$rel.'>' . $img_link . $playicon . '</a>';
$output .= $after;
}
}
// No dynamic resizing
} else {
foreach($src_arr as $key => $custom_field){
//Set the ID to the Attachment's ID if it is an attachment
if($is_auto_image == true AND isset($attachment_id[$key])){
$quick_id = $attachment_id[$key];
} else {
$quick_id = $id;
}
//Set custom meta
if ($meta) {
$alt = $meta;
$title = 'title="'. $meta .'"';
} else {
if ('' == $alt) $alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
$title = 'title="'. get_the_title($quick_id) .'"';
}
$img_link = '<img src="'. $custom_field .'" alt="'. $alt .'" '. $set_width . $set_height . ' class="'. stripslashes($class) .'" />';
if ( 'img' == $link ) { // Just output the image
$output .= $before;
$output .= $img_link;
$output .= $after;
} elseif( 'url' == $link ) { // Output the URL to original image
if ( $vt_image['url'] || $is_auto_image ) {
$src = wp_get_attachment_image_src($thumb_id, 'full', true);
$custom_field = $src[0];
}
$output .= $custom_field;
} else { // Default - output with link
if ( ( is_single() OR is_page() ) AND $single == false ) {
// Link to the large image if single post
if ( $vt_image['url'] || $is_auto_image ) {
$src = wp_get_attachment_image_src($thumb_id, 'full', true);
$custom_field = $src[0];
}
$href = $custom_field;
$rel = 'rel="lightbox"';
} else {
$href = get_permalink($id);
$rel = '';
}
$output .= $before;
$output .= '<a href="' . $href .'" '. $rel . $title .'>' . $img_link . '</a>';
$output .= $after;
}
}
}
// Return or echo the output
if ( $return == TRUE )
return $output;
else
echo $output; // Done
}
/* Get thumbnail from Video Embed code */
You can add a javascript onError to the picture.
$key = '<img border="0" src="mypic.jpg" alt="Image" width="100" height="100"
onError="this.onerror=null;this.src='.chr(39).'alternative.jpg'.chr(39).'"/>';

Short display images by date newer to older in PHP

I'm using the following function to read a directory and show images as a gallery, it works really well, but I need to display images ordering by date from newer to older.
Knows anyone how to do it using this method?
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir("saved/2013") ) {
$lightbox = rand();
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('saved/2013') ) {
mkdir('saved/2013');
}
$strFileName = "saved/2013/".$file;
echo '<div id="imagen-t">';
echo '<p>' .date( "D d M Y g:i A", filemtime($strFileName)) . "</p>";
echo '<p><img src=saved/2013/'.$file.' alt="" width="220" /></p>';
echo '</div>';
$count++;
}
}
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
Here is the result:
http://www.espigoplatja.com/whale/galeria/
Salutations,
Gonzalo
Have you looked at USort: http://php.net/manual/en/function.usort.php
It allows you to sort an array by values with user defined comparison function.
An example
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
$arrlength=count($a);
for($x=0;$x<$arrlength;$x++)
{
echo $a[$x];
echo "<br>";
}
?>
By the way I try implementing the sample you provide and it displays the same date for all imagenes:
# SETTINGS
$per_page = 6;
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir("saved/2013") ) {
$lightbox = rand();
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('saved/2013') ) {
mkdir('saved/2013');
}
$a=array($file);
usort($a,"my_sort");
//$strFileName = "saved/2013/".$file;
$strFileName = "saved/2013/".$a[$x];
echo '<div id="imagen-t">';
//echo '<p>' .date( "D d M Y g:i A", filemtime($strFileName)) . "</p>";
echo '<p>' .date( "D d M Y g:i A", filemtime($strFileName)) . "</p>";
echo '<p><img src=saved/2013/'.$file.' alt="" width="220" /></p>';
echo '</div>';
$count++;
}
}
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}

php blog style gallery

after a long search on google i found below php code for image gallery, but it produce jquery effect after cick on thumbnail, instead of jquery i want to go to other page that shows full respective image, like a wordpress blog does!
<?php
# SETTINGS
$max_width = 200;
$max_height = 200;
$per_page = 9;
//$imagedir = 'gallery/';
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir(".") ) {
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('thumbs') ) {
mkdir('thumbs');
}
if ( ! file_exists('thumbs/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">';
echo '<img src="thumbs/'.$file.'" alt="" />';
echo '<div class="fb">view</div></a></li>';
$count++;
}
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function makeThumb( $file, $type ) {
global $max_width, $max_height;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = 220;
$newH = $max_height;
} else {
$newW = $max_width;
$newH = 200;
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, 'thumbs/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, 'thumbs/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, 'thumbs/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
?>
Remove the rel attribute from the anchor element in the while loop outputting the images. This would prevent the Lightbox script from binding events to this link, so when users click it, they will simply be redirected to the image specified in the href attribute.
In other words, instead of
echo '<li><a href="'.$file.'" rel="lightbox['.$lightbox.']">';
use
echo '<li><a href="'.$file.'">';

PHP: Sorting array with natsort

I have a PHP script that creates a thumbnail and lists an image gallery. The problem I'm having is that it lists it by timestamp on the server but I want it to list 'naturally'.
<?php
# SETTINGS
$max_width = 100;
$max_height = 100;
$per_page = 24;
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir(".") ) {
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('thumbs') ) {
mkdir('thumbs');
}
if ( ! file_exists('thumbs/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$file.'" class="zoom" rel="group">';
echo '<img src="thumbs/'.$file.'" alt="" />';
echo '</a></li>';
$count++;
}
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function makeThumb( $file, $type ) {
global $max_width, $max_height;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = $oldW * ($max_width / $oldH);
$newH = $max_height;
} else {
$newW = $max_width;
$newH = $oldH * ($max_height / $oldW);
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, 'thumbs/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, 'thumbs/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, 'thumbs/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
?>
similair to hobodave but i would use php's built in natsort function:
uksort($output, "strnatcmp");
You're not even using an array.
Instead of echo'ing your li's as you encounter them you need to put them into an array, indexed by filename.
$output[$file] = '<li>etc</li>';
Then once your loop has completed, you'll need to use a custom function to do a natural key sort, since PHP's natsort() only works on values.
function natksort($array) {
$keys = array_keys($array);
natsort($keys);
$ret = array();
foreach ($keys as $k) {
$ret[$k] = $array[$k];
}
return $ret;
}
$output = natksort($output);
echo '<ul>';
foreach ($output as $out) {
echo $out;
}
echo '</ul>';
Edit
Wow, I found this little gem to do the sorting:
uksort($array, 'strnatcasecmp');
Credit: http://www.chipstips.com/?p=269
The trick was to put everything inside an array... I took the liberty of rewriting your getPictures() function... This one implements the sorting.
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if (!is_dir('thumbs')) {
mkdir('thumbs');
}
if ($handle = opendir(".")) {
$lightbox = rand();
$files = array();
while (($file = readdir($handle)) !== false) {
if (!is_dir($file) && ($type = getPictureType($file)) != '') {
$files[] = $file;
}
}
natsort($files);
$has_previous = $skip != 0;
$has_next = (count($files) - $skip - $per_page) > 0;
$spliceLength = min($per_page, count($files) - $skip);
$files = array_slice($files, $skip, $spliceLength);
echo '<ul id="pictures">';
foreach($files as $file) {
if (!file_exists('thumbs/' . $file)) {
$type = getPictureType($file);
makeThumb($file, $type);
}
echo '<li><a href="' . $file . '" class="zoom" rel="group">';
echo '<img src="thumbs/' . $file . '" alt="" />';
echo '</a></li>';
}
echo '</ul>';
}
}

Categories