peterbelsky/Wordpress get gallery images ( PHP)
// GET THE PATHS
// IN FUNCTIONS:
// get all of the images attached to the current post
function aldenta_get_images($size = 'thumbnail') {
global $post;
return get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
}
// IN PAGE
if ($images = aldenta_get_images()) {
foreach ($images as $image) {
echo wp_get_attachment_url($image->ID); // attachment url
}
}
GET THE IMAGES
// IN FUNCTIONS
// get all of the images attached to the current post
function aldenta_get_images($size = 'thumbnail') {
global $post;
$photos = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
$results = array();
if ($photos) {
foreach ($photos as $photo) {
// get the correct image html for the selected size
$results[] = wp_get_attachment_image($photo->ID, $size);
}
}
return $results;
}
// IN PAGE
$photos = aldenta_get_images('full');
if ($photos) {
foreach ($photos as $photo) {
echo "$photo<br />";
}
}
doubledcreative/Wordpress Gallery - Changing the CSS ( PHP)
//deactivate WordPress function
remove_shortcode('gallery', 'gallery_shortcode');
//activate own function
add_shortcode('gallery', 'wpe_gallery_shortcode');
//the own renamed function
function wpe_gallery_shortcode($attr) {
global $post, $wp_locale;
static $instance = 0;
$instance++;
// Allow plugins/themes to override the default gallery template.
$output = apply_filters('post_gallery', '', $attr);
if ( $output != '' )
return $output;
// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
unset( $attr['orderby'] );
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';
if ( !empty($include) ) {
$include = preg_replace( '/[^0-9,]+/', '', $include );
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}
if ( empty($attachments) )
return '';
if ( is_feed() ) {
$output = "\n";
foreach ( $attachments as $att_id => $attachment )
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';
$selector = "gallery-{$instance}";
$gallery_style = $gallery_div = '';
if ( apply_filters( 'use_default_gallery_style', true ) )
$gallery_style = "
<style type='text/css'>
</style>
<!-- see wpe_gallery_shortcode() in wp-includes/media.php -->";
$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
$i = 0;
foreach ( $attachments as $id => $attachment ) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '';
}
$output .= "
</div>\n";
return $output;
}
Original code from: http://wpengineer.com/1802/a-solution-for-the-wordpress-gallery/
lancemonotone/Wordpress 2.7+ Gallery Styles Fix ( PHP)
// Registers our function to filter default gallery shortcode
remove_shortcode('gallery');
add_shortcode('gallery', 'sandbox_gallery');
// Function to filter the default gallery shortcode
function sandbox_gallery($attr) {
global $post;
static $instance = 0;
$instance++;
// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
unset( $attr['orderby'] );
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';
if ( !empty($include) ) {
$include = preg_replace( '/[^0-9,]+/', '', $include );
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}
if ( empty($attachments) )
return '';
if ( is_feed() ) {
$output = "\n";
foreach ( $attachments as $att_id => $attachment )
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
// check to see if tags have been set to false. If they are the defaults or have been set to a string value use that as the tag.
if ($itemtag) $itemtag = tag_escape($itemtag);
if ($captiontag) $captiontag = tag_escape($captiontag);
if ($icontag) $icontag = tag_escape($icontag);
$columns = intval($columns);
$selector = "gallery-{$instance}";
$output = "<div id='$selector' class='gallery galleryid-{$id}'>\n";
$i = 0;
foreach ( $attachments as $id => $attachment ) {
++$i;
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
if ($itemtag) {
$output .= '<'.$itemtag.' class="gallery-item ';
if( $columns > 0 && $i % $columns == 0 ) $output .= " last";
$output .= '">';
}
if ($icontag) $output .= "\n\t<" .$icontag. ">\t";
$output .= "\n\t".$link;
if ($icontag) $output .= "\n\t</".$icontag.">";
// if the attachment has a caption set
if ( trim($attachment->post_excerpt) ) {
if ($captiontag) $output .= "\n<" .$captiontag. ">\n\t";
$output .= wptexturize($attachment->post_excerpt);
if ($captiontag) $output .= "\n</" .$captiontag. ">" . "<!-- end caption -->\n";
}
if ($itemtag) $output .= "\n</".$itemtag ."><!-- end itemtag -->\n";
if ( $columns > 0 && $i % $columns == 0 ) $output .= "\n";
}
$output .= "</div><!-- end gallery -->\n";
return $output;
}
This is a combination of two fixes from Michael at WPEngineer.com, which removes the styles from the gallery output, and a follow-up comment by Aaron Cimolini, which allows the developer to omit shortcode attributes.
The blog stripped some of the usable code from the comment, so I cleaned it up and reposted it here. I'm using it with the Sandbox theme, so I've replaced the original sandbox_gallery function with Michael and Aaron's improvement.
ginoplusio/How to make a small gallery with PHP and JQuery ( jQuery)
<?
//---------------------------------------------
//Php Function to read the images in a dir
function getJsArray($dir) {
$out = "";
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false)
if(in_array( substr(strrchr($file, '.'), 1) , array('gif','png','jpg') )) $out.= ($out?",":"")."'".$dir.$file."'";
closedir($dh);
} else { die ("no dir"); }
return $out;
}
?>
<html>
<head>
<title>Mini PHP-Jquery Gallery/Slideshow</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//---------------------------------------------
var gallery_current_pos = 0; // gallery counter position
var gallery_idname = "container"; // id of the gallery container
var gallery_timer = 5000; // 5 seconds
var gallery_ar = Array(<?=getJsArray("./minislides/")?>);
function goGallery() {
if (gallery_current_pos>gallery_ar.length - 1) gallery_current_pos =0;
$('#'+gallery_idname).fadeTo("fast", 0 , function () {
$('#'+gallery_idname).css("background-image","url(" + gallery_ar[gallery_current_pos] + ")");
$('#'+gallery_idname).fadeTo("slow", 1);
gallery_current_pos++;
});
if (gallery_ar.length>1) setTimeout( function () { goGallery(); }, gallery_timer);
}
//---------------------------------------------
</script>
<style>
#container {background-repeat:no-repeat;width:300px;height:200px;}
</style>
</head>
<body onload="goGallery();">
<div id='container'>&nbsp;</div>
</body>
</html>
This is the code to make a simple gallery really fast, with php, jquery and a dir full of pictures.
pdswan/Prototype.js Image Gallery ( JavaScript)
var SlideShow = Class.create({
initialize: function(container, images){
this.container = $(container);
if( !this.container ){
throw "SlideShow: Invalid container element";
return null;
}
this.images = [];
images.each(function(e, i){
this.images.push({
info: e,
element: null
});
}, this);
this.options = Object.extend({
template: '<div id="#{id}" class="SlideShowItem" style="display: none; position: absolute; top: 0px; left: 0px;">' +
'<img alt="#{caption}" src="#{src}" />' +
'<div class="image_caption">#{caption}</div>' +
'</div>',
swap: function(container, current, swap, scope){
if( current ){
new Effect.Parallel([
new Effect.Fade(current, {
sync: true
}),
new Effect.Appear(swap, {
sync: true
})
], {queue: {position: 'end', scope: scope}});
}else{
new Effect.Appear(swap, {queue: {position: 'end', scope: scope}});
}
},
active_class: 'active'
}, arguments[2] || {});
this.options.template = new Template(this.options.template);
/* wire up all the elements */
this.id = this.container.identify();
var gotos = $$('[class*=' + this.id + '_goto_]');
this.gotos = $H();
gotos.each(function(g){
var re = new RegExp(this.id + '_goto_([0-9]+)');
var matches = re.exec(g.className);
if( matches ){
var m = parseInt(matches[1]);
g.observe('click', this.gotoIndex.bindAsEventListener(this, m));
this.gotos.set( m, (this.gotos.get(m) || []).concat([g]) );
}
}, this);
this.prev_elements = $$('.' + this.id + '_action_previous');
this.next_elements = $$('.' + this.id + '_action_next');
this.prev_elements.invoke('observe', 'click', this.previous.bindAsEventListener(this));
this.next_elements.invoke('observe', 'click', this.next.bindAsEventListener(this));
this.loaders = $$('.' + this.id + '_loading');
this.current_index = null;
this.to_animate = null;
this.gotoIndex(0);
},
gotoIndex: function(){
var index = null;
if( arguments.length == 2){
try{
arguments[0].stop();
}catch(e){}
index = arguments[1];
}else{
index = arguments[0];
}
index = this._getIndex(index);
var add = this.to_animate!=null?this.gotos.get(this.to_animate):null;
if( this.current_index != null ){
add.concat(this.gotos.get(this.current_index)||[]);
}
this.to_animate = index;
var remove = this.gotos.get(index);
if( add ) add.invoke('removeClassName', this.options.active_class);
if( remove ) remove.invoke('addClassName', this.options.active_class);
if( !this.images[index].loaded){
if (!this.images[index].loading) {
this.doLoad(index);
}
}else{
this.doIt(index);
}
},
next: function(){
var args = this._assembleArguments(arguments, [this.to_animate + 1]);
this.gotoIndex.apply(this, args);
},
previous: function(){
var args = this._assembleArguments(arguments, [this.to_animate - 1]);
this.gotoIndex.apply(this, args);
},
_assembleArguments: function(){
return $A(arguments[0]||[]).concat(arguments[1]||[]);
},
doLoad: function(index){
this.images[index].loading = true;
this._toggleLoading(true);
this.images[index].info.id = 'image' + index;
this.container.insert(this.options.template.evaluate(this.images[index].info));
this._processElement.bind(this).defer(index);
},
doIt: function(index){
this.images[index].loading = false;
this.images[index].loaded = true;
this._toggleLoading(false);
if( index == this.to_animate && index != this.current_index ){
var current_element = this.current_index!=null?this.images[this.current_index].element:null;
var new_element = this.images[index].element;
var dir = this.current_index==null||index>this.current_index?1:-1;
this.current_index = index;
this.options.swap(this.container, current_element, new_element, dir, this.id);
}
},
_processElement: function(index){
var elm = $(this.images[index].info.id);
this.images[index].element = elm;
if( !this.images[index].element ){
throw "SlideShow: image element was not properly created";
}
var i = new Image();
i.onload = this.doIt.bind(this, index);
i.src = this.images[index].info.src;
},
_getIndex: function(index){
if( index > this.images.length - 1){
return 0;
}else if( index < 0 ){
return this.images.length - 1;
}else{
return index;
}
},
_toggleLoading: function(s){
this.loaders.invoke((s?'show':'hide'));
}
});
lcy1208/Joseph Caraud Art Dealer buying Joseph Caraud paintings. Joseph Caraud Art Gallery Pays Top Dollar for your Joseph Caraud Art. ( ActionScript 3)
Joseph Caraud Art Dealer buying Joseph Caraud paintings. Joseph Caraud Art Gallery Pays Top Dollar for your Joseph Caraud Art. <BR><BR>Royalton Arts LLC buys Joseph Caraud paintings. We pay top dollar for your original Joseph Caraud artwork. Royalton Arts LLC is the Joseph Caraud art dealer buying Joseph Caraud paintings worldwide. When you are ready to sell your Joseph Caraud art, contact us to receive IMMEDIATE PAYMENT. We take care of all shipping arrangements and make it easy for you – you won’t even have to lift a finger. You can get paid up to 50% MORE by selling your Joseph Caraud painting to us, <a href="http://www.ebuypainting.com/category-407-b0-Caraud+Joseph.html" onmouseover="this.click();">Joseph Caraud paintings</a> because our clients include top Joseph Caraud collectors worldwide. As a Joseph Caraud Art Gallery we are constantly buying and selling high quality Joseph Caraud paintings. Royalton Arts, LLC pays top dollar for Joseph Caraud, and other American and European artists of 19th and 20th Century. We buy individual paintings or entire collections or estates. Royalton Arts has representatives in: New York City, Palm Beach, FL, Beverly Hills, CA, San Francisco, CA, Las Vegas, NV, Chicago, IL, Dallas, TX. International representation in: London, Paris, Zurich. <BR>Why smart sellers trust Royalton Arts: <BR>Smart and experienced collectors know that Royalton Arts, <a href="http://www.ebuypainting.com/category-181-b0-OKeeffe+Georgia.html" onmouseover="this.click();">Georgia O'Keeffe paintings</a> LLC offers fair prices, fast payment, and discreet professional service. Easy transactions with no hassles. <BR>Whether you want to sell a single Joseph Caraud painting, or an entire estate – Royalton Arts LLC is here to help you. <BR> Fair prices and fast payment: Royalton Arts offers fair market prices. We won’t pay the highest price, but we will pay you a fair market price, and pay you immediately. <BR> Fair dealing and no hassles: We make things easy by quickly agreeing on price. No endless negotiations like most other dealers! <BR> Convenience: We will even take care of shipping, <a href="http://www.ebuypainting.com/category-182-b0-Parrish+Maxfield.html" onmouseover="this.click();">Maxfield Parrish paintings</a> if necessary. If you have a collection of several paintings, an entire estate or over-sized paintings, we can arrange to have the artwork picked up from your premises by our network of professional shippers – anywhere in the world. <BR> Discretion: We pride ourselves on discretion. Any information you provide is kept strictly confidential.
Joseph Caraud Art Dealer buying Joseph Caraud paintings. Joseph Caraud Art Gallery Pays Top Dollar for your Joseph Caraud Art.
adambundy/Wordpress Image Gallery Short Code Using Post Attachments ( PHP)
function pippin_gallery_shortcode( $atts, $content = null ) {
extract( shortcode_atts( array(
'size' => ''
), $atts ) );
$image_size = 'medium';
if($size =! '') { $image_size = $size; }
$images = get_children(array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'numberposts' => -1,
'orderly' => 'menu_order',
//'exclude' => get_post_thumbnail_id(), -- uncomment to exclude post thumbnail
'post_mime_type' => 'image',
)
);
if($images) {
$gallery = '<ul class="gallery clearfix">';
foreach( $images as $image ) {
$gallery .= '<li>';
$gallery .= '<a href="' . wp_get_attachment_url($image->ID) . '" rel="shadowbox">';
$gallery .= wp_get_attachment_image($image->ID, $image_size);
$gallery .= '</a>';
$gallery .= '</li>';
}
$gallery .= '</ul>';
return $gallery;
}
}
add_shortcode('photo_gallery', 'pippin_gallery_shortcode');
**courtesy Pippin Williamson (http://pippinsplugins.com/image-gallery-short-code-using-post-attachments/)
use shortcode [photo_gallery] to display the gallery
ebiansyah1402/WordPress Gallery page with custom post type and custom taxonomy ( PHP)
<?php
//register Gallery post type
add_action('init', 'gallery_register');
function gallery_register() {
$labels = array(
'name' => __('Gallery', 'post type general name'),
'singular_name' => __('Gallery Item', 'post type singular name'),
'add_new' => __('Add New', 'gallery item'),
'add_new_item' => __('Add New Gallery Item'),
'edit_item' => __('Edit Gallery Item'),
'new_item' => __('New Gallery Item'),
'view_item' => __('View Portfolio Item'),
'search_items' => __('Search Gallery'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
);
register_post_type( 'gallery' , $args );
}
// Register "Site type" taxonomy (As Category)
register_taxonomy("Site Type", array("gallery"),
array(
"hierarchical" => true,
"label" => "Site Type",
"singular_label" => "Site Type",
"rewrite" => true)
);
//Resgister "Color" Taxonomy (As Tags)
register_taxonomy("Color", array("gallery"),
array(
"hierarchical" => false,
"label" => "Color",
"singular_label" => "Color",
"rewrite" => true)
);
//gallery post meta field for website URL or source URL
add_action("admin_init", "admin_init");
function admin_init(){
add_meta_box("source_url", "Source URL", "source_url", "gallery", "normal", "low");
}
function source_url(){
global $post;
$custom = get_post_custom($post->ID);
$source_url = $custom["source_url"][0];
?>
<label>source URL:</label>
<input name="source_url" value="<?php echo $source_url; ?>" />
<?php
}
?>
coryschadt/Wordpress - Remove inline style from default gallery ( PHP)
//Remove default inline gallery styling
add_filter( 'gallery_style', 'my_gallery_style', 99 );
function my_gallery_style() {
return "<div class='gallery'>";
}
Add this to your functions file
tylersticka/WordPress-Powered Portfolios: Gallery ( PHP)
<?php
// http://tylersticka.com/2009/09/wcpdx09/
// Retrieve custom meta for this item
$fields = get_post_custom();
// If the gallery key exists, let's show some gallery functionality
if (isset($fields['gallery'])) {
// Split the comma-separated gallery meta value into an array
$images = split(',',$fields['gallery'][0]);
// Grab the current WordPress page and use it as the current
// gallery item (defaults to 1)
$current = ($paged == '') ? 1 : $paged;
// Grab the current image from the array
$image = $images[$current-1];
// Display the current gallery image with intelligent alt text
?>
<div id="gallery">
<img src="<?php echo $image; ?>" alt="<?php echo "Image $current of ".count($images); ?>" />
<?php
// Only show "next" and "back" controls if there's more
// than one gallery item
if (count($images) > 1) {
?>
<ul>
<?php if ($current > 1) { ?><li class="prev"><a href="<?php the_permalink() ?>page/<?php echo $current-1; ?>">Previous Image</a></li><?php } ?>
<?php if ($current < count($images)) { ?><li class="next"><a href="<?php the_permalink() ?>page/<?php echo $current+1; ?>">Next Image</a></li><?php } ?>
</ul>
<?php } ?>
</div>
<?php } ?>
For use within The Loop, in your portfolio item page template.
TheJasonParker/Magento Gallery Image Rollover ( PHP)
<?php
$_product = $this->getProduct();
$_helper = $this->helper('catalog/output');
?>
<p class="product-image">
<?php
$_img = '<img src="'.$this->helper('catalog/image')->init($_product, 'image')->resize(220).'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" id="main_image" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
</p>
<?php if (count($this->getGalleryImages()) > 0): ?>
<div class="more-views">
<h4><?php echo $this->__('Click Images') ?></h4>
<ul>
<?php foreach ($this->getGalleryImages() as $_image): ?>
<li>
<a href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'main_image', $_image->getFile())->resize(220); ?>" title="<?php echo $_product->getName();?>" onmouseover="this.prevsrc=$('main_image').src; $('main_image').src = this.href;" onmouseout="$('main_image').src=this.prevsrc;" onclick="return false;" >
<!-- The below should remain the same as before -->
<img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56, 56); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"/>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
Replace the code below in your templates 'media.phtml' file. This has mouseover and mouseout but can be removed it needed.
1man/Full Gallery JS Tutorial ( JavaScript)
//This function allows you to queue up functions to be executed.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
//create function, it expects 2 values.
function insertAfter(newElement,targetElement) {
//target is what you want it to go after. Look for this elements parent.
var parent = targetElement.parentNode;
//if the parents lastchild is the targetElement...
if(parent.lastchild == targetElement) {
//add the newElement after the target element.
parent.appendChild(newElement);
} else {
// else the target has siblings, insert the new element between the target and it's next sibling.
//syntax for insertBefore: parentElement.insertBefore(newElement, targetElement);
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
function preparePlaceholder() {
//checks to make the script degrade if methods not supported.
if(!document.createElement) return false;
if(!document.createTextNode) return false;
if(!document.getElementById) return false;
if(!document.getElementById("list")) return false;
var imageElement = document.createElement("img");
imageElement.setAttribute("src","images/placeholder.jpg");
imageElement.setAttribute("id", "placeholder");
imageElement.setAttribute("alt", "Placeholder image");
var descriptionPara = document.createElement("p");
descriptionPara.setAttribute("id", "description");
var desText = document.createTextNode("This is a description.");
descriptionPara.appendChild(desText);
//uses the insertAfter function above.
var gallery = document.getElementById("list");//grab the ul list.
insertAfter(imageElement,gallery);//insert the placeholder AFTER the list.
insertAfter(descriptionPara, imageElement);//insert the description AFTER the placeholder image.
}
function applyEvent() {
//Browser check to see if they are supported.
if(!document.getElementById || !document.getElementsByTagName) return false;
//Check to see that the elements exist.
if (!document.getElementById("list")) return false;
var list = document.getElementById("list");
if (!list.getElementsByTagName("a")) return false;
var links = list.getElementsByTagName("a");
for (i=0; i < links.length; i++) {
links[i].onclick = function() {
return swapImg(this);
}
}
function swapImg(selectedLink) {
var source = selectedLink.getAttribute("href");//or selectedLink.href
//if placeholder doesn't exist(no image on page), return true so the link clicks through.
if (!document.getElementById("placeholder")) return true;
//what if the id placeholder isn't on an image, make the link follow through.
if (document.getElementById("placeholder").nodeName != "IMG") return true;
var placeHolder = document.getElementById("placeholder");
placeHolder.setAttribute("src", source);//or placeHolder.src = source.
if (!document.getElementById("description")) return false;
var description = document.getElementById("description");
//if the link has a title, grab it, else set the variable to nothing.
//variable = condition ? if true : if false; Ternary operator.
var grabTitle = selectedLink.getAttribute("title") ? selectedLink.getAttribute("title") : " ";//or var grabTitle = selectedLink.title ? selectedLink.title : " ";
//if the description firstchild is a text node, allow it to set the variable.
if(description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = grabTitle;
}
//if it gets to here, this will stop the link clicking.
return false;
}
}
addLoadEvent(applyEvent);
addLoadEvent(preparePlaceholder);
Not really relevant to anybody else. Full unobtrusive js file for a simple gallery. From DOM Scripting by Jeremy Keith (superb book, highly recommend it for anyone looking to move into DOM scripting)
danielfilho/Flickr set gallery ( JavaScript)
//jquery galeria flickr
$(document).ready( function() {
var Cont = $('<ul>').appendTo('.fotos');
var ifo = {
Api : 'YOUR API ID', //flickr api
Set : '72157612297020622', //foto set
fLink : 'http://www.flickr.com/photos/burgersux/', //link da galeria no flickr
Cant : 2 //qtd de fotos a serem exibidas
};
$.getJSON('http://api.flickr.com/services/rest/?format=json&jsoncallback=?&api_key='+ifo.Api+'&method=flickr.photosets.getPhotos&photoset_id='+ifo.Set+'&per_page='+ifo.Cant, function(Data){
if (Data.stat == "ok"){
for (var i=0; i<Data.photoset.photo.length; i++){
var photo = Data.photoset.photo[i];
var Thum = 'http://farm'+photo['farm']+'.static.flickr.com/'+photo['server']+'/'+photo['id']+'_'+photo['secret']+'_'+'s.jpg';
Cont.append('<li><a href="'+ifo.fLink+photo['id']+'/in/set-'+ifo.Set+'" title="'+photo['title']+'"><img src="'+Thum+'" alt="'+photo['title']+'" /></a></li>');
};
}
});
});
James Lynch/Image Gallery and AdRotator ( C#)
using System;
using System.Xml;
using System.IO;
partial class WebUserControl : System.Web.UI.UserControl
{
public void Page_Load(Object sender, EventArgs e)
{
btnImage.Click += (Button_Click);
}
protected bool imageIsAd;
protected void AdRadio_CheckedChanged(object sender, EventArgs e)
{
imageIsAd = true;
}
protected void GalleryRadio_CheckedChanged(object sender, EventArgs e)
{
imageIsAd = false;
}
public void Button_Click(object sender, EventArgs e)
{
if (!imageUpload.HasFile) return;
if (!imageIsAd)
{
var filePath = "~/Assets/Images/" + imageUpload.FileName;
imageUpload.SaveAs(MapPath(filePath));
}
var adPath = "~/Assets/Ads/" + imageUpload.FileName;
imageUpload.SaveAs(MapPath(adPath));
WriteXml();
ImageLink.Text = String.Empty;
AltText.Text = String.Empty;
}
void Page_PreRender()
{
var imgFolder = MapPath("~/Assets/Images/");
var dir = new DirectoryInfo(imgFolder);
dlstImages.DataSource = dir.GetFiles();
dlstImages.DataBind();
}
protected void WriteXml()
{
if (!imageIsAd) return;
System.Drawing.Image UppedImage = System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream);
float UploadedImageWidth = UppedImage.PhysicalDimension.Width;
float UploadedImageHeight = UppedImage.PhysicalDimension.Height;
var imagePath = "~/Assets/Ads/" + imageUpload.FileName;
// *Insert* var xmlFile = Absolute Path of XML file (use Literal)
var xmlFileInfo = new FileInfo(xmlFile);
if (!xmlFileInfo.Exists)
{
var writer = new XmlTextWriter(xmlFile, null);
writer.WriteStartDocument();
writer.WriteRaw("\n");
writer.WriteStartElement("Advertisements");
writer.WriteRaw("\n");
writer.WriteStartElement("Ad");
writer.WriteRaw("\n");
writer.WriteStartElement("", "ImageUrl", "");
writer.WriteString(imagePath);
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteStartElement("", "Width", "");
writer.WriteString(UploadedImageWidth.ToString());
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteStartElement("", "Height", "");
writer.WriteString(UploadedImageHeight.ToString());
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteStartElement("", "NavigateUrl", "");
writer.WriteString(ImageLink.Text);
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteStartElement("", "AlternateText", "");
writer.WriteString(AltText.Text);
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteEndElement();
writer.WriteRaw("\n");
writer.WriteEndDocument();
writer.Close();
}
else
{
var xdoc = new XmlDocument();
xdoc.Load(xmlFile);
var adverts = xdoc.SelectSingleNode("Advertisements");
XmlElement ad = xdoc.CreateElement("Ad");
XmlElement img = xdoc.CreateElement("ImageUrl");
img.InnerText = imagePath;
XmlElement width = xdoc.CreateElement("Width");
width.InnerText = UploadedImageWidth.ToString();
XmlElement height = xdoc.CreateElement("Height");
height.InnerText = UploadedImageHeight.ToString();
XmlElement navUrl = xdoc.CreateElement("NavigateUrl");
navUrl.InnerText = ImageLink.Text;
XmlElement xaltText = xdoc.CreateElement("AlternateText");
xaltText.InnerText = AltText.Text;
adverts.AppendChild(ad);
ad.AppendChild(img);
ad.AppendChild(width);
ad.AppendChild(height);
ad.AppendChild(navUrl);
ad.AppendChild(xaltText);
xdoc.Save(xmlFile);
}
}
}
Add images via a form to an image datalist or create/append an XML file which is used by an AdRotator control.
mzym/Photo Gallery via flickr API ( PHP)
require_once("phpFlickr/phpFlickr.php");
$username = "";
$apiKey = "";
$apiSecret ="";
// Create new phpFlickr object
$f = new phpFlickr($apiKey, $apiSecret);
$f->enableCache("db","mysql://<dbname>:<dbpass>@mysql.localhost/<dbname>");
//$flickr->enableCache("fs", "/var/www/phpFlickrCache");
// Find the NSID of the username inputted via the form
$nsid = $f->people_findByUsername($username);
function returnPhotosDetailView($f,$setid) {
$photosSetInfo = $f->photosets_getInfo($setid);
$heading = "Photos: ".$photosSetInfo['title'];
$photos = $f->photosets_getPhotos($setid, NULL, NULL);
$i=0;
$html .= "<ul id='photos-list' class='clearfix'>\n";
foreach ($photos['photo'] as $photo) {
$i++;
if ($i % 6 == 0) {
$html .="<li class='right'>\n";
} else {
$html .="<li>\n";
}
$html .= "<a href='".$f->buildPhotoURL($photo, "medium")."' rel='lightbox' class='vtip round shadow' title='&copy; All rights reserved'>";
$html .= "<img alt='$photo[title]' ".
"src='".$f->buildPhotoURL($photo, "square")."' id='photo_".$photo['id']."' width='75' height='75' /></a>\n";
$html .="</li>\n";
}
$html .="</ul>";
return $html;
echo $html;
}
$action = "detailview";
$setid = "";
$pid = rawurlencode($_GET['pid']);
$img_out = returnPhotosDetailView($f,$setid);
$smarty->assign("img_out",$img_out);