{"id":644,"date":"2017-09-16T02:22:28","date_gmt":"2017-09-16T02:22:28","guid":{"rendered":"http:\/\/frowningbear.com\/blog\/?p=644"},"modified":"2018-05-29T06:31:07","modified_gmt":"2018-05-29T06:31:07","slug":"wordpress-code-snippets","status":"publish","type":"post","link":"https:\/\/frowningbear.com\/codebase\/2017\/09\/16\/wordpress-code-snippets\/","title":{"rendered":"WordPress code snippets"},"content":{"rendered":"<p>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.<\/p>\n<p><!--more--><\/p>\n<pre class=\"lang:default decode:true\" title=\"Basic functions.php\">if ( ! function_exists( 'myfirsttheme_setup' ) ) :\n\/**\n * Sets up theme defaults and registers support for various WordPress features.\n *\n * Note that this function is hooked into the after_setup_theme hook, which runs\n * before the init hook. The init hook is too late for some features, such as indicating\n * support post thumbnails.\n *\/\nfunction myfirsttheme_setup() {\n \n    \/**\n     * Make theme available for translation.\n     * Translations can be placed in the \/languages\/ directory.\n     *\/\n    load_theme_textdomain( 'myfirsttheme', get_template_directory() . '\/languages' );\n \n    \/**\n     * Add default posts and comments RSS feed links to &lt;head&gt;.\n     *\/\n    add_theme_support( 'automatic-feed-links' );\n \n    \/**\n     * Enable support for post thumbnails and featured images.\n     *\/\n    add_theme_support( 'post-thumbnails' );\n \n    \/**\n     * Add support for two custom navigation menus.\n     *\/\n    register_nav_menus( array(\n        'primary'   =&gt; __( 'Primary Menu', 'myfirsttheme' ),\n        'secondary' =&gt; __('Secondary Menu', 'myfirsttheme' )\n    ) );\n \n    \/**\n     * Enable support for the following post formats:\n     * aside, gallery, quote, image, and video\n     *\/\n    add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );\n}\nendif; \/\/ myfirsttheme_setup\nadd_action( 'after_setup_theme', 'myfirsttheme_setup' );<\/pre>\n<pre class=\"lang:default decode:true \" title=\"Basic functions.php\" >\/**\n * MyFirstTheme's functions and definitions\n *\n * @package MyFirstTheme\n * @since MyFirstTheme 1.0\n *\/\n \n\/**\n * First, let's set the maximum content width based on the theme's design and stylesheet.\n * This will limit the width of all uploaded images and embeds.\n *\/\nif ( ! isset( $content_width ) )\n    $content_width = 800; \/* pixels *\/\n \nif ( ! function_exists( 'myfirsttheme_setup' ) ) :\n\/**\n * Sets up theme defaults and registers support for various WordPress features.\n *\n * Note that this function is hooked into the after_setup_theme hook, which runs\n * before the init hook. The init hook is too late for some features, such as indicating\n * support post thumbnails.\n *\/\nfunction myfirsttheme_setup() {\n \n    \/**\n     * Make theme available for translation.\n     * Translations can be placed in the \/languages\/ directory.\n     *\/\n    load_theme_textdomain( 'myfirsttheme', get_template_directory() . '\/languages' );\n \n    \/**\n     * Add default posts and comments RSS feed links to &lt;head&gt;.\n     *\/\n    add_theme_support( 'automatic-feed-links' );\n \n    \/**\n     * Enable support for post thumbnails and featured images.\n     *\/\n    add_theme_support( 'post-thumbnails' );\n \n    \/**\n     * Add support for two custom navigation menus.\n     *\/\n    register_nav_menus( array(\n        'primary'   =&gt; __( 'Primary Menu', 'myfirsttheme' ),\n        'secondary' =&gt; __('Secondary Menu', 'myfirsttheme' )\n    ) );\n \n    \/**\n     * Enable support for the following post formats:\n     * aside, gallery, quote, image, and video\n     *\/\n    add_theme_support( 'post-formats', array ( 'aside', 'gallery', 'quote', 'image', 'video' ) );\n}\nendif; \/\/ myfirsttheme_setup\nadd_action( 'after_setup_theme', 'myfirsttheme_setup' );\n\n<\/pre>\n<p>Loop through a query twice with rewind_loop.<\/p>\n<pre class=\"lang:default decode:true \" title=\"Rewinding the loop\">\/\/ Start the main loop\n&lt;?php\n    if ( have_posts() ) : while ( have_posts() ) : the_post();\n        the_title();\n    endwhile;\n    endif;\n \n    \/\/ Use rewind_posts() to use the query a second time.\n    rewind_posts();\n \n    \/\/ Start a new loop\n    while ( have_posts() ) : the_post();\n        the_content();\n    endwhile;\n?&gt;<\/pre>\n<p>displaying a single post with a list of posts from the same category below the single post.<\/p>\n<pre class=\"lang:default decode:true \" title=\"Secondary query\">&lt;?php\n    \/\/ The main query.\n    if ( have_posts() ) : while ( have_posts() ) : the_post();\n        the_title();                                                             \n        the_content();                                                          \n    endwhile;                                                                   \n    else :                                                                      \n        \/\/ When no posts are found, output this text.                           \n        _e( 'Sorry, no posts matched your criteria.' );                         \n    endif;                                                                       \n    wp_reset_postdata();                                                        \n                                                                                 \n    \/*                                                                          \n     * The secondary query. Note that you can use any category name here. In our example,\n     * we use \"example-category\".                                               \n     *\/                                                                        \n    $secondary_query = new WP_Query( 'category_name=example-category' );        \n                                                                                 \n    \/\/ The second loop. if ( $secondary_query-&gt;have_posts() ) \n    echo '&lt;ul&gt;';\n    while ( $secondary_query-&gt;have_posts() ) :\n        $secondary_query-&gt;the_post();\n        echo '&lt;li&gt;' . get_the_title() . '&lt;\/li&gt;';\n    endwhile;\n    echo '&lt;\/ul&gt;';\n    endif;\nwp_reset_postdata();\n?&gt;<\/pre>\n<pre class=\"lang:default decode:true \" title=\"Display random posts\">function wpb_rand_posts() { \n \n$args = array(\n    'post_type' =&gt; 'post',\n    'orderby'   =&gt; 'rand',\n    'posts_per_page' =&gt; 5, \n    );\n \n$the_query = new WP_Query( $args );\n \nif ( $the_query-&gt;have_posts() ) {\n \n$string .= '&lt;ul&gt;';\n    while ( $the_query-&gt;have_posts() ) {\n        $the_query-&gt;the_post();\n        $string .= '&lt;li&gt;&lt;a href=\"'. get_permalink() .'\"&gt;'. get_the_title() .'&lt;\/a&gt;&lt;\/li&gt;';\n    }\n    $string .= '&lt;\/ul&gt;';\n    \/* Restore original Post Data *\/\n    wp_reset_postdata();\n} else {\n \n$string .= 'no posts found';\n}\n \nreturn $string; \n} \n \nadd_shortcode('wpb-random-posts','wpb_rand_posts');\nadd_filter('widget_text', 'do_shortcode');<\/pre>\n<p>Now you can display random posts inside a WordPress post, page, or text widget using the shortcode [wpb-random-posts].<\/p>\n<p>&nbsp;<\/p>\n<h3>Custom Taxonomies<\/h3>\n<pre class=\"lang:default decode:true \" title=\"Custom Hierarchical Taxonomy\">\/\/hook into the init action and call create_book_taxonomies when it fires\nadd_action( 'init', 'create_topics_hierarchical_taxonomy', 0 );\n \n\/\/create a custom taxonomy name it topics for your posts\n \nfunction create_topics_hierarchical_taxonomy() {\n \n\/\/ Add new taxonomy, make it hierarchical like categories\n\/\/first do the translations part for GUI\n \n  $labels = array(\n    'name' =&gt; _x( 'Topics', 'taxonomy general name' ),\n    'singular_name' =&gt; _x( 'Topic', 'taxonomy singular name' ),\n    'search_items' =&gt;  __( 'Search Topics' ),\n    'all_items' =&gt; __( 'All Topics' ),\n    'parent_item' =&gt; __( 'Parent Topic' ),\n    'parent_item_colon' =&gt; __( 'Parent Topic:' ),\n    'edit_item' =&gt; __( 'Edit Topic' ), \n    'update_item' =&gt; __( 'Update Topic' ),\n    'add_new_item' =&gt; __( 'Add New Topic' ),\n    'new_item_name' =&gt; __( 'New Topic Name' ),\n    'menu_name' =&gt; __( 'Topics' ),\n  );    \n \n\/\/ Now register the taxonomy\n \n  register_taxonomy('topics',array('post'), array(\n    'hierarchical' =&gt; true,\n    'labels' =&gt; $labels,\n    'show_ui' =&gt; true,\n    'show_admin_column' =&gt; true,\n    'query_var' =&gt; true,\n    'rewrite' =&gt; array( 'slug' =&gt; 'topic' ),\n  ));\n \n}<\/pre>\n<hr \/>\n<pre class=\"lang:default decode:true \" title=\"Non-hierarchical Custom Taxonomy\">\/\/hook into the init action and call create_topics_nonhierarchical_taxonomy when it fires\n \nadd_action( 'init', 'create_topics_nonhierarchical_taxonomy', 0 );\n \nfunction create_topics_nonhierarchical_taxonomy() {\n \n\/\/ Labels part for the GUI\n \n  $labels = array(\n    'name' =&gt; _x( 'Topics', 'taxonomy general name' ),\n    'singular_name' =&gt; _x( 'Topic', 'taxonomy singular name' ),\n    'search_items' =&gt;  __( 'Search Topics' ),\n    'popular_items' =&gt; __( 'Popular Topics' ),\n    'all_items' =&gt; __( 'All Topics' ),\n    'parent_item' =&gt; null,\n    'parent_item_colon' =&gt; null,\n    'edit_item' =&gt; __( 'Edit Topic' ), \n    'update_item' =&gt; __( 'Update Topic' ),\n    'add_new_item' =&gt; __( 'Add New Topic' ),\n    'new_item_name' =&gt; __( 'New Topic Name' ),\n    'separate_items_with_commas' =&gt; __( 'Separate topics with commas' ),\n    'add_or_remove_items' =&gt; __( 'Add or remove topics' ),\n    'choose_from_most_used' =&gt; __( 'Choose from the most used topics' ),\n    'menu_name' =&gt; __( 'Topics' ),\n  ); \n \n\/\/ Now register the non-hierarchical taxonomy like tag\n \n  register_taxonomy('topics','post',array(\n    'hierarchical' =&gt; false,\n    'labels' =&gt; $labels,\n    'show_ui' =&gt; true,\n    'show_admin_column' =&gt; true,\n    'update_count_callback' =&gt; '_update_post_term_count',\n    'query_var' =&gt; true,\n    'rewrite' =&gt; array( 'slug' =&gt; 'topic' ),\n  ));\n}<\/pre>\n<p>Display Custom Taxonomy<\/p>\n<pre class=\"lang:default decode:true \" title=\"Display simple\">\t\n&lt;?php the_terms( $post-&gt;ID, 'topics', 'Topics: ', ', ', ' ' ); ?&gt;<\/pre>\n<p>\u2260==========<\/p>\n<pre class=\"lang:default decode:true \" title=\"Custom Taxonomy wpmudev\">add_action( 'init', 'create_athlete_taxonomy' );\n\nfunction create_athlete_taxonomy() {\n\t$labels = array(\n\t\t'name'                           =&gt; 'Athletes',\n\t\t'singular_name'                  =&gt; 'Athlete',\n\t\t'search_items'                   =&gt; 'Search Athletes',\n\t\t'all_items'                      =&gt; 'All Athletes',\n\t\t'edit_item'                      =&gt; 'Edit Athlete',\n\t\t'update_item'                    =&gt; 'Update Athlete',\n\t\t'add_new_item'                   =&gt; 'Add New Athlete',\n\t\t'new_item_name'                  =&gt; 'New Athlete Name',\n\t\t'menu_name'                      =&gt; 'Athlete',\n\t\t'view_item'                      =&gt; 'View Athlete',\n\t\t'popular_items'                  =&gt; 'Popular Athlete',\n\t\t'separate_items_with_commas'     =&gt; 'Separate athletes with commas',\n\t\t'add_or_remove_items'            =&gt; 'Add or remove athletes',\n\t\t'choose_from_most_used'          =&gt; 'Choose from the most used athletes',\n\t\t'not_found'                      =&gt; 'No athletes found'\n\t);\n\n\tregister_taxonomy(\n\t\t'athlete',\n\t\t'post',\n\t\tarray(\n\t\t\t'label' =&gt; __( 'Athlete' ),\n\t\t\t'hierarchical' =&gt; false,\n\t\t\t'labels' =&gt; $labels,\n\t\t\t'public' =&gt; true,\n\t\t\t'show_in_nav_menus' =&gt; false,\n\t\t\t'show_tagcloud' =&gt; false,\n\t\t\t'show_admin_column' =&gt; true,\n\t\t\t'rewrite' =&gt; array(\n\t\t\t\t'slug' =&gt; 'athletes'\n\t\t\t)\n\t\t)\n\t);\n}<\/pre>\n<h3>Widgets<\/h3>\n<pre class=\"lang:default decode:true \" title=\"Custom widget\">\/\/ Register and load the widget\nfunction wpb_load_widget() {\n    register_widget( 'wpb_widget' );\n}\nadd_action( 'widgets_init', 'wpb_load_widget' );\n \n\/\/ Creating the widget \nclass wpb_widget extends WP_Widget {\n \nfunction __construct() {\nparent::__construct(\n \n\/\/ Base ID of your widget\n'wpb_widget', \n \n\/\/ Widget name will appear in UI\n__('WPBeginner Widget', 'wpb_widget_domain'), \n \n\/\/ Widget description\narray( 'description' =&gt; __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), ) \n);\n}\n \n\/\/ Creating widget front-end\n \npublic function widget( $args, $instance ) {\n$title = apply_filters( 'widget_title', $instance['title'] );\n \n\/\/ before and after widget arguments are defined by themes\necho $args['before_widget'];\nif ( ! empty( $title ) )\necho $args['before_title'] . $title . $args['after_title'];\n \n\/\/ This is where you run the code and display the output\necho __( 'Hello, World!', 'wpb_widget_domain' );\necho $args['after_widget'];\n}\n         \n\/\/ Widget Backend \npublic function form( $instance ) {\nif ( isset( $instance[ 'title' ] ) ) {\n$title = $instance[ 'title' ];\n}\nelse {\n$title = __( 'New title', 'wpb_widget_domain' );\n}\n\/\/ Widget admin form\n?&gt;\n&lt;p&gt;\n&lt;label for=\"&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;\"&gt;&lt;?php _e( 'Title:' ); ?&gt;&lt;\/label&gt; \n&lt;input class=\"widefat\" id=\"&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;\" name=\"&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;\" type=\"text\" value=\"&lt;?php echo esc_attr( $title ); ?&gt;\" \/&gt;\n&lt;\/p&gt;\n&lt;?php \n}\n     \n\/\/ Updating widget replacing old instances with new\npublic function update( $new_instance, $old_instance ) {\n$instance = array();\n$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';\nreturn $instance;\n}\n} \/\/ Class wpb_widget ends here<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>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.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[19],"tags":[],"class_list":["post-644","post","type-post","status-publish","format-standard","hentry","category-wordpress"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/644","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/comments?post=644"}],"version-history":[{"count":1,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/644\/revisions"}],"predecessor-version":[{"id":1237,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/644\/revisions\/1237"}],"wp:attachment":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/media?parent=644"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/categories?post=644"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/tags?post=644"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}