Handy WordPress Functions

A collection of WordPress functions I use often.

Link to Home:

<?php home_url( $path_relative_to_root, $opt_scheme_http_https ); ?>

<?php echo esc_url( home_url( '/' ) ); ?>

Include another php file:

get_template_part($slug, $name);

*File name separated on ‘-‘ between two inputs to function. So if named include-content-blocks.php call is:

get_template_part('include', 'content-blocks');

Custom field images (not featured):

<?php echo wp_get_attachment_image($id, $size, false, array('class' => 'hero')); ?>

Get image values in array instead of outputting image:

$img = wp_get_attachment_image_src($id, $size, false, array('class' => 'hero')); 
$img[0]; // path to image
$img[1]; //image width
$img[2]; //image height

Retrieving featured images is a different function:

    the_post_thumbnail($size, array('class' => 'x');
} ?>

Get Image Caption

<?php $image_data = wp_prepare_attachment_for_js( $img_id );
if($image_data["caption"]): ?>
     <div class="post-featured-image--caption">
        <?php echo $image_data["caption"]; ?>
<?php endif; ?>

Conditionals to check post type Inside Loop:

<?php if( get_post_type() == 'post' ){ ...} ?>

Conditionals to check on single page (like in functions.php or header.php to change common things in templates):

<?php if( is_singular('post') ) {...} ?>

Keep selected taxonomies and categories in hierarchical order and not on top in admin:

<?php add_filter( 'wp_terms_checklist_args', 'ubx_terms_checklist_args', 1, 2 ); function  
ubx_terms_checklist_args ( $args, $post_id ) {    $args[ 'checked_ontop' ] = false;    return $args; } ?>

Reset $post variable:

Use after calling setup_postdata($post), $query->the_post() or ACF repeaters/flexible content the_row()

<?php wp_reset_postdata(); ?>

Retrieve public query variable in the WP_Query class of the global $wp_query object:

<?php get_query_var( $var, $default_if_no_value ) ?>

Get all pages that use a certain template:

<?php get_pages( array(
    'meta_key' => '_wp_page_template', //always value to retrieve by template
    'meta_value' => 'template-name.php',
    'post_type' => 'page',
    'heirarchical' => 0 // if 0, gets all child pages too, otherwise only top level
); ?>

Call shortcode from template:

<?php echo do_shortcode('[ shortcode with settings ]'); ?> 

Obfuscate Email:

<?php antispambot( $email_address, $hex_encoding ) ?>

See antispambot for more details