July 29, 2017

Create a custom image/video gallery in wordpress with angularjs

Create a custom image/video gallery in wordpress with angularjs by putting below code in themes function.php

If you are a code lover and want to get this gallery data in json format. this is the best code.

I don’t like making new plugins for bunch of lines of codes. This code involves storing all the gallery data array to the custom field of a custom post type.

You can also add this meta_box to any other post, page  or custom post type. by adding a single line of

function wp_sss_register_sim_gallery_meta_boxes() {
add_meta_box( ‘sim_gallery_meta_box_1’, ‘Sim Gallery’, ‘simgalleries_form’, ‘post’ );/*adding metabox to post*/
add_meta_box( ‘sim_gallery_meta_box_1’, ‘Sim Gallery’, ‘simgalleries_form’, ‘page’ );/*adding metabox to page*/
}
add_action( ‘add_meta_boxes’, ‘wp_sss_register_sim_gallery_meta_boxes’ );

How to get sim gallery data. Here is the thing all the data is  in an array and stored in a meta_key  ‘_simgallery’ of the post ID.

get_the_id()  will be given the current post ID and get_post_meta() will give you the all the data.

$simgallery_data = get_post_meta( get_the_id(), ‘_simgallery’, true );
var_dump($simgallery_data);

 

Below is the complete code for your gallery.

/*************************************
SIM GALLERY
**************************************/
/*
Angularjs URL: http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js
Drag n Drop Reference url: http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/types
*/

add_action( ‘init’, ‘simgalleries_post_type’ );
function simgalleries_post_type() {
$labels = array(
‘name’ => ‘Sim galleries’,
‘singular_name’ => ‘Sim gallery’,
‘add_new’ => ‘Add New’,
‘add_new_item’ => ‘Add New gallery’,
‘edit_item’ => ‘Edit gallery’,
‘new_item’ => ‘New gallery’,
‘view_item’ => ‘View gallery’,
‘search_items’ => ‘Search Sim galleries’,
‘not_found’ => ‘No Sim galleries found’,
‘not_found_in_trash’ => ‘No Sim galleries in the trash’,
‘parent_item_colon’ => ”,
);

register_post_type( ‘simgalleries’, array(
‘labels’ => $labels,
‘public’ => true,
‘publicly_queryable’ => true,
‘show_ui’ => true,
‘exclude_from_search’ => true,
‘query_var’ => true,
‘capability_type’ => ‘post’,
‘has_archive’ => true,
‘hierarchical’ => false,
‘menu_position’ => 10,
‘supports’ => array(‘title’,’thumbnail’),
‘register_meta_box_cb’ => ‘simgalleries_meta_boxes’, // Callback function for custom metaboxes

) );
//flush_rewrite_rules();
}

