WordPress面包屑导航

/*=============================================
=            BREADCRUMBS			            =
=============================================*/

//  to include in functions.php
function the_breadcrumb() {

    $sep = '    »   ';

    if (!is_front_page()) {
	
	// Start the breadcrumb with a link to your homepage
        echo '<ol class="breadcrumb no-border">';
        echo '<li class="breadcrumb-items light"><a class="link link-light-primary size-14" data-hover="' . get_the_title(get_page_by_path( 'home' )) . '" href="';
        echo get_option( 'home' );
        echo '">';
        echo get_the_title(get_page_by_path( 'home' ));
        echo '</a></li>' . $sep;
	
	// Check if the current page is a category, an archive or a single page. If so show the category or archive name.
        if (is_category() || is_single() ){
        	echo '<li class="breadcrumb-items light">';
            the_category('title_li=');
            echo '</li>';
        } elseif (is_archive() || is_single()){
            if ( is_day() ) {
                printf( __( '%s', 'webagency' ), get_the_date() );
            } elseif ( is_month() ) {
                printf( __( '%s', 'webagency' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'webagency' ) ) );
            } elseif ( is_year() ) {
                printf( __( '%s', 'webagency' ), get_the_date( _x( 'Y', 'yearly archives date format', 'webagency' ) ) );
            } else {
                _e( 'Blog Archives', 'webagency' );
            }
        }
	
	// If the current page is a single post, show its title with the separator
        if (is_single()) {
            echo $sep;
            the_title();
        }
	
	// If the current page is a static page, show its title.
        if (is_page()) {
            echo the_title();
        }
	
	// if you have a static page assigned to be you posts list page. It will find the title of the static page and display it. i.e Home >> Blog
        if (is_home()){
            global $post;
            $page_for_posts_id = get_option('page_for_posts');
            if ( $page_for_posts_id ) { 
                $post = get_page($page_for_posts_id);
                setup_postdata($post);
                the_title();
                rewind_posts();
            }
        }

        echo '</ol>';
    }
}

WordPress footer walker

//Class custom

class Footer_Walker extends Walker_Nav_Menu {
  function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
    $classes = empty($item->classes) ? array () : (array) $item->classes;
    $class_names = join(' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item,1,4 ) ); //设置权重防止filter冲突
    !empty ( $class_names ) and $class_names = ' class="'. esc_attr( $class_names ) . '"';
    $output .= '';
    $attributes  = '';
    !empty( $item->attr_title ) and $attributes .= ' title="'  . esc_attr( $item->attr_title ) .'"';
    !empty( $item->target ) and $attributes .= ' target="' . esc_attr( $item->target     ) .'"';
    !empty( $item->xfn ) and $attributes .= ' rel="'    . esc_attr( $item->xfn        ) .'"';
    !empty( $item->url ) and $attributes .= ' href="'   . esc_attr( $item->url        ) .'"';
    $title = apply_filters( 'the_title', $item->title, $item->ID );
    $item_output = $args->before
    ."<div class='clear-fix w-100'></div>"
    . "<a class='link link-gray size-18 animsition-link' $attributes data-hover='$title'>"
    . $args->link_before
    . $title
    . '</a>'
    . $args->link_after
    . $args->after;
    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  }
}

给the_category的a标签添加class和data-hover

//给 the_category的a标签添加class和data-hover

function add_category_callback( $result ) {

  $class = strtolower( $result[2] );
  $class = str_replace( ' ', '-', $class );
  // do more sanitazion on the class (slug) like esc_attr() and so on

  $replacement = sprintf( 'class="link link-light-primary size-14">%s</a>', $class, $result[2] );
  return preg_replace( '#>([^<]+)</a>#Uis', $replacement, $result[0] );

}

function add_category_slug( $html ) {

  $search  = '#<a[^>]+(\>([^<]+)\</a>)#Uuis';
  $html = preg_replace_callback( $search, 'add_category_callback', $html );

  return $html;
}

add_filter( 'the_category', 'add_category_slug', 99, 1 );

function add_hover_callback( $result ) {

  $class = strtolower( $result[2] );
  $class = str_replace( ' ', '-', $class );
  // do more sanitazion on the class (slug) like esc_attr() and so on

  $replacement = sprintf( 'data-hover="%s">%s</a>', $class, $result[2] );
  return preg_replace( '#>([^<]+)</a>#Uis', $replacement, $result[0] );

}

function add_hover_category_slug( $html ) {

  $search  = '#<a[^>]+(\>([^<]+)\</a>)#Uuis';
  $html = preg_replace_callback( $search, 'add_hover_callback', $html );

  return $html;
}

