Tuesday, December 17, 2013

get_page_by_slug in wordpress

I'm developing a wordpress site and I need a function that will retrieve the page information from a given slug. I'd been looking into wordpress functions but I can't find it, what I saw are just get_page_by_path and get_page_by_title which are not the perfect function I need for the functionality I need for the site.

So, here's what I did. I checked out the existing functionality which is most likely the same of what I wanted to achieve get_page_by_title then from there I was able to arrived a new function get_page_by_slug that will retrieve the page information from a slug.

Please see below, hope this helps a lot on building your wordpress site and hopefully this would be included on the next version of wordpress.

/**
 * Retrieve a page given its slug.
 * @uses $wpdb
 *
 * @param string $page_slug Page slug
 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
 * @param string $post_type Optional. Post type. Default page.
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
    global $wpdb;
    $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) );
    if ( $page )
        return get_post( $page, $output );

    return null;
}


Please take note that you use this as well on retrieving post coz technically, page and post are the same but with different post type, you just need to pass on third parameter as "post". To make it much clearer with names, please see get_post_by_slug function below.

/**
 * Retrieve a post given its slug.
 * @uses $wpdb
 *
 * @param string $slug Post slug
 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
 * @param string $type Optional. Post type. Default page.
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_post_by_slug($slug, $output = OBJECT, $type = 'post' ) {
    global $wpdb;
    $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $slug, $type ) );
    if ( $post )
        return get_post( $post, $output );

    return null;
}

Tuesday, December 10, 2013

in_array function in javascript

This is a simple post for the converted in_array function in javascript. This function will return boolean whether the value is in the array or not.

function in_array(array, id) {
    for(var i=0; i<array.length; i++) {
        if (array[i]==id) return true;
    }
    return false;
}



Hope you like this post, probably short but will help a lot.