function simgalleries_form() {
$post_id = get_the_ID();
$simgallery_data = get_post_meta( $post_id, ‘_simgallery’, true );
//var_dump($simgallery_data);

wp_nonce_field( ‘simgalleries’, ‘simgalleries’ );
?>
<style>
.typesDemo ul[dnd-list],
.typesDemo ul[dnd-list] > li {
position: relative;
}
.typesDemo ul[dnd-list] {
min-height: 42px;
padding-left: 0px;
}
.typesDemo ul[dnd-list] .dndDraggingSource {
display: none;
}
.typesDemo ul[dnd-list] .dndPlaceholder {
display: block;
background-color: #ddd;
padding: 10px 15px;
min-height: 42px;
}
.typesDemo ul[dnd-list] li {
background-color: #fff;
border: 1px solid #ddd;
border-top-right-radius: 4px;
border-top-left-radius: 4px;
display: block;
margin-bottom: -1px;
overflow:auto;
/* Disable text selection if item is not draggable */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.typesDemo ul[dnd-list] li dnd-nodrag {
display: block;
padding: 10px 15px;
}
.typesDemo .handle {
cursor: move;
position: absolute;
top: 14px;
}
.typesDemo .name {
margin-left: 20px;
}
.imgwrap{overflow:hidden;height:100%;width:200px;float:left; margin-right: 20px;}
.imgwrap img{width:100%;height:auto;}
.align-right{float:right;}
</style>

<script src=”<?php echo get_template_directory_uri(); ?>/angularjs/angular.min.js”></script>
/*http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js*/
<script src=”<?php echo get_template_directory_uri(); ?>/angularjs/angular-drag-and-drop-lists.js”></script>
/*http://marceljuenemann.github.io/angular-drag-and-drop-lists/angular-drag-and-drop-lists.js*/

<?php echo json_encode($simgallery_data); ?>
<script>
var app = angular.module(‘mySimGalleryApp’, [“dndLists”]);
app.controller(‘mySimGalleryCtrl’, function($scope,$sce) {

<?php if($simgallery_data){ ?>
$scope.lists = <?php echo json_encode($simgallery_data); ?>;
<?php }else{ ?>
$scope.lists = [{
‘label’:”,
‘item’:[]
}];
<?php } ?>

// Model to JSON for demo purpose
$scope.$watch(‘lists’, function(lists) {
$scope.modelAsJson = angular.toJson(lists, true);
}, true);

$scope.getYoutubeURL = function(url){
/* you tube url for iframe will show */
return $sce.trustAsResourceUrl(url);
}

$scope.remove = function(item) {
var index = $scope.lists[0].item.indexOf(item);
$scope.lists[0].item.splice(index, 1);
}

$scope.addItem = function() {
if($scope.addType == ‘youtube’){
$scope.addUrl = ‘https://www.youtube.com/embed/’+$scope.addKey;
}
var data={‘name’:$scope.addName,’type’:$scope.addType,’id’:$scope.addKey,’url’:$scope.addUrl};
console.log(data);
$scope.lists[0].item.push(data);
$scope.addName = $scope.addType = $scope.addKey = $scope.addUrl = ”;
//$scope.$apply();
}

$scope.addMedia = function(){

myplugin_media_upload = wp.media.frames.file_frame = wp.media({
title: ‘Media Library’,
button: { text: ‘Add Attachments’ },
multiple: true
});
var attachmentIds = ”;

myplugin_media_upload.on( ‘select’, function() {
var selection = myplugin_media_upload.state().get( ‘selection’ );
selection.map( function( attachment ) {
attachment.toJSON();
console.log(attachment);
var data={‘name’:attachment.attributes.name,’type’:’image’,’id’:attachment.id,’url’:attachment.attributes.url};
//console.log(data);
$scope.lists[0].item.push(data);
$scope.$apply();
});
});
myplugin_media_upload.open();
console.log(‘refreshing’);
}
});
</script>
<div id=”sim_wrap” ng-app=”mySimGalleryApp” ng-controller=”mySimGalleryCtrl” class=”typesDemo”>

<div ng-repeat=”list in lists”>
<div class=”panel panel-info”>
<div class=”panel-heading”>
<h3 class=”panel-title”>List of {{list.label}} </h3>
</div>
<ul dnd-list=”list.item”
dnd-allowed-types=”list.allowedTypes”
dnd-disable-if=”list.item.length >= list.max”>

<li ng-repeat=”item in list.item”
dnd-draggable=”item”
dnd-type=”item.type”
dnd-disable-if=”item.type == ‘unknown'”
dnd-moved=”list.item.splice($index, 1)”
class=”background-{{item.type}}”
>
<dnd-nodrag>
<div dnd-handle class=”handle”>:::</div>
<div class=”name”>
<div class=”imgwrap”>
<img ng-show=”item.type == ‘image'” src=”{{item.url}}” />
<div ng-show=”item.type != ‘image'” >
<iframe src=”{{getYoutubeURL(item.url)}}” class=”video” ></iframe>
</div>
</div>
<a class=”btn align-right” ng-click=”remove(item)”>Delete</a>
<table>
<tr><td>Title</td><td><input type=”text” ng-model=”item.name” class=”background-{{item.type}} form-control input-sm”></td></tr>
<tr><td>Type</td><td><input type=”text” ng-model=”item.type” class=”background-{{item.type}} form-control input-sm”></td></tr>
<tr><td>ID/KEY</td><td><input type=”text” ng-model=”item.id” class=”background-{{item.type}} form-control input-sm”></td></tr>
<tr><td>URL</td><td><input type=”text” ng-model=”item.url” class=”background-{{item.type}} form-control input-sm”></td></tr>
</table>

</div>
</dnd-nodrag>
</li>

<li class=”dndPlaceholder”>
Drop any <strong>{{list.allowedTypes.join(‘ or ‘)}}</strong> here
</li>

</ul>
</div>
</div>

<a class=”button button-primary button-large” ng-click=”addMedia();”>Add Media Image</a>
<a class=”button button-primary” ng-click=”toggle.clicked = !toggle.clicked”>Add Video</a>

<div ng-show=”toggle.clicked” >
<p>Title: <input type = “text” ng-model = “addName”></p>
<p>Type: <label><input type = “radio” ng-model=”addType” value=”youtube” name=”type”>You Tube </label>
<label><input type = “radio” ng-model=”addType” value=”url” name=”type”> URL</label></p>
<p ng-show=”addType==’youtube'”>Youtube Video ID: <input type = “text” ng-model=”addKey”></p>
<p ng-show=”addType==’url'”>Put Video URL: <input type = “text” ng-model=”addUrl” ></p>
<a class=”button button-primary” ng-click=”addItem();”>SAVE VIDEO</a>
</div>

<code>{{modelAsJson}}</code>
<textarea type=”text” name=”simgallery” id=”meta-image” class=”meta_image” style=”width:100%;”>{{modelAsJson}}</textarea>

</div><!– #sim_wrap –>

<p style=”clear:both”></p>

<?php
}

function simgalleries_meta_boxes() {
add_meta_box( ‘simgalleries_form’, ‘Simgallery Details’, ‘simgalleries_form’, ‘simgalleries’, ‘normal’, ‘high’ );
}
/********saving metaboxes*******/

add_action( ‘save_post’, ‘simgalleries_save_post’ );
function simgalleries_save_post( $post_id ) {
if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE )
return;

if ( ! empty( $_POST[‘simgalleries’] ) && ! wp_verify_nonce( $_POST[‘simgalleries’], ‘simgalleries’ ) )
return;

if ( ! empty( $_POST[‘post_type’] ) && ‘page’ == $_POST[‘post_type’] ) {
if ( ! current_user_can( ‘edit_page’, $post_id ) )
return;
} else {
if ( ! current_user_can( ‘edit_post’, $post_id ) )
return;
}

$data = ( empty( $_POST[‘simgallery’] ) ) ? ” : $_POST[‘simgallery’];
$data = stripslashes($data);
$data = json_decode($data, true);

if ( ! empty( $_POST[‘simgallery’] ) ) {
update_post_meta( $post_id, ‘_simgallery’, $data );
} else {
delete_post_meta( $post_id, ‘_simgallery’ );
}
}

