A place to store some useful snippets of code for working with WordPress. Just a personal reference. All these codes have been tested by me and they work as intended, unless otherwise noted.
if ( ! function_exists( 'myfirsttheme_setup' ) ) : /** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which runs * before the init hook. The init hook is too late for some features, such as indicating * support post thumbnails. */ function myfirsttheme_setup() { /** * Make theme available for translation. * Translations can be placed in the /languages/ directory. */ load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' ); /** * Add default posts and comments RSS feed links to <head>. */ add_theme_support( 'automatic-feed-links' ); /** * Enable support for post thumbnails and featured images. */ add_theme_support( 'post-thumbnails' ); /** * Add support for two custom navigation menus. */ register_nav_menus( array( 'primary' => __( 'Primary Menu', 'myfirsttheme' ), 'secondary' => __('Secondary Menu', 'myfirsttheme' ) ) ); /** * Enable support for the following post formats: * aside, gallery, quote, image, and video */ add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) ); } endif; // myfirsttheme_setup add_action( 'after_setup_theme', 'myfirsttheme_setup' );
/** * MyFirstTheme's functions and definitions * * @package MyFirstTheme * @since MyFirstTheme 1.0 */ /** * First, let's set the maximum content width based on the theme's design and stylesheet. * This will limit the width of all uploaded images and embeds. */ if ( ! isset( $content_width ) ) $content_width = 800; /* pixels */ if ( ! function_exists( 'myfirsttheme_setup' ) ) : /** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which runs * before the init hook. The init hook is too late for some features, such as indicating * support post thumbnails. */ function myfirsttheme_setup() { /** * Make theme available for translation. * Translations can be placed in the /languages/ directory. */ load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' ); /** * Add default posts and comments RSS feed links to <head>. */ add_theme_support( 'automatic-feed-links' ); /** * Enable support for post thumbnails and featured images. */ add_theme_support( 'post-thumbnails' ); /** * Add support for two custom navigation menus. */ register_nav_menus( array( 'primary' => __( 'Primary Menu', 'myfirsttheme' ), 'secondary' => __('Secondary Menu', 'myfirsttheme' ) ) ); /** * Enable support for the following post formats: * aside, gallery, quote, image, and video */ add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) ); } endif; // myfirsttheme_setup add_action( 'after_setup_theme', 'myfirsttheme_setup' );
Loop through a query twice with rewind_loop.
// Start the main loop <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title(); endwhile; endif; // Use rewind_posts() to use the query a second time. rewind_posts(); // Start a new loop while ( have_posts() ) : the_post(); the_content(); endwhile; ?>
displaying a single post with a list of posts from the same category below the single post.
<?php // The main query. if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title(); the_content(); endwhile; else : // When no posts are found, output this text. _e( 'Sorry, no posts matched your criteria.' ); endif; wp_reset_postdata(); /* * The secondary query. Note that you can use any category name here. In our example, * we use "example-category". */ $secondary_query = new WP_Query( 'category_name=example-category' ); // The second loop. if ( $secondary_query->have_posts() ) echo '<ul>'; while ( $secondary_query->have_posts() ) : $secondary_query->the_post(); echo '<li>' . get_the_title() . '</li>'; endwhile; echo '</ul>'; endif; wp_reset_postdata(); ?>
function wpb_rand_posts() { $args = array( 'post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => 5, ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { $string .= '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); $string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>'; } $string .= '</ul>'; /* Restore original Post Data */ wp_reset_postdata(); } else { $string .= 'no posts found'; } return $string; } add_shortcode('wpb-random-posts','wpb_rand_posts'); add_filter('widget_text', 'do_shortcode');
Now you can display random posts inside a WordPress post, page, or text widget using the shortcode [wpb-random-posts].
Custom Taxonomies
//hook into the init action and call create_book_taxonomies when it fires add_action( 'init', 'create_topics_hierarchical_taxonomy', 0 ); //create a custom taxonomy name it topics for your posts function create_topics_hierarchical_taxonomy() { // Add new taxonomy, make it hierarchical like categories //first do the translations part for GUI $labels = array( 'name' => _x( 'Topics', 'taxonomy general name' ), 'singular_name' => _x( 'Topic', 'taxonomy singular name' ), 'search_items' => __( 'Search Topics' ), 'all_items' => __( 'All Topics' ), 'parent_item' => __( 'Parent Topic' ), 'parent_item_colon' => __( 'Parent Topic:' ), 'edit_item' => __( 'Edit Topic' ), 'update_item' => __( 'Update Topic' ), 'add_new_item' => __( 'Add New Topic' ), 'new_item_name' => __( 'New Topic Name' ), 'menu_name' => __( 'Topics' ), ); // Now register the taxonomy register_taxonomy('topics',array('post'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'topic' ), )); }
//hook into the init action and call create_topics_nonhierarchical_taxonomy when it fires add_action( 'init', 'create_topics_nonhierarchical_taxonomy', 0 ); function create_topics_nonhierarchical_taxonomy() { // Labels part for the GUI $labels = array( 'name' => _x( 'Topics', 'taxonomy general name' ), 'singular_name' => _x( 'Topic', 'taxonomy singular name' ), 'search_items' => __( 'Search Topics' ), 'popular_items' => __( 'Popular Topics' ), 'all_items' => __( 'All Topics' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Topic' ), 'update_item' => __( 'Update Topic' ), 'add_new_item' => __( 'Add New Topic' ), 'new_item_name' => __( 'New Topic Name' ), 'separate_items_with_commas' => __( 'Separate topics with commas' ), 'add_or_remove_items' => __( 'Add or remove topics' ), 'choose_from_most_used' => __( 'Choose from the most used topics' ), 'menu_name' => __( 'Topics' ), ); // Now register the non-hierarchical taxonomy like tag register_taxonomy('topics','post',array( 'hierarchical' => false, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'update_count_callback' => '_update_post_term_count', 'query_var' => true, 'rewrite' => array( 'slug' => 'topic' ), )); }
Display Custom Taxonomy
<?php the_terms( $post->ID, 'topics', 'Topics: ', ', ', ' ' ); ?>
≠==========
add_action( 'init', 'create_athlete_taxonomy' ); function create_athlete_taxonomy() { $labels = array( 'name' => 'Athletes', 'singular_name' => 'Athlete', 'search_items' => 'Search Athletes', 'all_items' => 'All Athletes', 'edit_item' => 'Edit Athlete', 'update_item' => 'Update Athlete', 'add_new_item' => 'Add New Athlete', 'new_item_name' => 'New Athlete Name', 'menu_name' => 'Athlete', 'view_item' => 'View Athlete', 'popular_items' => 'Popular Athlete', 'separate_items_with_commas' => 'Separate athletes with commas', 'add_or_remove_items' => 'Add or remove athletes', 'choose_from_most_used' => 'Choose from the most used athletes', 'not_found' => 'No athletes found' ); register_taxonomy( 'athlete', 'post', array( 'label' => __( 'Athlete' ), 'hierarchical' => false, 'labels' => $labels, 'public' => true, 'show_in_nav_menus' => false, 'show_tagcloud' => false, 'show_admin_column' => true, 'rewrite' => array( 'slug' => 'athletes' ) ) ); }
Widgets
// Register and load the widget function wpb_load_widget() { register_widget( 'wpb_widget' ); } add_action( 'widgets_init', 'wpb_load_widget' ); // Creating the widget class wpb_widget extends WP_Widget { function __construct() { parent::__construct( // Base ID of your widget 'wpb_widget', // Widget name will appear in UI __('WPBeginner Widget', 'wpb_widget_domain'), // Widget description array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), ) ); } // Creating widget front-end public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); // before and after widget arguments are defined by themes echo $args['before_widget']; if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title']; // This is where you run the code and display the output echo __( 'Hello, World!', 'wpb_widget_domain' ); echo $args['after_widget']; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'New title', 'wpb_widget_domain' ); } // Widget admin form ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <?php } // Updating widget replacing old instances with new public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; return $instance; } } // Class wpb_widget ends here