Created
March 24, 2016 22:19
-
-
Save daggerhart/335390fba7660396e6c7 to your computer and use it in GitHub Desktop.
WordPress functions that I tend to write often
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get a WP_Post object by its slug ( post_name ) | |
* | |
* @param $post_name | |
* | |
* @return WP_Post|null | |
*/ | |
function get_post_by_slug( $post_name ) { | |
$post_id = get_post_id_by_slug( $post_name ); | |
if( $post_id ) { | |
return get_post( $post_id ); | |
} | |
return null; | |
} | |
/** | |
* Get post ID by its slug (post_name) | |
* @param $post_name | |
* | |
* @return int|null | |
*/ | |
function get_post_id_by_slug( $post_name ) { | |
global $wpdb; | |
$post_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s LIMIT 1", $post_name )); | |
if ( $post_id ) { | |
return $post_id; | |
} | |
return null; | |
} | |
/** | |
* Get term object by its slug | |
* | |
* @param $term_slug | |
* | |
* @return WP_Term|null | |
*/ | |
function get_term_by_slug( $term_slug ){ | |
$taxonomy = get_term_taxonomy_by_slug( $term_slug ); | |
if ( $taxonomy ){ | |
return get_term_by( 'slug', $term_slug, $taxonomy ); | |
} | |
return null; | |
} | |
/** | |
* Get a term's taxonomy by its slug | |
* | |
* @param string $term_slug | |
* | |
* @return string|null | |
*/ | |
function get_term_taxonomy_by_slug($term_slug) { | |
global $wpdb; | |
$taxonomy = $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy.taxonomy FROM $wpdb->term_taxonomy AS term_taxonomy LEFT JOIN $wpdb->terms AS terms ON term_taxonomy.term_id = terms.term_id WHERE terms.slug = %s LIMIT 1", $term_slug) ); | |
if ( $taxonomy ){ | |
return $taxonomy; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