Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Last active February 23, 2016 16:55
Show Gist options
  • Save beardedtim/1f9b2cbef3578e241d36 to your computer and use it in GitHub Desktop.
Save beardedtim/1f9b2cbef3578e241d36 to your computer and use it in GitHub Desktop.

PHP/WordPress CheatSheet

print_r($myarray);

  • prints off the array and its keys
  • helpful when you get the error trying to do $myarray[0] since there's some weird stuff with keys in php
  • need to figure out php keys
  • more info here

get_field('myField', $id);

  • Lets us set whatever the custom 'myField' to a variable that we can mess with later
  • $id is optional. If not used, it uses current POST/PAGE id
  • if we use the_field instead, it is basically saying echo get_field()
  • this has only been used with Custom Fields plugin
  • When grabbing field(s) from forms outside of loop/page, be sure to use the PAGE/POST id and not the ACF id. This will cause you confusion and make you very, very upset when you can't figure out why it only works on one page and not the others or why your current ID isn't working when YOU JUST KNOW that it should be.

is_front_page()

  • this checks to see if it is the front page
  • even works for static pages (unlike is_home() )

dynamic_sidebar( $index );

  • You add to "Apperance/Widgets" area in Dashboard
  • '$index' is the name of the widget that you gave on creation
  • If it is two words (such as Top Bar) you put a hyhpen in it and surround it with single quote ('Top-Bar');

get_the_id()

  • gets current post ID inside of page template
  • seems to pull from the URL
  • if not, it is getting it from the loop/somewhere other than the page template

echo <pre>, var_dump($var), </pre>;

  • prettifies var_dump

get_template_part( $slug, $name );

  • loads a template part (other than header, footer sidebar) into current file
  • $slug is the bigger name, $name is the specific one we want
  • for instance:
    • ('loop', 'index') would look in this order -
      1. themes/currentTheme/loop-index.php
      2. themes/parentTheme/loop-index.php
      3. themes/currentTheme/loop.php
      4. themes/parentTheme/loop.php
  • will not give error message if no template is found

#UPDATE