function simgalleries_taxonomy() {
register_taxonomy(
‘simgallery_categories’, //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
‘simgalleries’, //post type name
array(
‘hierarchical’ => true,
‘label’ => ‘Simgallery category’, //Display name
‘query_var’ => true,
‘rewrite’ => array(
‘slug’ => ‘simgallery’, // This controls the base slug that will display before each term
‘with_front’ => false // Don’t display the category base before
)
)
);
}
add_action( ‘init’, ‘simgalleries_taxonomy’);

function save_simgalleries_meta_box( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ ‘simgalleries’ ] ) && wp_verify_nonce( $_POST[ ‘simgalleries’ ], ‘simgalleries’ ) ) ? ‘true’ : ‘false’;
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ ‘meta-image’ ] ) ) {
update_post_meta( $post_id, ‘meta-image’, $_POST[ ‘meta-image’ ] );
}

}

add_action( ‘save_post’, ‘save_simgalleries_meta_box’ );

 

If you want a custom shortc

function simgallery($atts,$data) {
global $post;
$atts = shortcode_atts( array(
‘id’ => ”,
‘row’ => 2,
‘item_per_row’ => 4,
‘height’ => 300
), $atts, ‘simgallery’ );

if(empty($atts[‘id’])){return ‘Please pass gallery id’;}

if($atts[‘item_per_row’] == 4 ){$itemclass = “col-md-3”;}
if($atts[‘item_per_row’] == 3 ){$itemclass = “col-md-4”;}
if($atts[‘item_per_row’] == 2 ){$itemclass = “col-md-6″;}

$simgallery_data = get_post_meta( $atts[‘id’], ‘_simgallery’, true );
//var_dump($simgallery_data);
$count = 0;
$limit = $atts[‘row’] * $atts[‘item_per_row’];
$image_gallery='<section>’;
$items_needed = array_slice($simgallery_data[0][‘item’], 0, $limit);
foreach($items_needed as $data){
$full_img=wp_get_attachment_image_src($data[‘id’],’full’);
$image_src=wp_get_attachment_image_src($data[‘id’],’medium’);
if($data[‘link’]){$link = $data[‘link’]; $popup = ”;}else{$link = $full_img[0]; }
if($data[‘newtab’]){$newtab = ‘ target=”_blank” ‘;}else{$newtab=”; $popup = “data-gal=’prettyPhoto[“.$attr[‘id’].”]’ “;}

if($data[‘type’] == ‘image’){
$image_gallery .=”<div class=’sim_gallery_item “.$itemclass.” col-sm-6′ style=’background-image:url(“.$image_src[0].”); min-height:”.$atts[‘height’].”‘><a href='”.$link.”‘ “.$popup.” title='”.get_the_title($data[‘id’]).”‘ “.$newtab.” ></a></div>”;
}else{
$image_gallery .=”<div class=’sim_gallery_item “.$itemclass.” col-sm-6’ style=’min-height:”.$atts[‘height’].”‘><iframe src='”.$data[‘url’].”‘ ></iframe></div>”;
}
$count++;
}
$image_gallery .=”</section>”;
return $image_gallery;
}
add_shortcode( ‘simgallery’, ‘simgallery’ );

 

ode for this sim gallery

 

 

 

You may also like...