Repository: twittem/wp-bootstrap-navwalker
Branch: master
Commit: 11791945df1e
Files: 22
Total size: 119.6 KB
Directory structure:
gitextract_z5aidwga/
├── .codeclimate.yml
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── CONTRIBUTING.md
│ ├── ISSUE_TEMPLATE.md
│ └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── LICENSE.txt
├── README.md
├── bin/
│ └── install-wp-tests.sh
├── class-wp-bootstrap-navwalker.php
├── composer.json
├── phpcs.xml.dist
├── phpstan.neon.dist
├── phpunit.xml.dist
└── tests/
├── bootstrap.php
├── phpstan/
│ ├── class-wp-nav-menu-args.php
│ └── class-wp-nav-menu-item.php
└── test-navwalker.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .codeclimate.yml
================================================
---
version: "2"
plugins:
duplication:
enabled: true
config:
languages:
- php
fixme:
enabled: true
markdownlint:
enabled: true
phpcodesniffer:
enabled: true
config:
file_extensions: "php"
standard: "WordPress-Docs,WordPress-Extra"
phpmd:
enabled: true
checks:
Controversial/CamelCaseMethodName:
enabled: false
Controversial/CamelCaseParameterName:
enabled: false
Controversial/CamelCasePropertyName:
enabled: false
Controversial/CamelCaseVariableName:
enabled: false
CleanCode/ElseExpression:
enabled: false
shellcheck:
enabled: true
exclude_patterns:
- "**.dist"
- "**.lock"
- "**.json"
- "**.txt"
- "tests/*"
- "vendor/**"
================================================
FILE: .editorconfig
================================================
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
# WordPress Coding Standards
# https://make.wordpress.org/core/handbook/coding-standards/
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
[{.jshintrc,*.json,*.yml}]
indent_style = space
indent_size = 2
[{*.txt,wp-config-sample.php}]
end_of_line = crlf
================================================
FILE: .gitattributes
================================================
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Explicitly declare text files that will always be normalized and converted
# to native line endings on checkout.
.editorconfig text
.gitattributes text
.gitignore text
*.json text
*.md text
*.txt text
*.xml text
*.yml text
# Declare files that will always have LF line endings on checkout.
*.php text eol=lf
*.sh text eol=lf
# Exclude from export.
.* export-ignore
bin export-ignore
tests export-ignore
*.dist export-ignore
CODE_OF_CONDUCT.md export-ignore
composer.* export-ignore
================================================
FILE: .github/CONTRIBUTING.md
================================================
# Want to contribute?
Did you know that you could be instrumental in making the WP Bootstrap NavWalker more robust? If you use and love it, why not contribute to the project?
## Contributing for Everyone!
Whether you can barely recognize a filter (or don’t know what that means) or you’ve already authored your own plugins, there are ways for you to pitch in.
### Create Bug Reports
If you find a bug, just [file a GitHub issue](https://github.com/wp-bootstrap/wp-bootstrap-navwalker/issues), that’s all. If you want to prefix the title with a “Question:”, “Bug:”, or the general area of the application, that would be helpful, but by no means mandatory. If you have write access, add the appropriate labels.
If you’re filing a bug, specific steps to reproduce are helpful. Please include the URL of the page that has the bug, along with what you expected to see and what happened instead.
### Write and submit a patch
If you'd like to fix a bug, you can submit a Pull Request.
#### Where to get started?
If you'd like to contribute but don't know where to get started, you can take a look at existing issues:
- ["Good First Bug"](https://github.com/wp-bootstrap/wp-bootstrap-navwalker/labels/%5BTYPE%5D%20GOOD%20FIRST%20BUG) issues are a good entry point to get familiar with the codebase.
================================================
FILE: .github/ISSUE_TEMPLATE.md
================================================
<!-- Thanks for contributing to WP Bootstrap NavWalker! Pick a clear title and proceed. -->
#### Steps to reproduce the issue:
#### What I expected:
#### What happened instead:
<!--
PLEASE NOTE
- These comments won't show up when you submit the issue.
- Everything is optional, but try to add as many details as possible.
- If requesting a new feature, explain why you'd like to see it added.
- This issue tracker is not for support.
-->
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
Fixes #
#### Changes proposed in this Pull Request:
*
#### Testing instructions:
*
<!-- Add the following only if this is meant to be in changelog -->
#### Proposed changelog entry for your changes:
================================================
FILE: .gitignore
================================================
/vendor/
/phpcs.xml
================================================
FILE: .travis.yml
================================================
language: php
os:
- linux
dist: bionic
php:
- 7.4
- 7.3
- 7.2
- 7.1
- nightly
env:
- WP_VERSION=latest WP_MULTISITE=0 PHPUNIT_VERSION="^5.7"
- WP_VERSION=latest WP_MULTISITE=1 PHPUNIT_VERSION="^5.7"
services:
- mysql
jobs:
include:
- php: 7.0
dist: xenial
env:
- WP_VERSION=latest WP_MULTISITE=0 PHPUNIT_VERSION="^5.7"
- php: 7.0
dist: xenial
env:
- WP_VERSION=latest WP_MULTISITE=1 PHPUNIT_VERSION="^5.7"
- php: 5.6
dist: xenial
env:
- WP_VERSION=latest WP_MULTISITE=0 PHPUNIT_VERSION="^5.7"
- php: 5.6
dist: xenial
env:
- WP_VERSION=latest WP_MULTISITE=1 PHPUNIT_VERSION="^5.7"
- name: "Coding Standars"
php: 7.4
install:
- composer require --dev wp-coding-standards/wpcs dealerdirect/phpcodesniffer-composer-installer
# Counter wp-enforcer
- rm -f ./phpcs.xml
script:
- vendor/bin/phpcs
- name: "Static Analysis"
php: 7.4
install:
- composer require --dev szepeviktor/phpstan-wordpress
script:
- vendor/bin/phpstan analyze
allow_failures:
- php: nightly
branches:
only:
- master
cache:
directories:
- "${HOME}/.composer/cache"
install:
- bin/install-wp-tests.sh wordpress_test root "" localhost "${WP_VERSION}"
- composer global require --dev "phpunit/phpunit=${PHPUNIT_VERSION}"
script:
- "${HOME}/.composer/vendor/bin/phpunit"
notifications:
email:
on_success: never
on_failure: change
================================================
FILE: CHANGELOG.md
================================================
#CHANGELOG
## [4.3.0]
- Added an `aria-current` item.
- Added `.nav-item` for the `<li>` and `.nav-link` for the `<a>` in fallback function.
- Some escape improvements.
- Don't pass `$attributes` to element closing function as it's ignored anyway.
## [4.2.0]
- Fix typo in function name 'seporate'->'separate' (private function, no need to add back-compat).
## [4.1.0]
- Prevent error `trying to get property of non-object` when no menu is set to a location using the walker.
- Add `$depth` as 4th parameter passed to `nav_menu_link_attributes`.
- Add support for `dropdown-item-text` linkmod type.
## [4.0.3]
- Drop composer class autoload statement.
## [4.0.2]
- Fix dropdown opener having empty string for href value.
- More accurate regex matching of icon and linkmod classnames.
- Changed composer package type to `library` from `wordpress-plugin` again.
- Tests: Add unit tests for the function that separates classnames for the walker.
- Fix case sensitive matching to now match mixes of upper and lower case.
## [4.0.1]
- Fix untranslated string in fallback (this was lost in transition between v3 and v4, fixed again).
## [4.0.0]
- Added a prefix on @since tags to highlight when they refer to WP core instead of this class.
- Rework of `start_lvl()` and `start_el()` based on latest `Walker_Nav_Menu` Class from WP core.
- Whitespace preservation method improvements.
- Added `nav_menu_item_args` filter and `nav_menu_item_title` brought in at WP 4.4.0
- Use `the_title` filter prior to `nav_menu_item_title`.
- Added a labelled-by attribute to dropdowns for accessibility.
- Links inside dropdown have `.dropdown-item` instead of `.nav-link`.
- Remove `<span class="carat">` after parent dropdown items.
- Support `echo` arg in fallback menu. props: @toddlevy
- Add `.active` to parent when a child is current page. props: @zyberspace
- Fix to correct output of dropdown atts and styles when depth passed to wp_nav_menu is <= 1. props: @chrisgeary92
- Move icon output to a local var instead of modifying and clearing a global object.
- Reassign filtered classes back to $classes array so that updated classes can be accessed later if needed. props: @lf-jeremy
- Update to work with Bootstrap v4.
- Added `.nav-item` and `.nav-link` to `<li>` and `<a>` respectively.
- Dropped support for using title attribute to add link modifiers and icons.
- Added support for link modifiers and icons through WP Menu Builder 'classes' input.
- Icon support is for Font Awesome 4/5 and Glyphicons icons.
- Added unit tests for the `fallback` method.
- Added code to handle icon-only menus.
## [3.0.0]
- Fix untranslated string in fallback.
- Instruct screenreaders to ignore icons when present.
- Added basic unit tests and travis config.
- Swapped to IF statements with curly braces.
- Adds `$depth` arg for nav_menu_css_class filter.
- Fix sanitization function used for class output in fallback.
- Changed composer package type to `library` from `wordpress-plugin`.
## [2.0.5] - 2016-011-15
- Fixed all reported issues by WP Enforcer.
- Fixed several Code Climate issues.
## [2.0.4]
- Updated fallback function to accept args array from `wp_nav_menu`.
## [2.0.3]
- Included a fallback function that adds a link to the WordPress menu manager if no menu has been assigned to the theme location.
## [2.0.2]
- Small tweak to ensure carets are only displayed on top level dropdowns.
## [2.0.1]
- Added missing active class to active menu items.
## [2.0.0]
- Class was completly re-written using the latest Wordpress 3.6 walker class.
- Now full supports Bootstrap 3.0+
- Tested with wp_debug & the Theme Check plugin.
---
<small>All notable changes to this project will be documented in this file. Please read [Keep a Change Log](http://keepachangelog.com) for more information. This project adheres to [Semantic Versioning](http://semver.org).</small>
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at brandon@imforza.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
================================================
FILE: LICENSE.txt
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# WP Bootstrap Navwalker
[](https://codeclimate.com/github/wp-bootstrap/wp-bootstrap-navwalker)
[](https://codeclimate.com/github/wp-bootstrap/wp-bootstrap-navwalker/coverage)
[](https://codeclimate.com/github/wp-bootstrap/wp-bootstrap-navwalker)
[](https://travis-ci.org/wp-bootstrap/wp-bootstrap-navwalker)
[](https://scrutinizer-ci.com/g/wp-bootstrap/wp-bootstrap-navwalker/?branch=master)
[](https://scrutinizer-ci.com/g/wp-bootstrap/wp-bootstrap-navwalker/?branch=master)
[](https://scrutinizer-ci.com/g/wp-bootstrap/wp-bootstrap-navwalker/build-status/master)
**This code in the main repo branch is undergoing a big shakeup to bring it in line with recent standards and to merge and test the backlog of PRs I have left for too long. Please use the v4.3.0 tag for stable version while this process happens. https://github.com/wp-bootstrap/wp-bootstrap-navwalker/releases/tag/v4.3.0**
A custom WordPress Nav Walker Class to fully implement the Bootstrap 4 navigation style in a custom theme using the WordPress built in menu manager.
## NOTES
This is a utility class that is intended to format your WordPress theme menu with the correct syntax and CSS classes to utilize the Bootstrap dropdown navigation. It does not include the required Bootstrap JS and CSS files - you will have to include them manually.
### WordPress.org Theme Compliance
*This walker is fully compliant with all Theme Review guidelines for wordpress.org theme submission.* It requires no modification to be compliant but you can optionally replace the `wp-bootstrap-navwalker` text domain (which appears twice in the `fallback` function) with the text domain of your theme.
### Upgrade Notes
Between version 3 and version 4 of the walker there have been significant changes to the codebase. Version 4 of the walker is built to work with Bootstrap 4 and has not been tested for backwards compatibility with Bootstrap 3. A separate branch for Bootstrap 3 is maintained here: <https://github.com/wp-bootstrap/wp-bootstrap-navwalker/tree/v3-branch>
Here is a list of the most notable changes:
- The filename has been changed and prefixed with `class-` to better fit PHP coding standards naming conventions.
- New Name: `class-wp-bootstrap-navwalker.php`
- Old Name: `wp-bootstrap-navwalker.php`
- Icon and link modifier handling is now done through the `CSS Classes` menu item input instead of the `Title` input.
- Icon only items are possible using icon classes in combination with the `sr-only` classname.
## Installation
Place **class-wp-bootstrap-navwalker.php** in your WordPress theme folder `/wp-content/themes/your-theme/`
Open your WordPress themes **functions.php** file - `/wp-content/themes/your-theme/functions.php` - and add the following code:
```php
/**
* Register Custom Navigation Walker
*/
function register_navwalker(){
require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php';
}
add_action( 'after_setup_theme', 'register_navwalker' );
```
If you encounter errors with the above code use a check like this to return clean errors to help diagnose the problem.
```php
if ( ! file_exists( get_template_directory() . '/class-wp-bootstrap-navwalker.php' ) ) {
// File does not exist... return an error.
return new WP_Error( 'class-wp-bootstrap-navwalker-missing', __( 'It appears the class-wp-bootstrap-navwalker.php file may be missing.', 'wp-bootstrap-navwalker' ) );
} else {
// File exists... require it.
require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php';
}
```
You will also need to declare a new menu in your `functions.php` file if one doesn't already exist.
```php
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'THEMENAME' ),
) );
```
## Usage
Add or update any `wp_nav_menu()` functions in your theme (often found in `header.php`) to use the new walker by adding a `'walker'` item to the wp_nav_menu args array.
```php
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 2, // 1 = no dropdowns, 2 = with dropdowns.
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'navbar-nav mr-auto',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
```
Your menu will now be formatted with the correct syntax and classes to implement Bootstrap dropdown navigation.
Typically the menu is wrapped with additional markup, here is an example of a `fixed-top` menu that collapse for responsive navigation at the md breakpoint.
```php
<nav class="navbar navbar-expand-md navbar-light bg-light" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-controls="bs-example-navbar-collapse-1" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle navigation', 'your-theme-slug' ); ?>">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<?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(),
) );
?>
</div>
</nav>
```
To change your menu style add Bootstrap nav class names to the `menu_class` declaration.
Review options in the Bootstrap docs for more information on [nav classes](https://getbootstrap.com/components/#nav).
### Displaying the Menu
To display the menu you must associate your menu with your theme location. You can do this by selecting your theme location in the *Theme Locations* list while editing a menu in the WordPress menu manager.
### Making this Walker the Default Walker for Nav Menus
There has been some interest in making this walker the default walker for all menus. That could result in some unexpected situations but it can be achieved by adding this function to your functions.php file.
```php
function prefix_modify_nav_menu_args( $args ) {
return array_merge( $args, array(
'walker' => new WP_Bootstrap_Navwalker(),
) );
}
add_filter( 'wp_nav_menu_args', 'prefix_modify_nav_menu_args' );
```
Simply updating the walker may not be enough to get menus working right, you may need to add wrappers or additional classes, you can do that via the above function as well.
### Usage with Bootstrap 5
Bootstrap 5 uses namespaced data attributes. All `data` attributes now include `bs` as an infix. The new attributes work just like the old ones. Here’s the menu toggle button from the example above with the renamed data attributes.
```php
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#bs-example-navbar-collapse-1" aria-controls="bs-example-navbar-collapse-1" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle navigation', 'your-theme-slug' ); ?>">
<span class="navbar-toggler-icon"></span>
</button>
```
The walker also adds a data attribute for dropdown toggles via the `start_el()` method. Paste this to your functions.php to make the walker use the infixed data attibute.
```php
add_filter( 'nav_menu_link_attributes', 'prefix_bs5_dropdown_data_attribute', 20, 3 );
/**
* Use namespaced data attribute for Bootstrap's dropdown toggles.
*
* @param array $atts HTML attributes applied to the item's `<a>` element.
* @param WP_Post $item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @return array
*/
function prefix_bs5_dropdown_data_attribute( $atts, $item, $args ) {
if ( is_a( $args->walker, 'WP_Bootstrap_Navwalker' ) ) {
if ( array_key_exists( 'data-toggle', $atts ) ) {
unset( $atts['data-toggle'] );
$atts['data-bs-toggle'] = 'dropdown';
}
}
return $atts;
}
```
### Menu Caching
On some sites generating a large menu that rarely ever changes on every page request is an overhead that you may want to avoid. In those cases I can suggest you look at storing menu results in a transient.
The biggest drawback to caching nav menus with this method is that it cannot easily apply the `.current-menu-item` or the `.active` class to the currently active item as WP decides what is currently active on page load - and since the menu is cached it only knows the active page that it was cached on originally.
You can decide yourself if you want to put up with those drawbacks for the benefit of removing the menu generation time on most page loads. You can follow this article by Dave Clements to see how we cached nav menus that were generated by this walker: <https://www.doitwithwp.com/use-transients-speed-wordpress-menus/>
Be sure to set the `echo` argument to FALSE in `the wp_nav_menu()` call when doing this so that the results can be stored instead of echoed to the page.
See also:
- <https://generatewp.com/how-to-use-transients-to-speed-up-wordpress-menus/>
- <https://vip-svn.wordpress.com/plugins/cache-nav-menu/cache-nav-menu.php>
### Extras
This script included the ability to use Bootstrap nav link mods in your menus through the WordPress menu UI. Disabled links, dropdown headers and dropdown dividers are supported. Additionally icon support is built-in for Glyphicons and Font Awesome (note: you will need to include the icon stylesheets or assets separately).
#### Icons
To add an Icon to your link simply enter Glyphicons or Font Awesome class names in the links **CSS Classes** field in the Menu UI and the walker class will do the rest. IE `glyphicons glyphicons-bullhorn` or `fa fa-arrow-left` or `fas fa-arrow-left`.
#### Icon-Only Items
To make an item appear with the icon only apply the bootstrap screen reader class `sr-only` to the item alongside any icon classnames. This will then hide only the text that would appear as the link text.
#### Disabled Links
To set a disabled link simply add `disabled` to the **CSS Classes** field in the Menu UI and the walker class will do the rest. _Note: In addition to adding the .disabled class this will change the link `href` to `#` as well so that it is not a follow-able link._
#### Dropdown Headers, Dropdown Dividers & Dropdown Item Text
Headers, dividers and text only items can be added within dropdowns by adding a Custom Link and adding either `dropdown-header`, `dropdown-divider` or `dropdown-item-text` into the **CSS Classes** input. _Note: This will remove the `href` on the item and change it to either a `<span>` for headers or a `<div>` for dividers._
### Missing Edit Shortcut in Customizer Preview
According to the documentation for [`wp_nav_menu()`](https://developer.wordpress.org/reference/functions/wp_nav_menu/) one has to provide an instance of the custom walker class in order to apply the custom walker to the menu. As the instance is not [JSON serializable](https://make.wordpress.org/core/2015/07/29/fast-previewing-changes-to-menus-in-the-customizer/) this will cause the menu edit shortcut to not appear in the Customizer preview. To fix this do the following:
1. Provide the class name string instead of the class instance as value for the 'walker' key in the array of wp_nav_menu's arguments,
```diff
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 2, // 1 = no dropdowns, 2 = with dropdowns.
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'navbar-nav mr-auto',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
- 'walker' => new WP_Bootstrap_Navwalker(),
+ 'walker' => 'WP_Bootstrap_Navwalker',
) );
```
2. re-add the class instance by adding this filter to your `functions.php`
```php
function slug_provide_walker_instance( $args ) {
if ( isset( $args['walker'] ) && is_string( $args['walker'] ) && class_exists( $args['walker'] ) ) {
$args['walker'] = new $args['walker'];
}
return $args;
}
add_filter( 'wp_nav_menu_args', 'slug_provide_walker_instance', 1001 );
```
## Changelog
Please see the [Changelog](https://github.com/wp-bootstrap/wp-bootstrap-navwalker/blob/master/CHANGELOG.md).
================================================
FILE: bin/install-wp-tests.sh
================================================
#!/usr/bin/env bash
if [ $# -lt 3 ]; then
echo "usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version] [skip-database-creation]"
exit 1
fi
DB_NAME=$1
DB_USER=$2
DB_PASS=$3
DB_HOST=${4-localhost}
WP_VERSION=${5-latest}
SKIP_DB_CREATE=${6-false}
WP_TESTS_DIR=${WP_TESTS_DIR-/tmp/wordpress-tests-lib}
WP_CORE_DIR=${WP_CORE_DIR-/tmp/wordpress/}
download() {
if [ `which curl` ]; then
curl -s "$1" > "$2";
elif [ `which wget` ]; then
wget -nv -O "$2" "$1"
fi
}
if [[ $WP_VERSION =~ [0-9]+\.[0-9]+(\.[0-9]+)? ]]; then
WP_TESTS_TAG="tags/$WP_VERSION"
elif [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
WP_TESTS_TAG="trunk"
else
# http serves a single offer, whereas https serves multiple. we only want one
download http://api.wordpress.org/core/version-check/1.7/ /tmp/wp-latest.json
grep '[0-9]+\.[0-9]+(\.[0-9]+)?' /tmp/wp-latest.json
LATEST_VERSION=$(grep -o '"version":"[^"]*' /tmp/wp-latest.json | sed 's/"version":"//')
if [[ -z "$LATEST_VERSION" ]]; then
echo "Latest WordPress version could not be found"
exit 1
fi
WP_TESTS_TAG="tags/$LATEST_VERSION"
fi
set -ex
install_wp() {
if [ -d $WP_CORE_DIR ]; then
return;
fi
mkdir -p $WP_CORE_DIR
if [[ $WP_VERSION == 'nightly' || $WP_VERSION == 'trunk' ]]; then
mkdir -p /tmp/wordpress-nightly
download https://wordpress.org/nightly-builds/wordpress-latest.zip /tmp/wordpress-nightly/wordpress-nightly.zip
unzip -q /tmp/wordpress-nightly/wordpress-nightly.zip -d /tmp/wordpress-nightly/
mv /tmp/wordpress-nightly/wordpress/* $WP_CORE_DIR
else
if [ $WP_VERSION == 'latest' ]; then
local ARCHIVE_NAME='latest'
else
local ARCHIVE_NAME="wordpress-$WP_VERSION"
fi
download https://wordpress.org/${ARCHIVE_NAME}.tar.gz /tmp/wordpress.tar.gz
tar --strip-components=1 -zxmf /tmp/wordpress.tar.gz -C $WP_CORE_DIR
fi
download https://raw.github.com/markoheijnen/wp-mysqli/master/db.php $WP_CORE_DIR/wp-content/db.php
}
install_test_suite() {
# portable in-place argument for both GNU sed and Mac OSX sed
if [[ $(uname -s) == 'Darwin' ]]; then
local ioption='-i .bak'
else
local ioption='-i'
fi
# set up testing suite if it doesn't yet exist
if [ ! -d $WP_TESTS_DIR ]; then
# set up testing suite
mkdir -p $WP_TESTS_DIR
svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/includes/ $WP_TESTS_DIR/includes
svn co --quiet https://develop.svn.wordpress.org/${WP_TESTS_TAG}/tests/phpunit/data/ $WP_TESTS_DIR/data
fi
if [ ! -f wp-tests-config.php ]; then
download https://develop.svn.wordpress.org/${WP_TESTS_TAG}/wp-tests-config-sample.php "$WP_TESTS_DIR"/wp-tests-config.php
# remove all forward slashes in the end
WP_CORE_DIR=$(echo $WP_CORE_DIR | sed "s:/\+$::")
sed $ioption "s:dirname( __FILE__ ) . '/src/':'$WP_CORE_DIR/':" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/youremptytestdbnamehere/$DB_NAME/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/yourusernamehere/$DB_USER/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s/yourpasswordhere/$DB_PASS/" "$WP_TESTS_DIR"/wp-tests-config.php
sed $ioption "s|localhost|${DB_HOST}|" "$WP_TESTS_DIR"/wp-tests-config.php
fi
}
install_db() {
if [ ${SKIP_DB_CREATE} = "true" ]; then
return 0
fi
# parse DB_HOST for port or socket references
local PARTS=(${DB_HOST//\:/ })
local DB_HOSTNAME=${PARTS[0]};
local DB_SOCK_OR_PORT=${PARTS[1]};
local EXTRA=""
if ! [ -z $DB_HOSTNAME ] ; then
if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then
EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp"
elif ! [ -z $DB_SOCK_OR_PORT ] ; then
EXTRA=" --socket=$DB_SOCK_OR_PORT"
elif ! [ -z $DB_HOSTNAME ] ; then
EXTRA=" --host=$DB_HOSTNAME --protocol=tcp"
fi
fi
# create database
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
}
install_wp
install_test_suite
install_db
================================================
FILE: class-wp-bootstrap-navwalker.php
================================================
<?php
/**
* WP Bootstrap Navwalker
*
* @package WP-Bootstrap-Navwalker
*
* @wordpress-plugin
* Plugin Name: WP Bootstrap Navwalker
* Plugin URI: https://github.com/wp-bootstrap/wp-bootstrap-navwalker
* Description: A custom WordPress nav walker class to implement the Bootstrap 4 navigation style in a custom theme using the WordPress built in menu manager.
* Author: Edward McIntyre - @twittem, WP Bootstrap, William Patton - @pattonwebz, IanDelMar - @IanDelMar
* Version: 4.3.0
* Author URI: https://github.com/wp-bootstrap
* GitHub Plugin URI: https://github.com/wp-bootstrap/wp-bootstrap-navwalker
* GitHub Branch: master
* License: GPL-3.0+
* License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/
// Check if Class Exists.
if ( ! class_exists( 'WP_Bootstrap_Navwalker' ) ) :
/**
* WP_Bootstrap_Navwalker class.
*/
class WP_Bootstrap_Navwalker extends Walker_Nav_Menu {
/**
* Whether the items_wrap contains schema microdata or not.
*
* @since 4.2.0
* @var boolean
*/
private $has_schema = false;
/**
* Ensure the items_wrap argument contains microdata.
*
* @since 4.2.0
*/
public function __construct() {
if ( ! has_filter( 'wp_nav_menu_args', array( $this, 'add_schema_to_navbar_ul' ) ) ) {
add_filter( 'wp_nav_menu_args', array( $this, 'add_schema_to_navbar_ul' ) );
}
}
/**
* Starts the list before the elements are added.
*
* @since WP 3.0.0
*
* @see Walker_Nav_Menu::start_lvl()
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of menu item. Used for padding.
* @param WP_Nav_Menu_Args $args An object of wp_nav_menu() arguments.
*/
public function start_lvl( &$output, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
// Default class to add to the file.
$classes = array( 'dropdown-menu' );
/**
* Filters the CSS class(es) applied to a menu list element.
*
* @since WP 4.8.0
*
* @param array $classes The CSS classes that are applied to the menu `<ul>` element.
* @param stdClass $args An object of `wp_nav_menu()` arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = join( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/*
* The `.dropdown-menu` container needs to have a labelledby
* attribute which points to it's trigger link.
*
* Form a string for the labelledby attribute from the the latest
* link with an id that was added to the $output.
*/
$labelledby = '';
// Find all links with an id in the output.
preg_match_all( '/(<a.*?id=\"|\')(.*?)\"|\'.*?>/im', $output, $matches );
// With pointer at end of array check if we got an ID match.
if ( end( $matches[2] ) ) {
// Build a string to use as aria-labelledby.
$labelledby = 'aria-labelledby="' . esc_attr( end( $matches[2] ) ) . '"';
}
$output .= "{$n}{$indent}<ul$class_names $labelledby>{$n}";
}
/**
* Starts the element output.
*
* @since WP 3.0.0
* @since WP 4.4.0 The {@see 'nav_menu_item_args'} filter was added.
*
* @see Walker_Nav_Menu::start_el()
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Nav_Menu_Item $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param WP_Nav_Menu_Args $args An object of wp_nav_menu() arguments.
* @param int $id Current item ID.
*/
public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = ( $depth ) ? str_repeat( $t, $depth ) : '';
if ( false !== strpos( $args->items_wrap, 'itemscope' ) && false === $this->has_schema ) {
$this->has_schema = true;
$args->link_before = '<span itemprop="name">' . $args->link_before;
$args->link_after .= '</span>';
}
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
// Updating the CSS classes of a menu item in the WordPress Customizer preview results in all classes defined
// in that particular input box to come in as one big class string.
$split_on_spaces = function ( $class ) {
return preg_split( '/\s+/', $class );
};
$classes = $this->flatten( array_map( $split_on_spaces, $classes ) );
/*
* Initialize some holder variables to store specially handled item
* wrappers and icons.
*/
$linkmod_classes = array();
$icon_classes = array();
/*
* Get an updated $classes array without linkmod or icon classes.
*
* NOTE: linkmod and icon class arrays are passed by reference and
* are maybe modified before being used later in this function.
*/
$classes = $this->separate_linkmods_and_icons_from_classes( $classes, $linkmod_classes, $icon_classes, $depth );
// Join any icon classes plucked from $classes into a string.
$icon_class_string = join( ' ', $icon_classes );
/**
* Filters the arguments for a single nav menu item.
*
* @since WP 4.4.0
*
* @param WP_Nav_Menu_Args $args An object of wp_nav_menu() arguments.
* @param WP_Nav_Menu_Item $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
*
* @var WP_Nav_Menu_Args
*/
$args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );
// Add .dropdown or .active classes where they are needed.
if ( $this->has_children ) {
$classes[] = 'dropdown';
}
if ( in_array( 'current-menu-item', $classes, true ) || in_array( 'current-menu-parent', $classes, true ) ) {
$classes[] = 'active';
}
// Add some additional default classes to the item.
$classes[] = 'menu-item-' . $item->ID;
$classes[] = 'nav-item';
// Allow filtering the classes.
$classes = apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth );
// Form a string of classes in format: class="class_names".
$class_names = join( ' ', $classes );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filters the ID applied to a menu item's list item element.
*
* @since WP 3.0.1
* @since WP 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_id The ID that is applied to the menu item's `<li>` element.
* @param WP_Nav_Menu_Item $item The current menu item.
* @param WP_Nav_Menu_Args $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li ' . $id . $class_names . '>';
// Initialize array for holding the $atts for the link item.
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
if ( '_blank' === $item->target && empty( $item->xfn ) ) {
$atts['rel'] = 'noopener noreferrer';
} else {
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
}
// If the item has_children add atts to <a>.
if ( $this->has_children && 0 === $depth ) {
$atts['href'] = '#';
$atts['data-toggle'] = 'dropdown';
$atts['aria-expanded'] = 'false';
$atts['class'] = 'dropdown-toggle nav-link';
$atts['id'] = 'menu-item-dropdown-' . $item->ID;
} else {
if ( true === $this->has_schema ) {
$atts['itemprop'] = 'url';
}
$atts['href'] = ! empty( $item->url ) ? $item->url : '#';
// For items in dropdowns use .dropdown-item instead of .nav-link.
if ( $depth > 0 ) {
$atts['class'] = 'dropdown-item';
} else {
$atts['class'] = 'nav-link';
}
}
$atts['aria-current'] = $item->current ? 'page' : '';
// Update atts of this item based on any custom linkmod classes.
$atts = $this->update_atts_for_linkmod_type( $atts, $linkmod_classes );
// Allow filtering of the $atts array before using it.
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
// Build a string of html containing all the atts for the item.
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
// Set a typeflag to easily test if this is a linkmod or not.
$linkmod_type = $this->get_linkmod_type( $linkmod_classes );
// START appending the internal item contents to the output.
$item_output = isset( $args->before ) ? $args->before : '';
/*
* This is the start of the internal nav item. Depending on what
* kind of linkmod we have we may need different wrapper elements.
*/
if ( '' !== $linkmod_type ) {
// Is linkmod, output the required element opener.
$item_output .= $this->linkmod_element_open( $linkmod_type, $attributes );
} else {
// With no link mod type set this must be a standard <a> tag.
$item_output .= '<a' . $attributes . '>';
}
/*
* Initiate empty icon var, then if we have a string containing any
* icon classes form the icon markup with an <i> element. This is
* output inside of the item before the $title (the link text).
*/
$icon_html = '';
if ( ! empty( $icon_class_string ) ) {
// Append an <i> with the icon classes to what is output before links.
$icon_html = '<i class="' . esc_attr( $icon_class_string ) . '" aria-hidden="true"></i> ';
}
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $item->title, $item->ID );
/**
* Filters a menu item's title.
*
* @since WP 4.4.0
*
* @param string $title The menu item's title.
* @param WP_Nav_Menu_Item $item The current menu item.
* @param WP_Nav_Menu_Args $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );
// If the .sr-only class was set apply to the nav items text only.
if ( in_array( 'sr-only', $linkmod_classes, true ) ) {
$title = $this->wrap_for_screen_reader( $title );
$keys_to_unset = array_keys( $linkmod_classes, 'sr-only', true );
foreach ( $keys_to_unset as $k ) {
unset( $linkmod_classes[ $k ] );
}
}
// Put the item contents into $output.
$item_output .= isset( $args->link_before ) ? $args->link_before . $icon_html . $title . $args->link_after : '';
/*
* This is the end of the internal nav item. We need to close the
* correct element depending on the type of link or link mod.
*/
if ( '' !== $linkmod_type ) {
// Is linkmod, output the required closing element.
$item_output .= $this->linkmod_element_close( $linkmod_type );
} else {
// With no link mod type set this must be a standard <a> tag.
$item_output .= '</a>';
}
$item_output .= isset( $args->after ) ? $args->after : '';
// END appending the internal item contents to the output.
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
/**
* Menu fallback.
*
* If this function is assigned to the wp_nav_menu's fallback_cb variable
* and a menu has not been assigned to the theme location in the WordPress
* menu manager the function will display nothing to a non-logged in user,
* and will add a link to the WordPress menu manager if logged in as an admin.
*
* @param array $args passed from the wp_nav_menu function.
* @return string|void String when echo is false.
*/
public static function fallback( $args ) {
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
// Initialize var to store fallback html.
$fallback_output = '';
// Menu container opening tag.
$show_container = false;
if ( $args['container'] ) {
/**
* Filters the list of HTML tags that are valid for use as menu containers.
*
* @since WP 3.0.0
*
* @param array $tags The acceptable HTML tags for use as menu containers.
* Default is array containing 'div' and 'nav'.
*/
$allowed_tags = apply_filters( 'wp_nav_menu_container_allowedtags', array( 'div', 'nav' ) );
if ( is_string( $args['container'] ) && in_array( $args['container'], $allowed_tags, true ) ) {
$show_container = true;
$class = $args['container_class'] ? ' class="menu-fallback-container ' . esc_attr( $args['container_class'] ) . '"' : ' class="menu-fallback-container"';
$id = $args['container_id'] ? ' id="' . esc_attr( $args['container_id'] ) . '"' : '';
$fallback_output .= '<' . $args['container'] . $id . $class . '>';
}
}
// The fallback menu.
$class = $args['menu_class'] ? ' class="menu-fallback-menu ' . esc_attr( $args['menu_class'] ) . '"' : ' class="menu-fallback-menu"';
$id = $args['menu_id'] ? ' id="' . esc_attr( $args['menu_id'] ) . '"' : '';
$fallback_output .= '<ul' . $id . $class . '>';
$fallback_output .= '<li class="nav-item"><a href="' . esc_url( admin_url( 'nav-menus.php' ) ) . '" class="nav-link" title="' . esc_attr__( 'Add a menu', 'wp-bootstrap-navwalker' ) . '">' . esc_html__( 'Add a menu', 'wp-bootstrap-navwalker' ) . '</a></li>';
$fallback_output .= '</ul>';
// Menu container closing tag.
if ( $show_container ) {
$fallback_output .= '</' . $args['container'] . '>';
}
// if $args has 'echo' key and it's true echo, otherwise return.
if ( array_key_exists( 'echo', $args ) && $args['echo'] ) {
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo $fallback_output;
} else {
return $fallback_output;
}
}
/**
* Filter to ensure the items_Wrap argument contains microdata.
*
* @since 4.2.0
*
* @param array $args The nav instance arguments.
* @return array $args The altered nav instance arguments.
*/
public function add_schema_to_navbar_ul( $args ) {
if ( isset( $args['items_wrap'] ) ) {
$wrap = $args['items_wrap'];
if ( strpos( $wrap, 'SiteNavigationElement' ) === false ) {
$args['items_wrap'] = preg_replace( '/(>).*>?\%3\$s/', ' itemscope itemtype="http://www.schema.org/SiteNavigationElement"$0', $wrap );
}
}
return $args;
}
/**
* Find any custom linkmod or icon classes and store in their holder
* arrays then remove them from the main classes array.
*
* Supported linkmods: .disabled, .dropdown-header, .dropdown-divider, .sr-only
* Supported iconsets: Font Awesome 4/5, Glypicons
*
* NOTE: This accepts the linkmod and icon arrays by reference.
*
* @since 4.0.0
*
* @param array $classes an array of classes currently assigned to the item.
* @param array $linkmod_classes an array to hold linkmod classes.
* @param array $icon_classes an array to hold icon classes.
* @param integer $depth an integer holding current depth level.
*
* @return array $classes a maybe modified array of classnames.
*/
private function separate_linkmods_and_icons_from_classes( $classes, &$linkmod_classes, &$icon_classes, $depth ) {
// Loop through $classes array to find linkmod or icon classes.
foreach ( $classes as $key => $class ) {
/*
* If any special classes are found, store the class in it's
* holder array and and unset the item from $classes.
*/
if ( preg_match( '/^disabled|^sr-only/i', $class ) ) {
// Test for .disabled or .sr-only classes.
$linkmod_classes[] = $class;
unset( $classes[ $key ] );
} elseif ( preg_match( '/^dropdown-header|^dropdown-divider|^dropdown-item-text/i', $class ) && $depth > 0 ) {
/*
* Test for .dropdown-header or .dropdown-divider and a
* depth greater than 0 - IE inside a dropdown.
*/
$linkmod_classes[] = $class;
unset( $classes[ $key ] );
} elseif ( preg_match( '/^fa-(\S*)?|^fa(s|r|l|b)?(\s?)?$/i', $class ) ) {
// Font Awesome.
$icon_classes[] = $class;
unset( $classes[ $key ] );
} elseif ( preg_match( '/^glyphicon-(\S*)?|^glyphicon(\s?)$/i', $class ) ) {
// Glyphicons.
$icon_classes[] = $class;
unset( $classes[ $key ] );
}
}
return $classes;
}
/**
* Return a string containing a linkmod type and update $atts array
* accordingly depending on the decided.
*
* @since 4.0.0
*
* @param array $linkmod_classes array of any link modifier classes.
*
* @return string empty for default, a linkmod type string otherwise.
*/
private function get_linkmod_type( $linkmod_classes = array() ) {
$linkmod_type = '';
// Loop through array of linkmod classes to handle their $atts.
if ( ! empty( $linkmod_classes ) ) {
foreach ( $linkmod_classes as $link_class ) {
if ( ! empty( $link_class ) ) {
// Check for special class types and set a flag for them.
if ( 'dropdown-header' === $link_class ) {
$linkmod_type = 'dropdown-header';
} elseif ( 'dropdown-divider' === $link_class ) {
$linkmod_type = 'dropdown-divider';
} elseif ( 'dropdown-item-text' === $link_class ) {
$linkmod_type = 'dropdown-item-text';
}
}
}
}
return $linkmod_type;
}
/**
* Update the attributes of a nav item depending on the limkmod classes.
*
* @since 4.0.0
*
* @param array $atts array of atts for the current link in nav item.
* @param array $linkmod_classes an array of classes that modify link or nav item behaviors or displays.
*
* @return array maybe updated array of attributes for item.
*/
private function update_atts_for_linkmod_type( $atts = array(), $linkmod_classes = array() ) {
if ( ! empty( $linkmod_classes ) ) {
foreach ( $linkmod_classes as $link_class ) {
if ( ! empty( $link_class ) ) {
/*
* Update $atts with a space and the extra classname
* so long as it's not a sr-only class.
*/
if ( 'sr-only' !== $link_class ) {
$atts['class'] .= ' ' . esc_attr( $link_class );
}
// Check for special class types we need additional handling for.
if ( 'disabled' === $link_class ) {
// Convert link to '#' and unset open targets.
$atts['href'] = '#';
unset( $atts['target'] );
} elseif ( 'dropdown-header' === $link_class || 'dropdown-divider' === $link_class || 'dropdown-item-text' === $link_class ) {
// Store a type flag and unset href and target.
unset( $atts['href'] );
unset( $atts['target'] );
}
}
}
}
return $atts;
}
/**
* Wraps the passed text in a screen reader only class.
*
* @since 4.0.0
*
* @param string $text the string of text to be wrapped in a screen reader class.
* @return string the string wrapped in a span with the class.
*/
private function wrap_for_screen_reader( $text = '' ) {
if ( $text ) {
$text = '<span class="sr-only">' . $text . '</span>';
}
return $text;
}
/**
* Returns the correct opening element and attributes for a linkmod.
*
* @since 4.0.0
*
* @param string $linkmod_type a sting containing a linkmod type flag.
* @param string $attributes a string of attributes to add to the element.
*
* @return string a string with the openign tag for the element with attribibutes added.
*/
private function linkmod_element_open( $linkmod_type, $attributes = '' ) {
$output = '';
if ( 'dropdown-item-text' === $linkmod_type ) {
$output .= '<span class="dropdown-item-text"' . $attributes . '>';
} elseif ( 'dropdown-header' === $linkmod_type ) {
/*
* For a header use a span with the .h6 class instead of a real
* header tag so that it doesn't confuse screen readers.
*/
$output .= '<span class="dropdown-header h6"' . $attributes . '>';
} elseif ( 'dropdown-divider' === $linkmod_type ) {
// This is a divider.
$output .= '<div class="dropdown-divider"' . $attributes . '>';
}
return $output;
}
/**
* Return the correct closing tag for the linkmod element.
*
* @since 4.0.0
*
* @param string $linkmod_type a string containing a special linkmod type.
*
* @return string a string with the closing tag for this linkmod type.
*/
private function linkmod_element_close( $linkmod_type ) {
$output = '';
if ( 'dropdown-header' === $linkmod_type || 'dropdown-item-text' === $linkmod_type ) {
/*
* For a header use a span with the .h6 class instead of a real
* header tag so that it doesn't confuse screen readers.
*/
$output .= '</span>';
} elseif ( 'dropdown-divider' === $linkmod_type ) {
// This is a divider.
$output .= '</div>';
}
return $output;
}
/**
* Flattens a multidimensional array to a simple array.
*
* @param array $array a multidimensional array.
*
* @return array a simple array
*/
public function flatten( $array ) {
$result = array();
foreach ( $array as $element ) {
if ( is_array( $element ) ) {
array_push( $result, ...$this->flatten( $element ) );
} else {
$result[] = $element;
}
}
return $result;
}
}
endif;
================================================
FILE: composer.json
================================================
{
"name": "wp-bootstrap/wp-bootstrap-navwalker",
"description": "A custom WordPress nav walker class to fully implement the Bootstrap 4 navigation style in a custom theme using the WordPress built in menu manager.",
"type": "library",
"license": "GPL-3.0+",
"authors": [
{
"name": "Brandon Hubbard"
},
{
"name": "William Patton",
"email": "will@pattonwebz.com"
}
],
"support": {
"issues": "https://github.com/wp-bootstrap/wp-bootstrap-navwalker/issues/",
"source": "https://github.com/wp-bootstrap/wp-bootstrap-navwalker/"
},
"require": {
"composer/installers": "~1.0",
"php": "^5.5 || ^7.0"
},
"require-dev": {
"stevegrunwell/wp-enforcer": "^0.5.0"
},
"archive": {
"exclude": ["/.*", "/composer.lock"]
},
"scripts": {
"post-install-cmd": [
"wp-enforcer"
],
"post-update-cmd": [
"wp-enforcer"
]
}
}
================================================
FILE: phpcs.xml.dist
================================================
<?xml version="1.0"?>
<ruleset name="WordPress Coding Standards for Plugins">
<description>Generally-applicable sniffs for WordPress plugins</description>
<rule ref="WordPress-Core"/>
<rule ref="WordPress-Docs"/>
<file>./class-wp-bootstrap-navwalker.php</file>
<file>./tests/</file>
</ruleset>
================================================
FILE: phpstan.neon.dist
================================================
includes:
- phar://phpstan.phar/conf/bleedingEdge.neon
- vendor/szepeviktor/phpstan-wordpress/extension.neon
parameters:
level: 6
inferPrivatePropertyTypeFromConstructor: true
checkMissingIterableValueType: false
paths:
- class-wp-bootstrap-navwalker.php
scanFiles:
- tests/phpstan/class-wp-nav-menu-args.php
- tests/phpstan/class-wp-nav-menu-item.php
- class-wp-bootstrap-navwalker.php
ignoreErrors:
# Uses func_get_args()
- '#^Function apply_filters(_ref_array)? invoked with [34567] parameters, 2 required\.$#'
# False item type in core.
-
message: "#^Parameter \\#2 \\$item \\(WP_Nav_Menu_Item\\) of method WP_Bootstrap_Navwalker\\:\\:start_el\\(\\) should be compatible with parameter \\$item \\(WP_Post\\) of method Walker_Nav_Menu\\:\\:start_el\\(\\)$#"
path: class-wp-bootstrap-navwalker.php
# $output passed by reference.
-
message: '#^Method WP_Bootstrap_Navwalker::(start_lvl|start_el)\(\) has no return typehint specified\.$#'
path: class-wp-bootstrap-navwalker.php
# Uncertain properties.
-
message: '#^Property WP_Nav_Menu_Args::\$\S+ \(string\) in isset\(\) is not nullable\.$#'
path: class-wp-bootstrap-navwalker.php
================================================
FILE: phpunit.xml.dist
================================================
<phpunit
bootstrap="tests/bootstrap.php"
backupGlobals="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<testsuites>
<testsuite>
<directory prefix="test-" suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
================================================
FILE: tests/bootstrap.php
================================================
<?php
/**
* PHPUnit bootstrap file
*
* @package Wp_Bootstrap_Navwalker
*/
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir = '/tmp/wordpress-tests-lib';
}
// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
* Manually load the plugin being tested.
*/
function _manually_load_plugin() {
require dirname( dirname( __FILE__ ) ) . '/class-wp-bootstrap-navwalker.php';
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
// Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
================================================
FILE: tests/phpstan/class-wp-nav-menu-args.php
================================================
<?php
/**
* Data object for displaying navigation menu.
* Created to aid static analysis.
*
* @package WordPress
* @see wp_nav_menu()
*/
/**
* Nav menu arguments.
*/
class WP_Nav_Menu_Args {
/**
* Desired menu. Accepts a menu ID, slug, name, or object. Default empty.
*
* @var int|string|\WP_Term
*/
public $menu;
/**
* CSS class to use for the ul element which forms the menu. Default 'menu'.
*
* @var string
*/
public $menu_class;
/**
* The ID that is applied to the ul element which forms the menu.
* Default is the menu slug, incremented.
*
* @var string
*/
public $menu_id;
/**
* Whether to wrap the ul, and what to wrap it with. Default 'div'.
*
* @var string
*/
public $container;
/**
* Class that is applied to the container. Default 'menu-{menu slug}-container'.
*
* @var string
*/
public $container_class;
/**
* The ID that is applied to the container. Default empty.
*
* @var string
*/
public $container_id;
/**
* The aria-label attribute that is applied to the container
* when it's a nav element. Default empty.
*
* @var string
*/
public $container_aria_label;
/**
* If the menu doesn't exists, a callback function will fire.
* Default is 'wp_page_menu'. Set to false for no fallback.
*
* @var callable|bool
*/
public $fallback_cb;
/**
* Text before the link markup. Default empty.
*
* @var string
*/
public $before;
/**
* Text after the link markup. Default empty.
*
* @var string
*/
public $after;
/**
* Text before the link text. Default empty.
*
* @var string
*/
public $link_before;
/**
* Text after the link text. Default empty.
*
* @var string
*/
public $link_after;
/**
* Whether to echo the menu or return it. Default true.
*
* @var bool
*/
public $echo;
/**
* How many levels of the hierarchy are to be included. 0 means all.
* Default 0.
*
* @var int
*/
public $depth;
/**
* Instance of a custom walker class. Default empty.
*
* @var \Walker_Nav_Menu
*/
public $walker;
/**
* Theme location to be used. Must be registered with register_nav_menu()
* in order to be selectable by the user.
*
* @var string
*/
public $theme_location;
/**
* How the list items should be wrapped. Default is a ul with an id and class.
* Uses printf() format with numbered placeholders.
*
* @var string
*/
public $items_wrap;
/**
* Whether to preserve whitespace within the menu's HTML. Accepts 'preserve' or 'discard'.
* Default 'preserve'.
*
* @var string
*/
public $item_spacing;
}
================================================
FILE: tests/phpstan/class-wp-nav-menu-item.php
================================================
<?php
/**
* Value object for nav menu item objects.
*
* Created to aid static analysis by PHPStan.
*
* @package WordPress
* @see wp_setup_nav_menu_item()
*/
/**
* Decorates a menu item (WP_Post) object with the shared navigation menu item properties.
*/
class WP_Nav_Menu_Item {
/**
* The term_id if the menu item represents a taxonomy term.
*
* @overrides WP_Post
* @var int
*/
public $ID;
/**
* The title attribute of the link element for this menu item.
*
* @var string
*/
public $attr_title;
/**
* The array of class attribute values for the link element of this menu item.
*
* @var array
*/
public $classes;
/**
* The DB ID of this item as a nav_menu_item object, if it exists (0 if it doesn't exist).
*
* @var int
*/
public $db_id;
/**
* The description of this menu item.
*
* @var string
*/
public $description;
/**
* The DB ID of the nav_menu_item that is this item's menu parent, if any. 0 otherwise.
*
* @var int
*/
public $menu_item_parent;
/**
* The type of object originally represented, such as "category," "post", or "attachment."
*
* @var string
*/
public $object;
/**
* The DB ID of the original object this menu item represents,
* e.g. ID for posts and term_id for categories.
*
* @var int
*/
public $object_id;
/**
* The DB ID of the original object's parent object, if any (0 otherwise).
*
* @overrides WP_Post
* @var int
*/
public $post_parent;
/**
* A "no title" label if menu item represents a post that lacks a title.
*
* @overrides WP_Post
* @var string
*/
public $post_title;
/**
* The target attribute of the link element for this menu item.
*
* @var string
*/
public $target;
/**
* The title of this menu item.
*
* @var string
*/
public $title;
/**
* The family of objects originally represented, such as "post_type" or "taxonomy."
*
* @var string
*/
public $type;
/**
* The singular label used to describe this type of menu item.
*
* @var string
*/
public $type_label;
/**
* The URL to which this menu item points.
*
* @var string
*/
public $url;
/**
* The XFN relationship expressed in the link of this menu item.
*
* @var string
*/
public $xfn;
/**
* Whether the menu item represents an object that no longer exists.
*
* @var bool
*/
public $_invalid; // phpcs:ignore PSR2.Classes.PropertyDeclaration.Underscore
/**
* Whether the menu item represents the active menu item.
*
* @var bool
*/
public $current;
/**
* Whether the menu item represents an parent menu item.
*
* @var bool
*/
public $current_item_parent;
/**
* Whether the menu item represents an ancestor menu item.
*
* @var bool
*/
public $current_item_ancestor;
/* Copy of WP_Post */
/**
* ID of post author.
*
* A numeric string, for compatibility reasons.
*
* @var string
*/
public $post_author = 0;
/**
* The post's local publication time.
*
* @var string
*/
public $post_date = '0000-00-00 00:00:00';
/**
* The post's GMT publication time.
*
* @var string
*/
public $post_date_gmt = '0000-00-00 00:00:00';
/**
* The post's content.
*
* @var string
*/
public $post_content = '';
/**
* The post's excerpt.
*
* @var string
*/
public $post_excerpt = '';
/**
* The post's status.
*
* @var string
*/
public $post_status = 'publish';
/**
* Whether comments are allowed.
*
* @var string
*/
public $comment_status = 'open';
/**
* Whether pings are allowed.
*
* @var string
*/
public $ping_status = 'open';
/**
* The post's password in plain text.
*
* @var string
*/
public $post_password = '';
/**
* The post's slug.
*
* @var string
*/
public $post_name = '';
/**
* URLs queued to be pinged.
*
* @var string
*/
public $to_ping = '';
/**
* URLs that have been pinged.
*
* @var string
*/
public $pinged = '';
/**
* The post's local modified time.
*
* @var string
*/
public $post_modified = '0000-00-00 00:00:00';
/**
* The post's GMT modified time.
*
* @var string
*/
public $post_modified_gmt = '0000-00-00 00:00:00';
/**
* A utility DB field for post content.
*
* @var string
*/
public $post_content_filtered = '';
/**
* The unique identifier for a post, not necessarily a URL, used as the feed GUID.
*
* @var string
*/
public $guid = '';
/**
* A field used for ordering posts.
*
* @var int
*/
public $menu_order = 0;
/**
* The post's type, like post or page.
*
* @var string
*/
public $post_type = 'post';
/**
* An attachment's mime type.
*
* @var string
*/
public $post_mime_type = '';
/**
* Cached comment count.
*
* A numeric string, for compatibility reasons.
*
* @var string
*/
public $comment_count = 0;
/**
* Stores the post object's sanitization level.
*
* Does not correspond to a DB field.
*
* @var string
*/
public $filter;
}
================================================
FILE: tests/test-navwalker.php
================================================
<?php
/**
* Class SampleTest
*
* @package Wp_Bootstrap_Navwalker
*
* phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_print_r -- used for returned failure messages to give some details.
*/
/**
* Test_WP_Bootstrap_NavWalker class.
*
* @extends WP_UnitTestCase
*/
class Test_WP_Bootstrap_NavWalker extends WP_UnitTestCase {
/**
* The setUp function.
*
* @access public
* @return void
*/
public function setUp() {
parent::setUp();
$this->walker = new WP_Bootstrap_Navwalker();
// this is a test array of valid values that the fallback method will accept.
$this->valid_sample_fallback_args = array(
'container' => 'div',
'container_id' => 'a_container_id',
'container_class' => 'a_container_class',
'menu_class' => 'a_menu_class',
'menu_id' => 'a_menu_id',
'echo' => true,
);
// array of the possible linkmod typeflags.
$this->valid_linkmod_typeflags = array(
'dropdown-header',
'dropdown-divider',
'dropdown-item-text',
);
// array of all possible linkmods, including the valid typeflags.
$this->valid_linkmod_classes = array_merge(
$this->valid_linkmod_typeflags,
array(
'disabled',
'sr-only',
)
);
// array of valid font-awesome icon class starters plus some randomly
// chosen icon classes and some variations of upper/lower case letters.
$this->some_fontawesome_classes = array(
'fa',
'fas',
'fab',
'far',
'fal',
'fa-android',
'fa-css3',
'fa-home',
'fa-bluetooth-b',
'fa-chess-rook',
'fA-home',
'Fa-HoMe',
'fa-HomE',
);
// array of valid glyphicon icon class starters plus some randomly
// chosen icon classes and some variations of upper/lower case letters.
$this->some_glyphicons_classes = array(
'glyphicon',
'glyphicon-asterisk',
'glyphicon-ok',
'glyphicon-file',
'glyphicon-hand-left',
'glyphicon-sd-video',
'glyphicon-subscript',
'glyphicon-grain',
'Glyphicon-file',
'Glyphicon-File',
'glyphicon-File',
'glYphiCon-fiLe',
);
}
/**
* Test NavWalker File Exists.
*
* @access public
* @return void
*/
public function test_navwalker_file_exists() {
$this->assertFileExists( 'class-wp-bootstrap-navwalker.php' );
}
/**
* Test Start LVL Function.
*
* @access public
* @return void
*/
public function test_startlvl_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'start_lvl' ),
'Class does not have method start_lvl.'
);
}
/**
* Test Start El Function.
*
* @access public
* @return void
*/
public function test_start_el_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'start_el' ),
'Class does not have method start_el.'
);
}
/**
* Test for Display Element.
*
* @access public
* @return void
*/
public function test_display_element_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'display_element' ),
'Class does not have method display_element.'
);
}
/**
* Test Fallback function exists.
*
* @access public
* @return void
*/
public function test_fallback_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'fallback' ),
'Class does not have method fallback.'
);
}
/**
* Test Fallback method output for logged out users.
*
* Expects that for logged out users both echo and return requests should
* produce empty strings.
*
* @access public
* @return void
*/
public function test_fallback_function_output_loggedout() {
// default is to echo reults, buffer.
ob_start();
WP_Bootstrap_Navwalker::fallback( $this->valid_sample_fallback_args );
$fallback_output_echo = ob_get_clean();
// empty string expected when not logged in.
$this->assertEmpty(
$fallback_output_echo,
'Fallback output for logged out user created a non-empty string in echo mode.'
);
// set 'echo' to false and request the markup returned.
$fallback_output_return = WP_Bootstrap_Navwalker::fallback(
array_merge(
$this->valid_sample_fallback_args,
array(
'echo' => false,
)
)
);
// return and echo should result in the same values (both empty).
$this->assertEquals(
$fallback_output_echo,
$fallback_output_return,
'Fallback output for logged out user created a non-empty string in return mode.'
);
}
/**
* Test Fallback method output for logged in users.
*
* Expects strings to be produced with html markup and that they match when
* requesting either a return or defaulting to echo.
*
* @access public
* @return void
*/
public function test_fallback_function_output_loggedin() {
// make an admin user and set it to be the current user.
$user_id = $this->factory->user->create( array( 'role' => 'administrator' ) );
wp_set_current_user( $user_id );
// default is to echo results, buffer.
ob_start();
WP_Bootstrap_Navwalker::fallback( $this->valid_sample_fallback_args );
$fallback_output_echo = ob_get_clean();
// rudimentary content test - confirm it opens a div with 2 expected
// values and ends by closing a div.
$match = ( preg_match( '/^(<div id="a_container_id" class="menu-fallback-container a_container_class">)(.*?)(<\/div>)$/', $fallback_output_echo ) ) ? true : false;
$this->assertTrue(
$match,
'Fallback method seems to create unexpected html for logged in users in echo mode.'
);
// set 'echo' to false and request the markup returned.
$fallback_output_return = WP_Bootstrap_Navwalker::fallback(
array_merge(
$this->valid_sample_fallback_args,
array(
'echo' => false,
)
)
);
// return and echo should both produce the same strings.
$this->assertEquals(
$fallback_output_echo,
$fallback_output_return,
'Fallback method seems to create unexpected html for logged in users in return mode.'
);
}
/**
* Test separate_linkmods_and_icons_from_classes Function exists.
*
* @access public
* @return void
*/
public function test_separate_linkmods_and_icons_from_classes_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'separate_linkmods_and_icons_from_classes' ),
'Class does not have method separate_linkmods_and_icons_from_classes.'
);
}
/**
* Test that the function catches a random assortment of glyphicon icon
* classes mixed with with regular classnames.
*
* @depends test_separate_linkmods_and_icons_from_classes_function_exists
*
* @access public
* @return void
*/
public function test_separate_linkmods_and_icons_from_classes_fontawesome() {
$wp_bootstrap_navwalker = $this->walker;
// since we're working with private methods we need to use a reflector.
$reflector = new ReflectionClass( 'WP_Bootstrap_Navwalker' );
// get a reflected method for the opener function and set to public.
$method_open = $reflector->getMethod( 'separate_linkmods_and_icons_from_classes' );
$method_open->setAccessible( true );
$icons_array = $this->some_fontawesome_classes;
$linkmod_classes = array();
$icon_classes = array();
$chars = range( 'a', 'z' );
$extra_classes = array();
// make 10 random valid classnames with legth of 8 chars (there should
// be no naming collisions here with this random string gen method).
for ( $i = 0; $i < 20; $i++ ) {
$string = '';
$length = mt_rand( 4, 10 );
for ( $j = 0; $j < $length; $j++ ) {
$string .= $chars[ mt_rand( 0, count( $chars ) - 1 ) ];
}
$extra_classes[] = $string;
}
// merge the valid icon classes with the extra classes and shuffle order.
$icons_array = array_merge( $icons_array, $extra_classes );
shuffle( $icons_array );
$returned_array = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $icons_array, &$linkmod_classes, &$icon_classes, 0 ) );
// linkmod_classes should be empty and returned_array should not.
$this->assertTrue( ( empty( $linkmod_classes ) && ! empty( $returned_array ) ) );
// icon_classes should no longer be empty.
$this->assertNotTrue( empty( $icon_classes ) );
// the number of items inside updated $icon_classes should match number of valids we started with.
$this->assertTrue( count( $this->some_fontawesome_classes ) === count( $icon_classes ), "Seems that glyphicons classes are not catptured properly... \nvalid: \n" . print_r( $this->some_fontawesome_classes, true ) . "\nreturned: \n" . print_r( $icon_classes, true ) );
// get the differences between the original classes and updated classes.
$icon_differences = array_diff( $this->some_fontawesome_classes, $icon_classes );
// should be no differences thus empty array, this being TRUE also means
// that text was exact match in the updated array vs the original.
$this->assertTrue( empty( $icon_differences ) );
}
/**
* Test that the function catches a random assortment of font awesome icon
* classes mixed with with regular classnames.
*
* @depends test_separate_linkmods_and_icons_from_classes_function_exists
*
* @access public
* @return void
*/
public function test_separate_linkmods_and_icons_from_classes_glyphicons() {
$wp_bootstrap_navwalker = $this->walker;
// since we're working with private methods we need to use a reflector.
$reflector = new ReflectionClass( 'WP_Bootstrap_Navwalker' );
// get a reflected method for the opener function and set to public.
$method_open = $reflector->getMethod( 'separate_linkmods_and_icons_from_classes' );
$method_open->setAccessible( true );
$icons_array = $this->some_glyphicons_classes;
$linkmod_classes = array();
$icon_classes = array();
$chars = range( 'a', 'z' );
$extra_classes = array();
// make 10 random valid classnames with legth of 8 chars (there should
// be no naming collisions here with this random string gen method).
for ( $i = 0; $i < 10; $i++ ) {
$string = '';
$length = mt_rand( 4, 10 );
for ( $j = 0; $j < $length; $j++ ) {
$string .= $chars[ mt_rand( 0, count( $chars ) - 1 ) ];
}
$extra_classes[] = $string;
}
// merge the valid icon classes with the extra classes and shuffle order.
$icons_array = array_merge( $icons_array, $extra_classes );
shuffle( $icons_array );
$returned_array = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $icons_array, &$linkmod_classes, &$icon_classes, 0 ) );
// linkmod_classes should be empty and returned_array should not.
$this->assertTrue( ( empty( $linkmod_classes ) && ! empty( $returned_array ) ) );
// icon_classes should no longer be empty.
$this->assertNotTrue( empty( $icon_classes ) );
// the number of items inside updated $icon_classes should match number of valids we started with.
$this->assertTrue( count( $this->some_glyphicons_classes ) === count( $icon_classes ), "Seems that glyphicons classes are not catptured properly... \nvalid: \n" . print_r( $this->some_glyphicons_classes, true ) . "\nreturned: \n" . print_r( $icon_classes, true ) );
// get the differences between the original classes and updated classes.
$icon_differences = array_diff( $this->some_glyphicons_classes, $icon_classes );
// should be no differences thus empty array, this being TRUE also means
// that text was exact match in the updated array vs the original.
$this->assertTrue( empty( $icon_differences ) );
}
/**
* Test that the function catches a random assortment of font awesome icon
* classes mixed with with regular classnames.
*
* @depends test_separate_linkmods_and_icons_from_classes_function_exists
*
* @access public
* @return void
*/
public function test_separate_linkmods_and_icons_from_classes_linkmods() {
$wp_bootstrap_navwalker = $this->walker;
// since we're working with private methods we need to use a reflector.
$reflector = new ReflectionClass( 'WP_Bootstrap_Navwalker' );
// get a reflected method for the opener function and set to public.
$method_open = $reflector->getMethod( 'separate_linkmods_and_icons_from_classes' );
$method_open->setAccessible( true );
$valid_linkmods = $this->valid_linkmod_classes;
$linkmod_classes = array();
$icon_classes = array();
$chars = range( 'a', 'z' );
$extra_classes = array();
// make 20 random valid classnames with legth of 4 to 10 chars. There
// should be no naming collisions here with this random string gen.
for ( $i = 0; $i < 10; $i++ ) {
$string = '';
$length = mt_rand( 4, 10 );
for ( $j = 0; $j < $length; $j++ ) {
$string .= $chars[ mt_rand( 0, count( $chars ) - 1 ) ];
}
$extra_classes[] = $string;
}
// merge the valid icon classes with the extra classes and shuffle order.
$linkmod_array = array_merge( $valid_linkmods, $extra_classes );
shuffle( $linkmod_array );
// NOTE: this is depth of 0 and meaning valid_linkmod_typeflags won't be captured.
$returned_array = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $linkmod_array, &$linkmod_classes, &$icon_classes, 0 ) );
// linkmod_classes should NOT be empty and returned_array should not.
$this->assertTrue( ( ! empty( $linkmod_classes ) && ! empty( $returned_array ) ) );
// icon_classes should be empty.
$this->assertTrue( empty( $icon_classes ) );
$num_of_items_left = count( $this->valid_linkmod_classes ) - count( $linkmod_classes ) - count( $this->valid_linkmod_typeflags );
// the number of items inside updated array should match [what we started with - minus the linkmods for inside dropdowns].
$this->assertNotTrue(
(bool) $num_of_items_left,
"Seems that the linkmod classes are not catptured properly when outside of dropdowns... \nvalid: \n" . print_r( $this->valid_linkmod_classes, true ) . "\nreturned: \n" . print_r( $linkmod_classes, true )
);
// get the differences between the original classes and updated classes.
$linkmod_differences = array_diff( $this->valid_linkmod_classes, $linkmod_classes, $this->valid_linkmod_typeflags );
// should be no differences thus empty array, this being TRUE also means
// that text was exact match in the updated array vs the original.
$this->assertTrue( empty( $linkmod_differences ) );
// repeat some of the above tests but this time with depth = 1 so that we catch classes intended for inside dropdowns.
$depth = 1;
$linkmod_classes_d = array();
$icon_classes_d = array();
$returned_array_d = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $linkmod_array, &$linkmod_classes_d, &$icon_classes_d, $depth ) );
$this->assertTrue( count( $this->valid_linkmod_classes ) === count( $linkmod_classes_d ), "Seems that the linkmod classes are not catptured properly when inside dropdowns... \nvalid: \n" . print_r( $this->valid_linkmod_classes, true ) . "\nreturned: \n" . print_r( $linkmod_classes, true ) );
$linkmod_differences_d = array_diff( $this->valid_linkmod_classes, $linkmod_classes_d );
$this->assertTrue( empty( $linkmod_differences_d ), 'There are differences between the matched classnames and the valid classnames.' );
}
/**
* Test that the function catches all possible linkmod classes, any icon
* classes and leaves the other classes as-is on the array.
*
* @depends test_separate_linkmods_and_icons_from_classes_function_exists
*
* @depends test_separate_linkmods_and_icons_from_classes_fontawesome
* @depends test_separate_linkmods_and_icons_from_classes_glyphicons
* @depends test_separate_linkmods_and_icons_from_classes_linkmods
*
* @access public
* @return void
*/
public function test_separate_linkmods_and_icons_from_classes_fulltest() {
$wp_bootstrap_navwalker = $this->walker;
// since we're working with private methods we need to use a reflector.
$reflector = new ReflectionClass( 'WP_Bootstrap_Navwalker' );
// get a reflected method for the opener function and set to public.
$method_open = $reflector->getMethod( 'separate_linkmods_and_icons_from_classes' );
$method_open->setAccessible( true );
$icons_array = array_merge( $this->some_fontawesome_classes, $this->some_glyphicons_classes );
$linkmod_array = $this->valid_linkmod_classes;
$linkmod_classes = array();
$icon_classes = array();
$chars = range( 'a', 'z' );
$extra_classes = array();
// make 1000 random valid classnames with legth of 8 chars (there should
// be no naming collisions here with this random string gen method).
for ( $i = 0; $i < 1000; $i++ ) {
$string = '';
$length = mt_rand( 4, 10 );
for ( $j = 0; $j < $length; $j++ ) {
$string .= $chars[ mt_rand( 0, count( $chars ) - 1 ) ];
}
$extra_classes[] = $string;
}
// merge the valid icon classes with valid linkmod classes and the extra classes then shuffle order.
$classname_array = array_merge( $icons_array, $linkmod_array, $extra_classes );
shuffle( $classname_array );
// need a depth of 1 to ensure that our linkmods classes for inside dropdowns are also captured.
$depth = 1;
$returned_array = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $classname_array, &$linkmod_classes, &$icon_classes, $depth ) );
// linkmod_classes NOT should be empty and returned_array should not.
$this->assertTrue( ( ! empty( $linkmod_classes ) && ! empty( $returned_array ) ), 'Either the linkmod array or the returned non matching classes array is empty when they shoud not be.' );
// starting arrays should no longer be empty.
$this->assertNotTrue( empty( $icon_classes ), 'Did not catch any icons.' );
$this->assertNotTrue( empty( $linkmod_classes ), 'Did not catch any linkmods.' );
// icons compair.
$this->assertTrue( count( $icons_array ) === count( $icon_classes ), "Seems that icon classes are not catptured properly... valid: \n" . print_r( $icons_array, true ) . "returned: \n" . print_r( $icon_classes, true ) );
$icon_differences = array_diff( $icons_array, $icon_classes );
$this->assertTrue( empty( $icon_differences ), 'Seems that we did not catch all of the icon classes.' );
// linkmod compair.
$this->assertTrue( count( $linkmod_array ) === count( $linkmod_classes ), "Seems that linkmod classes are not catptured properly... valid: \n" . print_r( $linkmod_array, true ) . "returned: \n" . print_r( $linkmod_classes, true ) );
$linkmod_differences = array_diff( $icons_array, $icon_classes );
$this->assertTrue( empty( $linkmod_differences ), 'Seems that we did not catch all of the linkmod classes.' );
// extra classes string matches checks.
$returned_differences = array_diff( $returned_array, $extra_classes );
$this->assertTrue( empty( $returned_differences ), 'The returned array minus the extra classes should be empty, likely some classes were missed or string malformation occured.' );
}
/**
* Test get_linkmod_type Function exists.
*
* @access public
* @return void
*/
public function test_get_linkmod_type_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'get_linkmod_type' ),
'Class does not have method get_linkmod_type.'
);
}
/**
* Test update_atts_for_linkmod_type Function exists.
*
* @access public
* @return void
*/
public function test_update_atts_for_linkmod_type_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'update_atts_for_linkmod_type' ),
'Class does not have method update_atts_for_linkmod_type.'
);
}
/**
* Test linkmod_element_open Function exists.
*
* @access public
* @return void
*/
public function test_linkmod_element_open_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'linkmod_element_open' ),
'Class does not have method linkmod_element_open.'
);
}
/**
* Test linkmod_element_close Function exists.
*
* @access public
* @return void
*/
public function test_linkmod_element_close_function_exists() {
$wp_bootstrap_navwalker = $this->walker;
$this->assertTrue(
method_exists( $wp_bootstrap_navwalker, 'linkmod_element_close' ),
'Class does not have method linkmod_element_close.'
);
}
/**
* Tests for valid markup being used as the opener and closer sections for
* some different linkmod types.
*
* @access public
* @return void
*/
public function test_linkmod_elements_open_and_close_successfully() {
$wp_bootstrap_navwalker = $this->walker;
// since we're working with private methods we need to use a reflector.
$reflector = new ReflectionClass( 'WP_Bootstrap_Navwalker' );
// get a reflected method for the opener function and set to public.
$method_open = $reflector->getMethod( 'linkmod_element_open' );
$method_open->setAccessible( true );
// test openers for headers and dividers.
$header_open = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $this->valid_linkmod_typeflags[0], 'stringOfAttributes' ) );
$this->assertNotEmpty( $header_open, 'Got empty string for opener of ' . $this->valid_linkmod_typeflags[0] );
$divider_open = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $this->valid_linkmod_typeflags[1], 'stringOfAttributes' ) );
$this->assertNotEmpty( $divider_open, 'Got empty string for opener of ' . $this->valid_linkmod_typeflags[1] );
$text_open = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( $this->valid_linkmod_typeflags[2], 'stringOfAttributes' ) );
$this->assertNotEmpty( $divider_open, 'Got empty string for opener of ' . $this->valid_linkmod_typeflags[2] );
// test that that an unknown linkmod type being passed results in no output.
$nonexistent_linkmod_type_open = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( 'nonexistentlinkmodtype', 'stringOfAttributes' ) );
$this->assertEmpty( $nonexistent_linkmod_type_open, 'Expected empty string when using non-existent linkmod type.' );
// get a reflected method for the closer function and set to public.
$method_close = $reflector->getMethod( 'linkmod_element_close' );
$method_close->setAccessible( true );
$header_close = $method_close->invokeArgs( $wp_bootstrap_navwalker, array( $this->valid_linkmod_typeflags[0] ) );
$this->assertNotEmpty( $header_close, 'Got empty string for closer of ' . $this->valid_linkmod_typeflags[0] );
$divider_close = $method_close->invokeArgs( $wp_bootstrap_navwalker, array( $this->valid_linkmod_typeflags[1] ) );
$this->assertNotEmpty( $divider_close, 'Got empty string for closer of ' . $this->valid_linkmod_typeflags[1] );
$text_close = $method_close->invokeArgs( $wp_bootstrap_navwalker, array( $this->valid_linkmod_typeflags[2] ) );
$this->assertNotEmpty( $divider_close, 'Got empty string for closer of ' . $this->valid_linkmod_typeflags[2] );
// test that that an unknown linkmod type being passed results in no output.
$nonexistent_linkmod_type_close = $method_open->invokeArgs( $wp_bootstrap_navwalker, array( 'nonexistentlinkmodtype' ) );
$this->assertEmpty( $nonexistent_linkmod_type_close, 'Expected empty string when using non-existent linkmod type.' );
// dropdown-header should be a span.
$this->assertRegExp(
'/^(<span(.*?)>)(.*?)(<\/span>)$/',
$header_open . $header_close,
'The opener and closer for ' . $this->valid_linkmod_typeflags[0] . ' does not seem to match expected elements.'
);
// dropdown-divider should be a div.
$this->assertRegExp(
'/^(<div(.*?)>)(.*?)(<\/div>)$/',
$divider_open . $divider_close,
'The opener and closer for ' . $this->valid_linkmod_typeflags[1] . ' does not seem to match expected elements.'
);
// dropdown-item-text should be a span.
$this->assertRegExp(
'/^(<span(.*?)>)(.*?)(<\/span>)$/',
$text_open . $text_close,
'The opener and closer for ' . $this->valid_linkmod_typeflags[2] . ' does not seem to match expected elements.'
);
}
}
gitextract_z5aidwga/
├── .codeclimate.yml
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── CONTRIBUTING.md
│ ├── ISSUE_TEMPLATE.md
│ └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── LICENSE.txt
├── README.md
├── bin/
│ └── install-wp-tests.sh
├── class-wp-bootstrap-navwalker.php
├── composer.json
├── phpcs.xml.dist
├── phpstan.neon.dist
├── phpunit.xml.dist
└── tests/
├── bootstrap.php
├── phpstan/
│ ├── class-wp-nav-menu-args.php
│ └── class-wp-nav-menu-item.php
└── test-navwalker.php
SYMBOL INDEX (35 symbols across 5 files)
FILE: class-wp-bootstrap-navwalker.php
class WP_Bootstrap_Navwalker (line 25) | class WP_Bootstrap_Navwalker extends Walker_Nav_Menu {
method __construct (line 40) | public function __construct() {
method start_lvl (line 57) | public function start_lvl( &$output, $depth = 0, $args = null ) {
method start_el (line 112) | public function start_el( &$output, $item, $depth = 0, $args = null, $...
method fallback (line 336) | public static function fallback( $args ) {
method add_schema_to_navbar_ul (line 393) | public function add_schema_to_navbar_ul( $args ) {
method separate_linkmods_and_icons_from_classes (line 421) | private function separate_linkmods_and_icons_from_classes( $classes, &...
method get_linkmod_type (line 463) | private function get_linkmod_type( $linkmod_classes = array() ) {
method update_atts_for_linkmod_type (line 494) | private function update_atts_for_linkmod_type( $atts = array(), $linkm...
method wrap_for_screen_reader (line 529) | private function wrap_for_screen_reader( $text = '' ) {
method linkmod_element_open (line 546) | private function linkmod_element_open( $linkmod_type, $attributes = ''...
method linkmod_element_close (line 572) | private function linkmod_element_close( $linkmod_type ) {
method flatten (line 594) | public function flatten( $array ) {
FILE: tests/bootstrap.php
function _manually_load_plugin (line 19) | function _manually_load_plugin() {
FILE: tests/phpstan/class-wp-nav-menu-args.php
class WP_Nav_Menu_Args (line 13) | class WP_Nav_Menu_Args {
FILE: tests/phpstan/class-wp-nav-menu-item.php
class WP_Nav_Menu_Item (line 14) | class WP_Nav_Menu_Item {
FILE: tests/test-navwalker.php
class Test_WP_Bootstrap_NavWalker (line 15) | class Test_WP_Bootstrap_NavWalker extends WP_UnitTestCase {
method setUp (line 22) | public function setUp() {
method test_navwalker_file_exists (line 97) | public function test_navwalker_file_exists() {
method test_startlvl_function_exists (line 107) | public function test_startlvl_function_exists() {
method test_start_el_function_exists (line 124) | public function test_start_el_function_exists() {
method test_display_element_function_exists (line 141) | public function test_display_element_function_exists() {
method test_fallback_function_exists (line 158) | public function test_fallback_function_exists() {
method test_fallback_function_output_loggedout (line 178) | public function test_fallback_function_output_loggedout() {
method test_fallback_function_output_loggedin (line 218) | public function test_fallback_function_output_loggedin() {
method test_separate_linkmods_and_icons_from_classes_function_exists (line 261) | public function test_separate_linkmods_and_icons_from_classes_function...
method test_separate_linkmods_and_icons_from_classes_fontawesome (line 281) | public function test_separate_linkmods_and_icons_from_classes_fontawes...
method test_separate_linkmods_and_icons_from_classes_glyphicons (line 335) | public function test_separate_linkmods_and_icons_from_classes_glyphico...
method test_separate_linkmods_and_icons_from_classes_linkmods (line 389) | public function test_separate_linkmods_and_icons_from_classes_linkmods...
method test_separate_linkmods_and_icons_from_classes_fulltest (line 464) | public function test_separate_linkmods_and_icons_from_classes_fulltest...
method test_get_linkmod_type_function_exists (line 524) | public function test_get_linkmod_type_function_exists() {
method test_update_atts_for_linkmod_type_function_exists (line 541) | public function test_update_atts_for_linkmod_type_function_exists() {
method test_linkmod_element_open_function_exists (line 558) | public function test_linkmod_element_open_function_exists() {
method test_linkmod_element_close_function_exists (line 575) | public function test_linkmod_element_close_function_exists() {
method test_linkmod_elements_open_and_close_successfully (line 593) | public function test_linkmod_elements_open_and_close_successfully() {
Condensed preview — 22 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (131K chars).
[
{
"path": ".codeclimate.yml",
"chars": 779,
"preview": "---\nversion: \"2\"\nplugins:\n duplication:\n enabled: true\n config:\n languages:\n - php\n fixme:\n enabled"
},
{
"path": ".editorconfig",
"chars": 432,
"preview": "# This file is for unifying the coding style for different editors and IDEs\n# editorconfig.org\n\n# WordPress Coding Stand"
},
{
"path": ".gitattributes",
"chars": 701,
"preview": "# Set the default behavior, in case people don't have core.autocrlf set.\n* text=auto\n\n# Explicitly declare text files th"
},
{
"path": ".github/CONTRIBUTING.md",
"chars": 1304,
"preview": "# Want to contribute?\n\nDid you know that you could be instrumental in making the WP Bootstrap NavWalker more robust? If "
},
{
"path": ".github/ISSUE_TEMPLATE.md",
"chars": 442,
"preview": "<!-- Thanks for contributing to WP Bootstrap NavWalker! Pick a clear title and proceed. -->\n\n#### Steps to reproduce the"
},
{
"path": ".github/PULL_REQUEST_TEMPLATE.md",
"chars": 204,
"preview": "Fixes #\n\n#### Changes proposed in this Pull Request:\n\n*\n\n#### Testing instructions:\n\n*\n\n<!-- Add the following only if t"
},
{
"path": ".gitignore",
"chars": 20,
"preview": "/vendor/\n/phpcs.xml\n"
},
{
"path": ".travis.yml",
"chars": 1544,
"preview": "language: php\n\nos:\n - linux\n\ndist: bionic\n\nphp:\n - 7.4\n - 7.3\n - 7.2\n - 7.1\n - nightly\n\nenv:\n - WP_VERSION=latest"
},
{
"path": "CHANGELOG.md",
"chars": 3876,
"preview": "#CHANGELOG\n\n## [4.3.0]\n- Added an `aria-current` item.\n- Added `.nav-item` for the `<li>` and `.nav-link` for the `<a>` "
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 3216,
"preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
},
{
"path": "LICENSE.txt",
"chars": 35148,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 13385,
"preview": "# WP Bootstrap Navwalker\n\n[;\ni"
},
{
"path": "tests/phpstan/class-wp-nav-menu-args.php",
"chars": 2607,
"preview": "<?php\n/**\n * Data object for displaying navigation menu.\n * Created to aid static analysis.\n *\n * @package WordPress\n * "
},
{
"path": "tests/phpstan/class-wp-nav-menu-item.php",
"chars": 5008,
"preview": "<?php\n/**\n * Value object for nav menu item objects.\n *\n * Created to aid static analysis by PHPStan.\n *\n * @package Wor"
},
{
"path": "tests/test-navwalker.php",
"chars": 24151,
"preview": "<?php\n/**\n * Class SampleTest\n *\n * @package Wp_Bootstrap_Navwalker\n *\n * phpcs:disable WordPress.PHP.DevelopmentFunctio"
}
]
About this extraction
This page contains the full source code of the twittem/wp-bootstrap-navwalker GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 22 files (119.6 KB), approximately 31.4k tokens, and a symbol index with 35 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.