include(locate_template($templatePath);

  • get_template_part will not pass variables between stuff so we should probably use include(locate_template instead
  • Seems to do the exact same thing but does through an error if nothing is found!
  • Must include .php at the end of the file name, unlike get_template_part

foreach($arrayName as $value)

  • how we loop over an array
  • case use:
      ?>
      <img src="<?php echo $val['url'];?>">
      <?php
} ?>```

    * this prints a new <img> tag for each $val in the array. And since our $val in this case is another array, we target only the key 'url' inside of that array



This is the template for pulling data from a custom post type (listing) 
and getting the fields from Advanced Custom Fields

```<?php
get_header(); ?>
  <div id="main-content">
    <div class="container">
      <div id="content-area" class="clearfix">
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
          <h1 class="main_title"><?php the_title(); ?></h1>
            <?php

            // Listings Loop

            $args = array(
              'post_type' => 'listing',
              'post_status' => 'publish',
              'posts_per_page' => -1
            );
             foreach (get_posts($args) as $post){
              echo '<pre>', var_dump(get_fields()), '</pre>';
             }
            ?>
            <?php the_content();?>
        </article> <!-- .et_pb_post -->
      </div> <!-- #content-area -->
    </div> <!-- .container -->
  </div> <!-- #main-content -->
<?php get_footer(); ?>

ACF Splash Page

  • first, we want to name the file front-page.php so that Wordpress pulls it
  • Then, since we are using all the normal stuff that we don't need, let's delete everything that is between, and including, the masthead. Change this if you want links on your single page site.
  • We then set up ACF to have the content areas that we want. For instance:
client wants:
* video/picture in hero
* a few text blobs
* some tagline
* headlines

  • that means we need a file/image upload spot, enough textareas for each of the textarea inputs that we are using, and a few text inputs for our headlines
  • once we have that, we can fill in our content through the edit page from the dashboard
  • When all information is in, go to front-page.php and enter:

<?php

get_header();


// First we set up our variables
// so we can use them later
$logo = get_field('logo');
$video = get_field('video');
$firstText = get_field('first_text');
$secondText = get_field('second_text');
$thirdText = get_field('thirds_text');
$fourthText = get_field('fourth_text');
$tagline = get_field('tagline');

// then to make sure we have everything,
// let's just echo all of them!
// If nothing is coming up here, you
// might want to check that:
// 1) your variables are correctly called
// 2) your fields are correctly called
// 3) YOU ACTUALLY HAVE CONTENT DUMMY!
/*
echo $logo;
echo $video;
echo $firstText;
echo $secondText;
echo $thirdText;
echo $fourthText;
echo $tagline; 
*/


// Now that we know all of our stuff is showing up
// we can go ahead and make our skeleton!
?>
<div class="section hero">
</div>

<div class="section about">
</div>

<div class="section singup">
</div>




<?php wp_footer();?>

  • you can see we are pulling all of our information up top so that when we need it later, it is a simple <?php echo $var; ?> away.
  • If we want to use images for the section background, the easiest way I have found to do it as of today is to have a <style> right before your content and affect the .class that you want to add the style to. This way, we can use the images that are uploaded without having to worry about having to hardcode the images in the css file. There probably is a better way to do this but I have no found the answer yet.
  • We need to put get_header() and get_footer() or else bad stuff happens to us. If bad stuff is happening to you, make sure you have those two things before calling the calvary.

Filters/Hooks/Actions

  • this is the bread and butter of everything WP does.
  • If something is happening, it is almost always because of a hook/action
  • This is what adding an action looks like:
add_action( $hookName, $functionToAdd, $priority, $numberOfArgs  );

  • And this is what hooking onto that action looks like:
do_action( $hookName, $post_ID, $post, $update );
  • $post_ID,$post, and $update are the arguments that we are passing, so our $numberOfArgs would be 3
  • the $functionToAdd is usually defined near the add_action() method call. Not always but it does make sense to have the global call to the function near where the function is definied.
  • If you do not say how many arguments you are supposed to get, it seems to only take the first one.
  • I have not tested passing it less arguments than I told it to expect.

Using Console for Debugging

function debug_to_console($data) {
    if(is_array($data) || is_object($data))
	{
		echo("<script>console.log('PHP: ".json_encode($data)."');</script>");
	} else {
		echo("<script>console.log('PHP: ".$data."');</script>");
	}
}

  • And we call the function whenver we want it to console.log something debug_to_console($data)

add_filter( 'gform_confirmation_anchor', '__return_true' );

  • When you submit a Gravity form, it makes it go back to wherever the form was, instead of the top of the page.

get_object_taxonomies($customPostTypeSlug);

  • Purpose: When you are wanting to get a list of all of the categories that are underneath a Custom Post Type
  • So to make it into a menu, we could do something like:

$customPostTaxonomies = get_object_taxonomies('listing');

if(count($customPostTaxonomies) > 0)
{
     foreach($customPostTaxonomies as $tax)
     {
	     $args = array(
         	  'orderby' => 'name',
	          'show_count' => 0,
        	  'pad_counts' => 0,
		  'hide_empty' => 0,
	          'hierarchical' => 1,
        	  'taxonomy' => $tax,
        	  'title_li' => ''
        	);

	     wp_list_categories( $args );
     }
}

  • We need to make sure that 'hide_empty' is set to 0 if we want to show even empty categories (obviously)

HUGE UPGRADE IN LIFE AND LOGIC!

  • The above grabs ALL of the things, even if we really only wanted one, which is where the follwing comes in handy
<?php
$taxonomy = 'categories';
$args = array(
         	  'orderby' => 'name',
	          'show_count' => 0,
        	  'pad_counts' => 0,
		  'hide_empty' => 0,
	          'hierarchical' => 1,
        	  'taxonomy' => $taxonomy,
        	  'title_li' => ''
        	);
	wp_list_categories( $args );
?>

  • 'categories' is the slug that we use inside of CPT UI Add/Edit Taxonomies panel that we use because we're too lazy to figure out how to do it in code and let the computer make stuff for us and hand us magic behind the scenes that will one day sooner or later bite us in the ass
  • I'm not bitter

Looping Through Custom Post Types

  • First we need to set up our arguments like so: $args = array( 'post_type' => $postTypeSlug, 'posts_per_page' => -1 );
  • Then, we need to set up a foreach loop: foreach(get_posts($args) as $post) :

$bp->displayed_user->id

  • first you need to put global $bp
  • gets the currently displayed user's id

taxonomy-categories-personals.php

  • this is the template file name for
    • a custom post type
    • that has a taxonomy slug of categories
    • and categories has am item called personals which is what I am trying to affect

[gravityform id=1 title=false description=false ajax=true tabindex=49]

  • Shortcode for Gravity Form with ID 1.
  • Source

$object->property

  • how to access property from object
  • similar to object.prop or object[prop] in JS

FORM STUFF

  • This has been super hard to get the basics going
  • The below code:
  • outputs a form
  • calls a function on submit
  • outputs the form data

<?php
/*
	Template Name: Testing
*/
get_header();

the_content(); ?>
<form method="post" action="">
    <input type="text" name="studentname">
    <input type="text" name="studentword">
    <input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>

<?php
function display()
{
    echo "hello ".$_POST["studentname"];
    echo "you told me" .$_POST["studentword"];
}
if(isset($_POST['submit']))
{
// if the POST method has a value with the key 'submit',
// go ahead and run this block, which is just calling
// the display function from above!
   display();
} 

get_footer();
?>

Plugin Creates DB Table on Activation

<?php
// Stuff needed in every plugin
/*
Plugin Name: Write To Database
Plugin URI:  http:/knoxweb.com
Description: Test of writing a plugin that interfaces with the database
Version:     0.0.1
Author:      Tim Roberts
Author URI:  http://cisca.com
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Domain Path: /languages

*/

// Stop people from accessing this file directly
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

// For creating diff versions
global $word_db_version;
$word_db_version = '1.0';


function word_db_install() {
	global $wpdb;
	global $word_db_version;

	$table_name = $wpdb->prefix . 'wordListTestingImport';
	
	$charset_collate = $wpdb->get_charset_collate();

	$sql = "CREATE TABLE $table_name (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		/*
		 * Our awesome schema for our data
		*/
		UNIQUE KEY id (id)
	) $charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	// this method creates the table
	dbDelta( $sql );

	add_option( 'word_db_version', $word_db_version );
}