add_filter( 'the_category', 'add_hover_category_slug', 99, 2 );

Bootstrap的pagination函数

//also need to change thr core file of the a tag and the span tag with the file name of generate template.php
function get_bootstrap_paginate_links() {
	ob_start();
	?>
		<div class="pages clearfix">
			<?php
				global $wp_query;
				$current = max( 1, absint( get_query_var( 'paged' ) ) );
				$pagination = paginate_links( array(
					'base' => str_replace( PHP_INT_MAX, '%#%', esc_url( get_pagenum_link( PHP_INT_MAX ) ) ),
					'format' => '?paged=%#%',
					'current' => $current,
					'total' => $wp_query->max_num_pages,
					'type' => 'array',
					'prev_text' => '&laquo;',
					'next_text' => '&raquo;',
				) ); ?>

			<?php if ( ! empty( $pagination ) ) : ?>
				<ul class="pagination justify-content-center">
					<?php foreach ( $pagination as $key => $page_link ) : ?>
						<li class="page-item paginated_link<?php if ( strpos( $page_link, 'current' ) !== false ) { echo ' active'; } ?>">
							<?php echo $page_link;

 ?>
								
						</li>
					<?php endforeach ?>
				</ul>
			<?php endif ?>
		</div>


	<?php
	
}
function wa_paginate_links() {
	echo get_bootstrap_paginate_links();
}

WP_nav_menu function

wp_nav_menu( array $args = array() )

Displays a navigation menu.


Parameters #Parameters

$args

(array) (Optional) Array of nav menu arguments.

  • ‘menu’
    (int|string|WP_Term) Desired menu. Accepts a menu ID, slug, name, or object.
  • ‘menu_class’
    (string) CSS class to use for the ul element which forms the menu. Default ‘menu’.
  • ‘menu_id’
    (string) The ID that is applied to the ul element which forms the menu. Default is the menu slug, incremented.
  • ‘container’
    (string) Whether to wrap the ul, and what to wrap it with. Default ‘div’.
  • ‘container_class’
    (string) Class that is applied to the container. Default ‘menu-{menu slug}-container’.
  • ‘container_id’
    (string) The ID that is applied to the container.
  • ‘container_aria_label’
    (string) The aria-label attribute that is applied to the container when it’s a nav element.
  • ‘fallback_cb’
    (callable|bool) If the menu doesn’t exist, a callback function will fire. Default is ‘wp_page_menu’. Set to false for no fallback.
  • ‘before’
    (string) Text before the link markup.
  • ‘after’
    (string) Text after the link markup.
  • ‘link_before’
    (string) Text before the link text.
  • ‘link_after’
    (string) Text after the link text.
  • ‘echo’
    (bool) Whether to echo the menu or return it. Default true.
  • ‘depth’
    (int) How many levels of the hierarchy are to be included. 0 means all. Default 0. Default 0.
  • ‘walker’
    (object) Instance of a custom walker class.
  • ‘theme_location’
    (string) Theme location to be used. Must be registered with register_nav_menu() in order to be selectable by the user.
  • ‘items_wrap’
    (string) How the list items should be wrapped. Uses printf() format with numbered placeholders. Default is a ul with an id and class.
  • ‘item_spacing’
    (string) Whether to preserve whitespace within the menu’s HTML. Accepts ‘preserve’ or ‘discard’. Default ‘preserve’.

Default value: array()


Top ↑

Return #Return

(void|string|false) Void if ‘echo’ argument is true, menu output if ‘echo’ is false. False if there are no items or no menu was found.


Top ↑

More Information #More Information

Usage #Usage

1wp_nav_menu( $args );

Given a theme_location parameter, the function displays the menu assigned to that location. If no such location exists or no menu is assigned to it, the parameter fallback_cb will determine what is displayed.

If not given a theme_location parameter, the function displays

  • the menu matching the ID, slug, or name given by the menu parameter;
  • otherwise, the first non-empty menu;
  • otherwise (or if the menu given by menu is empty), output of the function given by the fallback_cb parameter (wp_page_menu(), by default);
  • otherwise nothing.

Top ↑

The following classes are applied to menu items, i.e. to the HTML <li> tags, generated by wp_nav_menu():

All Menu Items #All Menu Items

  • .menu-item
    This class is added to every menu item.
  • .menu-item-has-children
    This class is added to menu item which has sub-items .
  • .menu-item-object-{object}
    This class is added to every menu item, where {object} is either a post type or a taxonomy.
  • .menu-item-object-category
    This class is added to menu items that correspond to a category.
  • .menu-item-object-tag
    This class is added to menu items that correspond to a tag.
  • .menu-item-object-page
    This class is added to menu items that correspond to static pages.
  • .menu-item-object-{custom}
    This class is added to menu items that correspond to a custom post type or a custom taxonomy.
  • .menu-item-type-{type}
    This class is added to every menu item, where {type} is either “post_type” or “taxonomy”.
  • .menu-item-type-post_type
    This class is added to menu items that correspond to post types: i.e. static pages or custom post types.
  • .menu-item-type-taxonomy
    This class is added to menu items that correspond to taxonomies: i.e. categories, tags, or custom taxonomies.

Top ↑

Current-Page Menu Items #Current-Page Menu Items

  • .current-menu-item
    This class is added to menu items that correspond to the currently rendered page.

Top ↑

Current-Page Parent Menu Items #Current-Page Parent Menu Items

  • .current-menu-parent
    This class is added to menu items that correspond to the hierarchical parent of the currently rendered page.
  • .current-{object}-parent
    This class is added to menu items that correspond to the hierachical parent of the currently rendered object, where {object} corresponds to the the value used for .menu-item-object-{object}.
  • .current-{type}-parent
    This class is added to menu items that correspond to the hierachical parent of the currently rendered type, where {type} corresponds to the the value used for .menu-item-type-{type}.

Top ↑

Current-Page Ancestor Menu Items #Current-Page Ancestor Menu Items

  • .current-menu-ancestor
    This class is added to menu items that correspond to a hierarchical ancestor of the currently rendered page.
  • .current-{object}-ancestor
    This class is added to menu items that correspond to a hierachical ancestor of the currently rendered object, where {object} corresponds to the the value used for .menu-item-object-{object}.
  • .current-{type}-ancestor
    This class is added to menu items that correspond to a hierachical ancestor of the currently rendered type, where {type} corresponds to the the value used for .menu-item-type-{type}.

Top ↑

Site Front Page Menu Items #Site Front Page Menu Items

  • .menu-item-home
    This class is added to menu items that correspond to the site front page.

Top ↑

Backward Compatibility with wp_page_menu() #Backward Compatibility withwp_page_menu()

The following classes are added to maintain backward compatibility with the [[Function Reference/wp_page_menu|wp_page_menu()]] function output:

  • .page_item
    This class is added to menu items that correspond to a static page.
  • .page_item_has_children
    This class is added to menu items that have sub pages to it.
  • .page-item-$ID
    This class is added to menu items that correspond to a static page, where $ID is the static page ID.
  • .current_page_item
    This class is added to menu items that correspond to the currently rendered static page.
  • .current_page_parent
    This class is added to menu items that correspond to the hierarchical parent of the currently rendered static page.
  • .current_page_ancestor
    This class is added to menu items that correspond to a hierarchical ancestor of the currently rendered static page.

Register sidebar function

register_sidebar( array|string $args = array() )

Builds the definition for a single sidebar and returns the ID.

Description #Description

Accepts either a string or an array and then parses that against a set of default arguments for the new sidebar. WordPress will automatically generate a sidebar ID and name based on the current number of registered sidebars if those arguments are not included.

When allowing for automatic generation of the name and ID parameters, keep in mind that the incrementor for your sidebar can change over time depending on what other plugins and themes are installed.

If theme support for ‘widgets’ has not yet been added when this function is called, it will be automatically enabled through the use of add_theme_support()


Top ↑

Parameters #Parameters

$args

(array|string) (Optional) Array or string of arguments for the sidebar being registered.

  • ‘name’
    (string) The name or title of the sidebar displayed in the Widgets interface. Default ‘Sidebar $instance’.
  • ‘id’
    (string) The unique identifier by which the sidebar will be called. Default ‘sidebar-$instance’.
  • ‘description’
    (string) Description of the sidebar, displayed in the Widgets interface. Default empty string.
  • ‘class’
    (string) Extra CSS class to assign to the sidebar in the Widgets interface.
  • ‘before_widget’
    (string) HTML content to prepend to each widget’s HTML output when assigned to this sidebar. Default is an opening list item element.
  • ‘after_widget’
    (string) HTML content to append to each widget’s HTML output when assigned to this sidebar. Default is a closing list item element.
  • ‘before_title’
    (string) HTML content to prepend to the sidebar title when displayed. Default is an opening h2 element.
  • ‘after_title’
    (string) HTML content to append to the sidebar title when displayed. Default is a closing h2 element.

Default value: array()


Top ↑

Return #Return

(string) Sidebar ID added to $wp_registered_sidebars global.


Top ↑

Source #Source

File: wp-includes/widgets.php

WordPress100个常用函数

1. get_theme_mod()

Retrieve theme modification value for the current theme.


2. add_setting()

Add a customize setting.


4. apply_filters()

Call the functions added to a filter hook.


5. esc_attr()

Escaping for HTML attributes.


6. get_option()

Retrieves an option value based on an option name.


7. esc_url()

Checks and cleans a URL.


8. esc_html()

Escaping for HTML blocks.


9. _e()

In WordPress, strings in the php files are marked for translation to other languages, and localization using two functions: __() and _e().


10. absint()

Convert a value to non-negative integer.


11. get_template_part()

Loads a template part into a template.


12. is_singular()

Is the query for an existing single post of any post type (post, attachment, page, custom post types)?


13. get_post_type()

Retrieves the post type of the current post or of a given post.


14. get_the_ID()

Retrieve the ID of the current item in the WordPress Loop.


15. the_content()

Display the post content.


16. have_posts()

Whether current WordPress query has results to loop over.


17. post_class()

Display the classes for the post div.


18. get_comments_number()

Retrieves the amount of comments a post has.


19. the_ID()

Display the ID of the current item in the WordPress Loop.


20. is_single()

Is the query for an existing single post?


21. get_permalink()

Retrieves the full permalink for the current post or post ID.


22. get_the_title()

Retrieve post title.


23. admin_url()

Retrieves the URL to the admin area for the current site.


24. add_section()

Add a customize section.


25. is_home()

Determines if the query is for the blog homepage.


26. get_sidebar()

Load sidebar template.


27. get_footer()

Load footer template.


28. is_customize_preview()

Whether the site is being previewed in the Customizer.


29. wp_nav_menu()

Displays a navigation menu.


30. the_title()

Display or retrieve the current post title with optional markup.


31. current_user_can()

Whether the current user has a specific capability.


32. is_active_sidebar()

Whether a sidebar is in use.


33. wp_link_pages()

The formatted output of a list of pages.


34. get_the_time()

Retrieve the time at which the post was written.


35. get_the_date()

Retrieve the date on which the post was written.


36. the_permalink()

Displays the permalink for the current post.


37. the_post()

Iterate the post index in the loop.


38. esc_attr_e()

Display translated text that has been escaped for safe use in an attribute.


39. is_front_page()

Is the query for the front page of the site?


40. bloginfo()

Displays information about the current site.


41. comments_open()

Whether the current post is open for comments.


42. post_password_required()

Whether post requires password and correct password has been provided.


43. has_post_thumbnail()

Check if post has an image attached.


44. get_bloginfo()

Retrieves information about the current site.


45. get_post_format()

Retrieve the format slug for a post


46. dynamic_sidebar()

Display dynamic sidebar.


47. is_search()

Is the query for a search?


48. home_url()

Retrieves the URL for the current site where the front end is accessible.


49. comments_template()

Load the comment template specified in $file.


50. add_theme_support()

Registers theme support for a given feature.


51. add_query_arg()

Retrieves a modified URL query string.


52. has_nav_menu()

Determines whether a registered nav menu location has a menu assigned to it.


53. is_wp_error()

Check whether variable is a WordPress Error.


54. get_the_author_meta()

Retrieves the requested data of the author of the current post.


55. edit_post_link()

Displays the edit post link for post.


56. is_admin()

Whether the current request is for an administrative interface page.


57. the_excerpt()

Display the post excerpt.


58. wp_get_attachment_image_src()

Retrieve an image to represent an attachment.


59. _x()

Retrieve translated string with gettext context.


60. language_attributes()

Displays the language attributes for the html tag.


61. body_class()

Display the classes for the body element.


62. add_filter()

Hook a function or method to a specific filter action.


63. is_page()

Is the query for an existing single page?


64. register_sidebar()

Builds the definition for a single sidebar and returns the ID.


65. get_the_category_list()

Retrieve category list for a post in either HTML list or custom format.


66. get_the_tag_list()

Retrieve the tags for a post formatted as a string.


67. esc_attr_x()

Translate string with gettext context, and escapes it for safe use in an attribute.


68. get_setting()

Get value based on option. (Use get_option() instead.)


69. add_action()

Hooks a function on to a specific action.


70. have_comments()

Whether there are comments to loop over.


71. is_archive()

Is the query for an existing archive page?


72. wp_list_comments()

List comments.


73. wp_enqueue_style()

Enqueue a CSS stylesheet.


74. set_transient()

Set/update the value of a transient.


75. wp_enqueue_script()

Enqueue a script.


76. get_search_form()

Display search form.


77. get_post_thumbnail_id()

Retrieve post thumbnail ID.


78. get_transient()

Get the value of a transient.


79. the_post_thumbnail()

Display the post thumbnail.


80. get_search_query()

Retrieves the contents of the search WordPress query variable.


81. add_partial()


82. get_the_modified_date()

Retrieve the date on which the post was last modified.


83. get_author_posts_url()

Retrieve the URL to the author page for the user with the ID provided.


84. wp_footer()

Fire the wp_footer action.


85. wp_head()

Fire the wp_head action.


86. get_the_post_thumbnail()

Retrieve the post thumbnail.


87. comment_form()

Outputs a complete commenting form for use within a template.


88. number_format_i18n()

Convert float number to format based on the locale.


89. get_header()

Load header template.


90. the_posts_pagination()

Displays a paginated navigation to next/previous set of posts, when applicable.


91. register_nav_menus()

Registers navigation menu locations for a theme.


92. wp_die()

Kill WordPress execution and display HTML message with error message.


93. wp_reset_postdata()

After looping through a separate query, this function restores the $post global to the current post in the main query.


94. load_theme_textdomain()

Load the theme’s translated strings.


95. get_queried_object_id()

Retrieve ID of the current queried object.


96. esc_url_raw()

Performs esc_url() for database usage.


97. the_archive_title()

Display the archive title based on the queried object.


98. add_image_size()

Register a new image size.


99. get_theme_file_uri()

Retrieves the URL of a file in the theme.


100. get_stylesheet_uri()

Retrieves the URI of current theme stylesheet.

WordPress walker part-1

walker在任何程序里都存在,是一个方法将一个多级的array循环出来。wordpress本身有自带的walker, 很多时候要自定义walker.

start element 函数和end element 函数会循环每个单个的类目,start lvl 和end lvl函数会被读取当循环数据开始时和结束时候, 不会循环,只是在循环开始时候和结束时候读取。

召唤walker的方式是在wp_nav_menu的函数里边,

 <?php wp_nav_menu( array(
              'theme_location'  => 'header',
              'container'  => false,
              'fallback_cb'  => false,
              'walker'  => new Ju_Custom_Nav_Walker(),
  

            ) ); ?>

bootstrap的nav walker:

<?php
        wp_nav_menu( array(
            'theme_location'    => 'primary',
            'depth'             => 2,
            'container'         => 'div',
            'container_class'   => 'collapse navbar-collapse',
            'container_id'      => 'bs-example-navbar-collapse-1',
            'menu_class'        => 'nav navbar-nav',
            'fallback_cb'       => 'WP_Bootstrap_Navwalker::fallback',
            'walker'            => new WP_Bootstrap_Navwalker(),
        ) );
        ?>

简单的walker class:(注意要在functions.php里面include进来或者require进来。

<?php 

class Ju_Custom_Nav_Walker extends Walker_Nav_Menu {
	public function start_lvl(&$output,$depth = 0,$args = []) {
		$output  .= '<ul class="special-class">';
		
	}

	public function start_el(&$output,$item,$depth = 0,$args = [],$id = 0 ) {  //添加 $item 创建 item ,$id 包含这个menu的id ,wordpress 所有menu都有id 
		$output .= '<li class="special-class-item">';
		$output .= $args->before;  //the $args valuble contais the value you should set inside the wp_nav_menu function , 也就是 wp_nav_menu args 里面的 before 和 after ;
		$output .= '<a class="special-list-link" href="' . $item->url . '">';  //item value 包含 menu 的loop; 
		$output .= $args->link_before . $item->title . $args->link_after;

		$output .= '</a>';
		$output .= $args->after;



	}

	public function end_el(&$output,$item,$depth = 0,$args = [],$id = 0) {
		$output .= '</li>';
	}

	public function end_lvl(&$output,$depth = 0,$args = []) {

		$output .= '</ul>';
	}
}  //用walker之后 父级的li 也添加了 class 
//start lv and end lv functions get appied to sub menu item, the start el and end el functions get applied to all menus including  main level ones,  start lvl 函数 应用在子级, start el 函数应用在 全部 
//start element 和 end element  will loop through each individual item, the start level and end level will be called during the beging and ending of the data structure;