see also: code.orgnsm.org for testable examples
-
Stylesheet Switcher
Style Links HTML
<link rel="alternate stylesheet" type="text/css" href="/theme/KATALOG/style.css" title="KATALOG"/>
<link rel="alternate stylesheet" type="text/css" href="/theme/SCREEN/style.css" title="SCREEN"/>
<link rel="alternate stylesheet" type="text/css" href="/theme/spaeci...
JavaScript
Code 2012
-
Page Layout Method
HTML <div id="hub"> <div id="content1" class="column"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio...
Code
Information Structuring
Stylesheet Coding 2012
-
Read and Process RSS
<?php
function getRSS( $url ){
$cobj = curl_init( $url );
curl_setopt( $cobj, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $cobj, CURLOPT_CONNECTTIMEOUT, 0 );//0 = no timeout
$tumblr_raw = curl_exec( $cobj );
curl_close( $cobj );
if( $tumblr_raw ){
$tumblr_xml = new DOMDocument();
$tumblr_xml->lo...
Code
Template Coding 2013
-
Dynamic Form Submission
The JavaScript
jQuery(function($){
$("#contact").submit(function(){
//grab form values before blowing it out of the DOM in the next line
values=$(this).serialize();
$("#contact").html( "<p>Sending message...</p>\n" );
//send the values to the PHP handler
$.aja...
Code
JavaScript
PHP
JQuery 2013
-
Device-Responsive Layout
HTML
<meta name="viewport" content="width=device-width, initial-scale=1.0;"/>
CSS
@media (max-width: 480px){
}
@media (max-width: 767px){
#container{
padding: 0 25px;
}
nav ul li a{
font-size: 100%;
padding: 15px 0;
border-radius: 30px;
}
nav ul li ...
Stylesheet Coding
Code 2013
-
Pagination Logic
<?php
$items = array(
0 => array( "item 1", "2013-09-13", "1" ),
1 => array( "item 2", "2013-09-14", "2" ),
2 => array( "item 3", "2013-09-15", "3" ),
);
######## CALCULATIONS #########
# set per-page var
if (isset($_GET["perpage"])) $perpage = $_GET["perpage"];
else $perpage = 10;
# calc ...
Code
Template Coding
PHP 2013
-
DOM Inject and Add Event
w/JavaScript
window.onload = function(){
//create new button
var btn = document.createElement("a");
btn.setAttribute("id", "addedbutton");
var btntxt = document.createTextNode("Run Me");
btn.appendChild(btntxt);
//inject new button
document.getElementById("sidebar").appendChild(btn);
//add event to ...
Code
JavaScript
JQuery 2013
-
AJAX Remote Read, Local Write
w/JavaScript
//the callback function run after loading JSONp below
function test_results_loaded(data){
//post data to a service via ajax
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://orgnsm@orgnsm.org:lkAGWUE01H@orgnsm.testrail.com//index.php?/api/v2/add_result/1", true);
xhr.setRequestHeader('Cont...
Code
JavaScript
JQuery 2013
-
Webcam Image Refresher
HTML
<img src="http://orgnsm.org/camoff.jpg" alt="Webcam" id="webcamImage"/></div>
JavaScript
function refreshCam(id, file) {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById(id).src = file + "?time="+h+m+s;
setTime...
JavaScript
Code 2013
-
Slideshow
HTML
<div id="photos_rotator">
<ul>
<li>
<a href="/node/15">
<span class="title">003</span>
</a>
<div class="rotator_full"><img src="003_0.jpg" alt=""/></div>
</li>
<li>
<a href="/node/14">
<span class="t...
JavaScript
Stylesheet Coding
Code
JQuery 2013
-
Image Desaturation Effect
.box img{
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'>
<filter id=\'grayscale\'>
<feColorMatrix type=\'saturate\' values=\'0.5\'/>
</filter>
</svg>#grayscale");
filter: gray alpha(opacity=50);
-webkit-filter: grayscale(50%);
-webkit-transfo...
Stylesheet Coding
Code 2013
-
Make Drupal Module Most Important
So other modules don't supersede your module, run this code once.
<?php
db_query("UPDATE {system} SET weight = 100 WHERE name = 'MODULE_NAME'");
?>...
Code
Template Coding
Drupal 2013
-
Login redirect
<?php
function HOOK_user_login_submit( $form, &$form_state ){
$form_state["redirect"] = "";
}
function HOOK_form_user_login_alter( &$form, $form_state ){
$form["#submit"][] = "HOOK_user_login_submit";
}
?>...
Code
Template Coding
Drupal 2013
-
Insert email as username at registration
<?php
function HOOK_user_insert( &$edit, &$account, $category = NULL ){
// Don't create a new username if one is already set
if( strpos($account->name, 'temporary_') !== 0)
return;
// Otherwise, replace username with email address field
db_update("users")
->fields(array(...
Code
Template Coding
Drupal 2013
-
Show field when a different selection is made on the same form
function HOOK_form_alter( &$form, &$form_state, $form_id ){
if( $form_id == "user_register_form" || $form_id == "user_profile_form" ) {
// Shows OTHER text field when 'Other' is selected as their specialty
$form["field_specialty_other"]["#states"] = array(
"visible" => arr...
Code
JavaScript
Template Coding
Drupal 2013
-
Obtain matching entities
function obtain_entities_by_type($entity_type,$bundle,$limit=10,$offset=0,$subject_nid=FALSE){
$query=new EntityFieldQuery();
$query->entityCondition('entity_type', $entity_type)
->entityCondition('bundle', $bundle)
->propertyCondition('status', 1)
->range($offset, $limit...
Code
Template Coding
Drupal 2013
-
Add unique IDs to menu items
<?php
function HOOK_menu_link( array $variables ){
$element = $variables['element'];
$sub_menu = '';
$name_id = strtolower(strip_tags($element['#title']));
// remove colons and anything past colons
if (strpos($name_id, ':')) $name_id = substr ($name_id, 0, strpos($name_id, ':'));
//Pr...
Code
Template Coding
Drupal 2013
-
Render imagecache images
echo( "<img src=\"".image_style_url("thumbnail", $photo["uri"] )."\" alt=\"\"/>" );...
Code
Template Coding
Drupal 2013
-
Fill array with server request URI strings
<?php
$request = explode( "/", $_SERVER["REQUEST_URI"] );
array_shift( $request );
print_r( $requests );
?>...
Code
Template Coding
PHP 2013
-
Create custom content type
contenttypetest.info
name = Contenttype test
description = Test - how can I create a new content type with hook form?
core = 7.x
files[] = contenttypetest.module;
files[] = contenttypetest.install;
contenttypetest.module
<?php
// hook_form implementation
function contenttypetest_form($node, &$f...
Code
Template Coding
Drupal 2013
-
LDAP Connect and Bind Test
<?php
$host = "127.0.0.1:10389";
$ldap = ldap_connect($host);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
$username = "uid=admin,ou=system";
$password = "secret";
if( $bind = ldap_bind($ldap, $username, $password) )
echo( "logged into ".$host." as ".$username );
else
echo( "Fa...
Code
Template Coding
PHP 2013
-
Output a menu
<?php
$page_menu_items = menu_tree_output(menu_tree_all_data("main-menu"));
echo( drupal_render($page_menu_items) );
?>...
Code
Template Coding
Drupal 2013
-
Various WP snippets
Show Links Menu w/Active Class
<nav>
<?php $args=array(
'sort_order' => 'ASC',
'sort_column' => 'post_date',
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'meta_key' => '',
'meta_value' => '',
'authors' => '',
'child_of' => 0,
'parent' => -1,
'exclude_t...
Code
Template Coding
Wordpress 2013
-
Create symlinks
<?php
symlink('/homepages/21/d93015512/htdocs/library/organic_connectivity',
'/homepages/21/d93015512/htdocs/drupal/sites/all/modules/organic_connectivity/lib');
?>...
Code
Information Structuring
PHP 2014
-
Nested-query approach to mining field_collection data and relationship
<?php
function get_species_country($id_country) {
$inner = new EntityFieldQuery();
$inner_r = $inner->entityCondition('entity_type', 'field_collection_item')
->fieldCondition('field_species_country', 'target_id', $id_country, '=')
->execute();
if(!emp...
Code
Template Coding
Drupal 2014
-
Manually reset Drupal admin password
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
if (isset($_GET['pass']) && !empty($_GET['pass'])) {
$newhash = user_hash_password($_GET['pass']);
}
else {
die('...
Code
Drupal
PHP 2014
-
MySQL Basics
add export PATH=$PATH:/usr/local/mysql/bin to ~/.bash_profile or /etc/profile
Backup database to text file
mysqldump database_name > database_name.sql
Remove database
mysql> drop database database_name;
Create database
mysql> CREATE DATABASE database_name;...
Code 2014
-
OSX Virtual Web Host Config
add line to /etc/hosts
127.0.0.1 amniot.localhost
add lines to /etc/apache2/httpd.conf
NameVirtualHost 127.0.0.1:80
<VirtualHost amniot.localhost:80>
<Directory "/Library/Webserver/Documents_AMNIOT">
Options FollowSymLinks Indexes
AllowOverride All
Order deny,allow
allow from All
...
Code 2014
-
Rename stuck field names
<?php
$fields = array(
'field_inspirational_imagery' => 'field_images',
);
// Loop through each of the fields/tables with the old name and change them
foreach($fields as $field_name => $new_field_name) {
// First check that field_name exists
if(!db_table_exists('field_data_' . $field_name...
Code
Drupal
PHP 2014
-
Similar by Taxonomy
<ul class="item-list">
<?php
$terms_nood = taxonomy_node_get_terms_by_vocabulary($node,6);
$terms = taxonomy_get_tree(6);
foreach($terms as $term){
//$tagged = taxonomy_term_count_nodes($term->tid);
if( $term->name == arg(1) || array_key_exists( $term->tid,$terms_nood ) ){
echo("<li...
Code
Drupal
Template Coding 2014
-
Drupal DB Query to find Children (Recursively)
<?php
function loadchildrens($context){
$sql_children = "SELECT node.nid AS nid,
node.vid AS node_vid,
node.title AS node_title
FROM node node
LEFT JOIN content_field_connection node_data_field_connection ON node.vid = node_data_field_connection.vid
WHERE (node.type in ('category')) AND (node_data_field...
Code
Drupal
PHP
Template Coding 2014
-
Migrates multigroups in D6 to field collections in D7
<?php
/////////////////// PAGE DEFINITIONS ///////////////////
function migrate_groups_menu(){
$menu["migrate_groups"] = array(
"title" => "Migrate grps",
"description" => "....",
"page callback" => "migrate_multigroup_to_collections",
"access callback" => TRUE...
Code
Drupal 2014
-
Reading/setting Drupal config variables
<?php
function organic_context_config_page(){
$form = array();
$form['onthisdate_maxdisp'] = array(
'#type' => 'textfield',
'#title' => t('Maximum number of links'),
'#default_value' => variable_get('onthisdate_maxdisp', 3),
'#size' => 2,
'#maxlength' =&...
Code
Drupal 2014
-
Using jQuery flexslider with animated captions callback
jQuery(window).load(function(){
jQuery('.flexslider').flexslider( {
pauseOnHover: true,
controlsContainer: ".flex-container",
slideshowSpeed: 8000,
before: function(slider){
var currentSlide = slider.slides.eq(slider.currentSlide);
jQuery(currentSlide...
Code
JQuery 2014
-
Font-embed Rundown
TTF - Works in most browsers except IE and iPhone
EOT - IE only
WOFF - Compressed, emerging standard
SVG - iPhone/iPad...
Code
Stylesheet Coding 2014
-
Post referencing setup
Assign multiple disciplines to a project
<?php
// Adds custom post type for Projects and Services
function create_post_type(){
register_post_type('project',
array(
'labels' => array(
'name' => __('Projects'),
'singular_name' => __('Project')
),
'taxonomies' => array('category'),
'public...
Code
Wordpress 2016
-
Custom Post Types
Adds custom post type called "Reviews"
<?php
function create_post_type(){
register_post_type('review',
array(
'labels'=>array(
'name'=>__('Reviews'),
'singular_name'=>__('Review')
),
'public'=>true,
'has_archive'=>true,
'capabilities'=>array...
Wordpress
Code 2016
-
Find which file a function is defined in
<?php
$reflFunc=new ReflectionFunction('name_of_function');
echo($reflFunc->getFileName().':'.$reflFunc->getStartLine());
?>...
Code
PHP 2016