// this adds data to the table 
// that the above function made
function word_install_data() {
	global $wpdb;
	
	// hard coding in vars for testing
	$word = 'bite';
	$partOfSpeech = 'verb';
	$difficultyLevel = 'basic 1';
	$level = '3';
	$silentEPair = 'bit';
	
	$table_name = $wpdb->prefix . 'wordListTestingImport';
	
	// wpdb->insert( $tableName,$insertArray(,));
	// $wpdb->insert( 
	// 	$table_name, 
	// 	array( 
	// 		'wordNumber' => 299, 
	// 		'word' => $word, 
	// 		'partOfSpeech' => $partOfSpeech,
	// 		'difficultyLevel' => $difficultyLevel,
	// 		'level' => $level,
	// 		'silentEPair' => $silentEPair
	// 	) 
	// );
}


// And we tell our worker that whenever this plugin is
// activated, go ahead and run these functions
register_activation_hook( __FILE__, 'word_db_install' );
register_activation_hook( __FILE__, 'word_install_data' );

Creating Taxonomy Template

  • First we need to understand how it all works out:
  • Lance gave me a good primer with
	taxonomy-{taxonomy}-{term}.php
   taxonomy-{taxonomy}.php
   tag-{slug}.php
   tag-{id}.php
   category-{slug}.php
   category-{ID}.php

  • Since we are making a template for the 'categories' taxonomy of custom post types, we are going with the taxonomy-categories.php file name. Inside of it:

     // Get the term we are looking at
     $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
     // echo '<pre>', var_dump($term),'</pre>';
     // set up our args array for the query we're about to do
     $args = array(
     //telling WP that we are querying its taxonomies
     // and passing it an array to use
     'tax_query' => array(
         // this array is another array!
         // so meta....
         array(
         // we are telling it 'hey, the taxonomy that I want to query
         // is equivalent to whatever you find when you look inside of
         // the box 'taxonomy' inside of the box 'term' that I definied above
         'taxonomy' => $term->taxonomy,
         // the terms that I want are inside of the 'term_id' box, inside of
         // the term box defined above
         'terms' => $term->term_id
          )
       )
     );
     
     // since we have the args set up, we can send it to WP to retrieve some data for us!
     $query = new WP_Query( $args );
     // returns Obj
     
     
    

Weird Scoping Issues


$socialMedia = array();

function checkValues ($fields,$socialMedia = array()) {
  echo 'checkValues called';
	foreach($fields as $field){
    echo 'inside of foreach';
  	if(get_field($field)) {
      echo 'I found a field';
      echo '<pre>', var_dump(get_field($field)),'</pre>';
    	array_push($socialMedia, get_field($field));  
    } else {
    	echo 'I did not find a field';  
    }
  }
  
  return $socialMedia;
}
$socialMedia = checkValues(array('facebook_url','twitter_url','instragram_url'));

@mizner
Copy link

mizner commented Jan 22, 2016

Enqueuing scripts (done from functions.php or from Plugins generally)

wp_enqueue_script(
    'my_javascript_file',                                 //slug
    get_template_directory_uri() . '/javascripts/app.js', //path
    array('jquery'),                                      //dependencies
    false,                                                //version
    true                                                  //footer - *note this for pseudo asyncing*
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment