Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active February 23, 2019 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save itzikbenh/d9a698be6e896d6a5b3362dc4688b388 to your computer and use it in GitHub Desktop.
Save itzikbenh/d9a698be6e896d6a5b3362dc4688b388 to your computer and use it in GitHub Desktop.
Useful WordPress classes for creating taxonomies, custom-post-types, building queries, etc. In progress
<?php
class Ath_DB
{
protected static $table = null;
function __construct()
{
global $wpdb;
$this->db = $wpdb;
$this->prefix = $this->db->prefix;
}
static function table( $name )
{
self::$table = $name;
return new self;
}
function get()
{
if( isset( $this->query ) )
{
$this->query = "SELECT * FROM ".$this->query;
return $this->db->get_results( $this->query );
}
$table_name = $this->prefix . self::$table;
return $this->db->get_results( "SELECT * FROM $table_name" );
}
function delete()
{
if( isset( $this->query ) )
{
$this->query = "DELETE FROM ".$this->query;
return $this->db->query( $this->query );
}
$table_name = $this->prefix . self::$table;
return $this->db->get_results( "DELETE FROM $table_name" );
}
function where( $key, $sign, $value )
{
$table_name = $this->prefix . self::$table;
$this->query = "$table_name WHERE $key $sign '$value'";
return $this;
}
function or_where( $key, $sign, $value )
{
$this->query .= "OR $key $sign '$value'";
return $this;
}
function insert( $data )
{
$table_name = $this->prefix . self::$table;
//If user entered a single array we will make it multi dimensional so the for loop will handle it correctly.
if ( ! isset( $data[0] ) )
{
$data = array( $data );
}
//The array keys are the columns. We grab the first one incase there is only one array.
$columns = "(". implode( ',', array_keys( $data[0] ) ) .")";
$this->query = "INSERT INTO $table_name $columns VALUES";
$query_values = array();
for ( $i = 0; $i < count( $data ); $i++ )
{
$values = array_values( $data[$i] );
$placeholders = $this->create_placeholders( $values );
//Will prevent SQL injection.
$query_values[] = $this->db->prepare( $placeholders, $values );
}
$this->query .= implode(',', $query_values);
return $this->db->query( $this->query );
}
function create_placeholders( $values )
{
$placeholders = array();
foreach ( $values as $value )
{
if ( is_float( $value ) )
{
$placeholders[] = "%f";
}
elseif ( is_numeric( $value ) )
{
$placeholders[] = "%d";
}
else
{
$placeholders[] = "%s";
}
}
return "(".implode(',', $placeholders).")";
}
}

Ath_DB class

NOTE

When you add a table name do it without the prefix. It will be prefixed for you. This is only good for custom queries on tables you created or just custom queries that you can't find a WordPress function that will do it for you.

SELECT

will get all rows.

Ath_DB::table( 'events' )->get();

will get all rows that matches this ID

Ath_DB::table( 'events' )->where( 'post_id', '=', 420 )->get();

You can specify order as well

Ath_DB::table( 'events' )->where( 'post_id', '=', 420 )->order_by( 'id', 'DESC' )->get();

You can also nest where clauses

Ath_DB::table( 'events' )->where( 'id', '=', 81 )->or_where( 'id', '=', 82 )->get();

INSERT - will create placeholders and prepare your query for you.

Ath_DB::table( 'events' )->insert( [title => "pizza tasting", location => "NYC"] );

You can insert multiple arrays in this form:

Ath_DB::table( 'events' )->insert( [
	[title => "pizza tasting", location => "NYC"],
	[title => "burger tasting", location => "Chicago"]
] );

DELETE

Will delete where ID is 25

Ath_DB::table( 'events' )->where( 'id', '=', 25 )->delete();

Will delete all events!

Ath_DB::table( 'events' )->delete();

Ath_Taxonomy class

You can create cateogry like(hierarchical) or tag like taxonomies.

function ath_register_company_taxonomies()
{
    $ath_taxonomy = new Ath_Taxonomy();
    //params - ($post_type, $taxonomy_key, $name, $singular_name, $slug). 
    $ath_taxonomy->create_hierarchical_taxonomy( "company", "company_category", "Company Categories", "Company Category", "company-category" );
    $ath_taxonomy->create_hierarchical_taxonomy( "company", "company_stage", "Company Stages", "Company Stage", "company-stage" );
    $ath_taxonomy->create_taxonomy( "company", "company_tag", "Company Tags", "Company Tag", "company-tags" );
}
add_action( 'init', 'ath_register_company_taxonomies' );

Ath_Post_Type class

function a_theme_register_event()
{
	$ath_post_type = new Ath_Post_Type();
    //params - ($post_type, $plural_name, $singular_name, $slug, $capability_type, $supports = array(), $public = true).
	$ath_post_type->ath_register_post_type( 'event', 'Events', 'Event', 'event', 'post', array( 'title', 'thumbnail' ) );
}
add_action( 'init', 'a_theme_register_event' );
<?php
//You can modify this however you wish. Just add/remove arguments based on your needs.
class Ath_Post_Type
{
function ath_register_post_type( $post_type, $plural_name, $singular_name, $slug, $capability_type, $supports = array(), $public = true )
{
$args = array(
'labels' => array(
'name' => $singular_name,
'singular_name' => $singular_name,
'add_new' => 'Add New',
'add_new_item' => 'Add New '.$singular_name,
'edit_item' => 'Edit '.$singular_name,
'new_item' => 'New '.$singular_name,
'all_items' => 'All '.$plural_name,
'view_item' => 'View '.$singular_name,
'search_items' => 'Search '.$plural_name,
'not_found' => 'No '.$plural_name.' found',
'not_found_in_trash' => 'No '.$plural_name.' found in Trash',
'menu_name' => $plural_name
),
'label' => $singular_name,
'public' => $public,
'has_archive' => true,
'rewrite' => array( 'slug' => $slug, 'with_front' => true ),
'capability_type' => $capability_type,
'supports' => $supports
);
register_post_type( $post_type, $args );
}
}
//You will now be able to register post-types like this:
function a_theme_register_event()
{
$ath_post_type = new Ath_Post_Type();
$ath_post_type->ath_register_post_type( 'event', 'Events', 'Event', 'event', 'post', array( 'title', 'thumbnail' ) );
}
add_action( 'init', 'a_theme_register_event' );
<?php
//Update admin-notice messages to all post types.
//If you won't include this then each post type will be considered as "post" and for example,
//if you publish an event then instead of having "event published" you'll have "post published".
//This is dynamic so it will work for all your post-types.
function all_post_types_updated_messages( $messages )
{
$post = get_post();
$post_type = get_post_type( $post );
$post_type_object = get_post_type_object( $post_type );
//Capitilized post type
$cap_post_type = ucwords( $post_type );
$messages[ $post_type ] = array(
0 => '', // Unused. Messages start at index 1.
1 => __( $cap_post_type.' updated.', 'your-plugin-textdomain' ),
2 => __( 'Custom field updated.', 'your-plugin-textdomain' ),
3 => __( 'Custom field deleted.', 'your-plugin-textdomain' ),
4 => __( $cap_post_type.' updated.', 'your-plugin-textdomain' ),
/* translators: %s: date and time of the revision */
5 => isset( $_GET['revision'] ) ? sprintf( __( $cap_post_type.' restored to revision from %s', 'your-plugin-textdomain' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => __( $cap_post_type.' published.', 'your-plugin-textdomain' ),
7 => __( $cap_post_type.' saved.', 'your-plugin-textdomain' ),
8 => __( $cap_post_type.' submitted.', 'your-plugin-textdomain' ),
9 => sprintf(
__( $cap_post_type.' scheduled for: <strong>%1$s</strong>.', 'your-plugin-textdomain' ),
// translators: Publish box date format, see http://php.net/date
date_i18n( __( 'M j, Y @ G:i', 'your-plugin-textdomain' ), strtotime( $post->post_date ) )
),
10 => __( $cap_post_type.' draft updated.', 'your-plugin-textdomain' )
);
if ( $post_type_object->publicly_queryable )
{
$permalink = get_permalink( $post->ID );
$view_link = sprintf( ' <a href="%s">%s</a>', esc_url( $permalink ), __( 'View '.$cap_post_type, 'your-plugin-textdomain' ) );
$messages[ $post_type ][1] .= $view_link;
$messages[ $post_type ][6] .= $view_link;
$messages[ $post_type ][9] .= $view_link;
$preview_permalink = add_query_arg( 'preview', 'true', $permalink );
$preview_link = sprintf( ' <a target="_blank" href="%s">%s</a>', esc_url( $preview_permalink ), __( 'Preview '.$cap_post_type, 'your-plugin-textdomain' ) );
$messages[ $post_type ][8] .= $preview_link;
$messages[ $post_type ][10] .= $preview_link;
}
return $messages;
}
add_filter( 'post_updated_messages', 'all_post_types_updated_messages' );
<?php
class Ath_Taxonomy
{
//Will create category like taxonomy
function create_hierarchical_taxonomy( $post_type, $taxonomy_key, $name, $singular_name, $slug )
{
register_taxonomy(
$taxonomy_key,
$post_type,
array(
'label' => __( $singular_name ),
'labels' => array(
'name' => _x( $name, 'taxonomy general name' ),
'singular_name' => _x( $singular_name, 'taxonomy singular name' ),
'search_items' => __( 'Search '.$name ),
'popular_items' => __( 'Popular '.$name ),
'all_items' => __( 'All '.$name ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit '.$singular_name ),
'update_item' => __( 'Update '.$singular_name ),
'add_new_item' => __( 'Add New '.$singular_name ),
'new_item_name' => __( 'New '.$singular_name.' Name' ),
'menu_name' => __( $name ),
),
'public' => true,
'show_in_nav_menus' => true,
'show_ui' => true,
'show_tagcloud' => true,
'hierarchical' => true,
'update_count_callback' => '',
'query_var' => true,
'rewrite' => array(
'slug' => $slug,
'with_front' => true,
'hierarchical' => false,
),
'capabilities' => array('manage_terms', 'edit_terms', 'delete_terms', 'manage_categories', 'assign_terms',),
)
);
}
//Will create tag like taxonomy
function create_taxonomy( $post_type, $taxonomy_key, $name, $singular_name, $slug )
{
register_taxonomy(
$taxonomy_key,
$post_type,
array(
'label' => __( $singular_name ),
'labels' => array(
'name' => _x( $name, 'taxonomy general name' ),
'singular_name' => _x( $singular_name, 'taxonomy singular name' ),
'search_items' => __( 'Search '.$name ),
'popular_items' => __( 'Popular '.$name ),
'all_items' => __( 'All '.$name ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit '.$singular_name ),
'update_item' => __( 'Update '.$singular_name ),
'add_new_item' => __( 'Add New '.$singular_name ),
'new_item_name' => __( 'New '.$singular_name.' Name' ),
'separate_items_with_commas' => __( 'Separate '.$name.' with commas' ),
'add_or_remove_items' => __( 'Add or remove '.$name ),
'choose_from_most_used' => __( 'Choose from the most used '.$name ),
'menu_name' => __( $name ),
),
'public' => true,
'show_in_nav_menus' => true,
'show_ui' => true,
'show_tagcloud' => true,
'hierarchical' => false,
'update_count_callback' => '',
'query_var' => true,
'rewrite' => array(
'slug' => $slug,
'with_front' => true,
'hierarchical' => false,
),
'capabilities' => array('manage_terms', 'edit_terms', 'delete_terms', 'manage_categories', 'assign_terms',),
)
);
}
}
//Now we can do something like this and just reuse it whenever we want to.
function ath_register_company_taxonomies()
{
$ath_taxonomy = new Ath_Taxonomy();
$ath_taxonomy->create_hierarchical_taxonomy( "company", "company_category", "Company Categories", "Company Category", "company-category" );
$ath_taxonomy->create_hierarchical_taxonomy( "company", "company_stage", "Company Stages", "Company Stage", "company-stage" );
$ath_taxonomy->create_taxonomy( "company", "company_tag", "Company Tags", "Company Tag", "company-tags" );
}
add_action( 'init', 'ath_register_company_taxonomies' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment