Blog posts under the javascript tag https://webdevstudios.com/tags/javascript-2/ WordPress Design and Development Agency Mon, 15 Apr 2024 16:02:29 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the javascript tag https://webdevstudios.com/tags/javascript-2/ 32 32 58379230 Traditional Versus Headless WordPress https://webdevstudios.com/2024/03/14/traditional-versus-headless-wordpress/ https://webdevstudios.com/2024/03/14/traditional-versus-headless-wordpress/#comments Thu, 14 Mar 2024 16:00:53 +0000 https://webdevstudios.com/?p=27083 In the evolving landscape of web development, the choice between traditional WordPress and its headless counterpart represents a crucial crossroads for developers, content creators, and business owners alike. WebDevStudios helps you make the best choice by weighing the pros and cons of traditional and headless WordPress.

The post Traditional Versus Headless WordPress appeared first on WebDevStudios.

]]>
In the evolving web development landscape, the choice between traditional WordPress and its headless counterpart represents a crucial crossroads for developers, content creators, and business owners. With its all-in-one approach, Traditional WordPress has long been the go-to platform for easily creating, managing, and hosting websites, offering a user-friendly interface and a vast ecosystem of themes and plugins.

On the other hand, Headless WordPress emerges as a forward-thinking alternative, separating the frontend presentation layer from the backend content management system (CMS) and leveraging modern JavaScript frameworks to deliver faster, more secure, and highly customizable user experiences. WebDevStudios helps you make the best choice by weighing the pros and cons of each option and considering your project requirements, technical capabilities, and future objectives.

Traditional WordPress

This is a headless statue in a wooded area at night.Traditional WordPress operates as a monolithic system where the frontend (what users see) and the backend (where content is created and managed) are tightly integrated. This means that WordPress handles both content management and presentation.

Pros of Traditional WordPress:

  • User-Friendly CMS: WordPress is a user-friendly CMS that enables easy content management and organization, even for non-technical users.
  • Comprehensive Ecosystem: It boasts an extensive ecosystem of themes and plugins, allowing users to easily extend functionality and customize the design of their sites without needing to code.
  • Cost-Effectiveness: Traditional WordPress can be more cost-effective for small- to medium-sized projects. The availability of free and premium themes and plugins enables businesses to create a fully functional website with a lower initial investment than custom development.
  • SEO-Friendly: WordPress offers SEO features like customizable permalinks, easy content creation, and plugins such as Yoast SEO to optimize your site and content.
  • Large Community Support: With a massive global community of developers, designers, and users, finding help, tutorials, and forums to troubleshoot issues or learn new tricks is easier than ever.
  • Regular Updates and Improvements: WordPress is regularly updated with new features, security improvements, and bug fixes, helping sites stay current and secure.

Cons of Traditional WordPress:

  • Performance Concerns: Traditional WordPress sites can suffer from slower page load times, especially with shared hosting or when using numerous plugins and complex themes, affecting user experience and SEO rankings.
  • Security Vulnerabilities: Being the most popular CMS makes WordPress a prime target for hackers. Sites can be vulnerable to security breaches, especially if plugins and themes are not regularly updated or properly secured.
  • Plugin Dependency: Over-reliance on plugins for additional functionality can lead to a bloated website, causing performance issues and potential conflicts between plugins that can break site features or lead to security gaps.
  • Customization Limits: While WordPress is highly customizable through themes and plugins, there are limits to what can be achieved without custom coding. Traditional WordPress might require extensive custom development for highly customized or unique designs and functionality, which can mitigate its initial cost and ease-of-use advantages.
  • Scalability Issues: For very high-traffic sites, traditional WordPress architecture might struggle to keep up with the demand, especially in cheaper, shared hosting environments. Scaling might require moving to more sophisticated and expensive hosting solutions or optimizing the site extensively.
  • Maintenance Overhead: Regularly updating WordPress core, plugins, and themes is required. Neglecting updates can lead to security risks and performance issues, but applying updates without testing can break the site if there are compatibility issues.
  • Monolithic Architecture: In a monolithic architecture, the frontend and backend are tightly coupled, limiting flexibility and innovation on the frontend, especially if you’re looking to leverage the latest web technologies or create a highly interactive user experience.

Choosing Traditional WordPress involves weighing these pros and cons against your project’s requirements, resources, and long-term goals. For many, the ease of use, extensive support, and comprehensive ecosystem make Traditional WordPress an attractive choice, despite its drawbacks.

Headless WordPress

This is an image of a headless bust in front of a wall covered with vines.

Headless WordPress separates the backend (content management system) from the frontend (presentation layer). The frontend is typically built using modern JavaScript frameworks like React, Vue, Faust.js, Next.js, or Angular, and it communicates with the WordPress backend via the REST API or GraphQL.

Headless WordPress offers significant performance, security, and flexibility advantages. It also introduces complexity and potential challenges that must be carefully managed.

Organizations considering a headless approach should weigh these factors against their specific needs, technical capabilities, and long-term digital strategy to determine whether headless WordPress is the right choice. Exploring the headless WordPress approach further, we can outline additional pros and cons that highlight its distinct advantages and challenges compared to traditional WordPress setups:

Pros of Headless WordPress:

  • Frontend Flexibility: Decoupling the frontend from WordPress allows developers to use modern JavaScript frameworks like React, Vue, Faust.js, Next.js, or Angular, offering unparalleled flexibility to create highly interactive, dynamic user experiences that stand out.
  • Enhanced Performance: With the frontend separated, headless WordPress sites can leverage technologies like static site generators for faster page loads, improved SEO, and a better overall user experience. The ability to serve pre-rendered pages or single-page applications (SPAs) can significantly reduce load times.
  • Better Security: The headless approach inherently improves security by reducing the WordPress site’s exposure to the public internet. The attack surface is significantly smaller because there is no direct connection between the frontend and the CMS.
  • Scalability: Serving the frontend as static files or through a CDN can dramatically improve scalability, handling high-traffic loads more efficiently than traditional WordPress setups.
  • Future-Proofing: Adopting a headless architecture allows organizations to be more agile. As frontend technologies evolve, the presentation layer can be updated or completely revamped without overhauling the CMS, ensuring the website remains cutting-edge.
  • Omnichannel Publishing: Headless WordPress makes it easier to serve content across multiple platforms and devices (like mobile apps, IoT devices, and third-party websites) from a single content source, enhancing content reach and consistency.

Cons of Headless WordPress:

  • Complexity: Implementing a headless architecture requires a higher level of technical expertise. Developers need to be proficient in API integration, frontend frameworks, and possibly server-side rendering techniques, which increases complexity and, potentially, development costs.
  • Plugin Limitations: Many WordPress plugins are designed to work with the traditional frontend. In a headless setup, some plugins (especially those affecting the frontend) may not work as expected, requiring alternative solutions or custom development.
  • Increased Maintenance: While separating concerns can lead to better security and performance, it also means maintaining two separate systems (the WordPress backend and the frontend application), which can double the effort for updates, security patches, and troubleshooting.
  • SEO Challenges: Implementing SEO best practices can be more complex in a headless setup. Developers must ensure that meta tags, structured data, and other SEO essentials are properly managed on the frontend, as traditional WordPress SEO plugins may not directly influence the headless frontend.
  • Cost Considerations: The initial development cost for a Headless WordPress site can be higher due to the need for specialized development skills and potentially more complex hosting setups (e.g., separate hosting for the frontend and the CMS).
  • Content Preview Limitations: WordPress’ standard content preview feature may not work seamlessly in a headless environment, making it more challenging for content creators to preview their work in real-time in the context of the final site design.
  • Learning Curve for Content Teams: Content teams accustomed to the integrated WordPress editing experience may find the transition to a headless approach challenging, especially if custom solutions are required to bridge functionality gaps left by the decoupled frontend.

Is Headless WordPress Right for Your Website Project?

Choosing between traditional WordPress and Headless WordPress depends on your project’s specific needs, technical expertise, and long-term goals. Traditional WordPress is a great choice if you prioritize ease of use, a rich plugin ecosystem, and a quick setup. However, Headless WordPress might be better if your website strategy focuses on performance, security, and a highly customized user experience that leverages modern development practices. Each approach offers distinct advantages and challenges, so it is important to carefully consider the requirements before deciding.

Ideal Implementation for Headless WordPress

Setting up a Headless WordPress theme involves decoupling the frontend (the user interface) from the backend (where your content is stored and managed). This setup allows you to use WordPress as a CMS while deploying a modern frontend technology stack for a more responsive, secure, and scalable website. Here’s an ideal setup for a headless WordPress theme:

Backend: WordPress Setup

  • WordPress Installation: Start with a clean WordPress installation on your hosting provider. This will serve as the backend where you manage content.
  • REST API or GraphQL: WordPress comes with REST API out of the box, which you will use to fetch content from the backend. Alternatively, you can install plugins like WPGraphQL to use GraphQL, which can offer more efficient data loading.
  • Headless-specific Plugins: Install plugins that enhance WordPress’ headless capabilities. For instance, plugins for custom post types, custom fields (ACF, Meta Box), and authentication (JWT Authentication) can be very useful.
  • Security Enhancements: Since your WordPress site won’t serve the frontend, you can enhance security by restricting access to the admin area and using security plugins to prevent unauthorized API access.

Frontend: Modern JavaScript Framework

  • Choose a Framework: Select a modern JavaScript framework or library for the frontend. Popular choices include React.js, Vue.js, Faust.js, Angular, or Next.js for headless projects.
  • Static Site Generators: For projects that don’t require dynamic content on every page, consider using static site generators like Gatsby (for React) or Nuxt.js (for Vue). These tools pre-build pages at deployment time, ensuring lightning-fast load times.
  • Hosting for the Frontend: Choose a hosting provider specializing in static sites and Jamstack (JavaScript, APIs, Markup) deployments if you’re going static. Netlify, Vercel, and AWS Amplify offer global CDNs, automatic HTTPS, and continuous deployment from Git.
  • API Requests: Implement API requests to fetch content from the WordPress backend. Depending on the setup, use Axios, Fetch API, or a GraphQL client like Apollo Client.
  • Dynamic Routing: Implement dynamic routing to handle WordPress’ diverse content types and structures. Doing so ensures the site can dynamically generate pages based on the content available in the CMS.
  • Development Environment: Set up a local development environment that mirrors the production setup as closely as possible. Tools like Docker help create isolated environments for WordPress and the frontend framework.
  • Security and Performance: Implement best practices for security, such as API key management. Do the same for performance, like lazy loading images, caching, and optimizing asset delivery.

Deployment and Continuous Integration

This is a headless statue during the daytime with a deep blue sky in the background.

  • Version Control: It is recommended that a version control system such as Git be used to manage the codebase effectively. This allows for better collaboration, tracking of changes, and code organization. Additionally, Git allows separate repositories for the WordPress theme and the frontend application if necessary.
  • Continuous Integration/Continuous Deployment (CI/CD): Set up CI/CD pipelines using tools like GitHub Actions or GitLab CI/CD. Automate testing, building, and deploying the frontend application to the hosting provider on every code push or pull request.
  • Monitoring and Analytics: Implement monitoring and analytics tools to track the performance and usage of the site. Google Analytics data is valuable for understanding user behavior and catching errors in production.

The ideal setup for a headless WordPress theme depends on the project’s specific requirements. Consider the complexity of the content, the performance and scalability needs, and the team’s expertise. Tailoring the setup to fit these requirements can help maximize the effectiveness of the headless WordPress implementation.

How do you know if headless is the right approach for your website project?  Reach out to us, and let’s talk about it.  You can also learn more about our Headless WordPress service.

The post Traditional Versus Headless WordPress appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2024/03/14/traditional-versus-headless-wordpress/feed/ 1 27083
Let’s Get Ready to Rumble! Composer vs npm https://webdevstudios.com/2020/09/03/composer-npm/ https://webdevstudios.com/2020/09/03/composer-npm/#respond Thu, 03 Sep 2020 16:00:20 +0000 https://webdevstudios.com/?p=22738 TL;DR? NPM 🥊 Composer 👊 npm install (libraries go in node_modules, executables in node_modules/.bin) composer install (libraries go in vendor, executables in vendor/bin) npm install --production composer install --no-dev npm install --package-lock-only composer update --lock npm install <package> composer require <package> npm install <package> --save-dev composer require --dev <package> npm install -g <package> composer global Read More Let’s Get Ready to Rumble! Composer vs npm

The post Let’s Get Ready to Rumble! Composer vs npm appeared first on WebDevStudios.

]]>
TL;DR?
NPM 🥊 Composer 👊
npm install (libraries go in node_modules, executables in node_modules/.bin) composer install (libraries go in vendor, executables in vendor/bin)
npm install --production composer install --no-dev
npm install --package-lock-only composer update --lock
npm install <package> composer require <package>
npm install <package> --save-dev composer require --dev <package>
npm install -g <package> composer global require <package>
npm update composer update
npm update <package> composer update <package>
npm outdated composer outdated
npm run <script-name> composer run-script <script-name>

The Complete Picture

As developers, we’re used to saying, “It works on my machine.” A decade ago, this phrase was reserved for snarky conversations with your friendly quality assurance person or the product owner who is testing a feature.

As our technology tooling has become more advanced (read: more complex), I’ve seen it come up as inter-developer conversation, frequently between a frontend and backend engineers:

Composer and Node package manager (npm) are the de-facto package managers for PHP and JavaScript. We use them every day at WebDevStudios. Let’s help each other get to know their similarities and their differences, as both tools can do unexpected things that you may not realize.

Init

While initializing a project isn’t the most common command, it’s useful to cover it first; in case you want to try to initialize a Composer or npm project in an empty directory.

$ composer init

Composer will interactively ask you some questions about your PHP project including: package name, description, package type, etc. Newer versions of Composer will prompt you to add the vendor directory to your .gitignore file. You should do this!

You can also just create your own composer.json file. Here’s an example minimal composer.json:

{
    "name": "webdevstudios/composer-vs-npm",
    "description": "php side of composer-vs-npm",
    "license": "GPL-3.0-or-later"
}

npm has the same command:

$ npm init

It will also interactively ask you a few questions about your JavaScript project including: package name, description, license, etc. After gathering this info, it will create a package.json file.

You can instead create a package.json file yourself. A minimal package.json is just {}, but npm will warn you if you don’t have these fields:

{
  "name": "@webdevstudios/composer-vs-npm",
  "description": "js side of composer-vs-npm",
  "license": "GPL-3.0-or-later",
  "repository": "https://github.com/WebDevStudios/composer-vs-npm"  
}

Init Best Practices

For the npm package name, it’s a good idea to add a scope using the @ symbol, your organization name, and a slash before the package name. While it’s not required like Composer’s vendor name, it will help group your packages together.

npm does not offer to create an entry in .gitignore for the node_modules directory, but you should.

You can validate your composer.json file format by running:

$ composer validate

I recommend not including version in your composer.json. It’s just one more thing that developers will forget or ignore. Let your version numbers be managed through tagging in your version control software.

npm requires a version entry in package.json only if you’re publishing your package. If you’re publishing your package, make sure keeping this up to date is part of your workflow. Otherwise, I suggest to omit it.

Both Composer and npm use the same license strings. A license entry is not strictly required, but both will print a warning, if you don’t include it.

Saving Dependencies

I’m getting a little ahead of myself because we’re going to talk about npm install before the Install section below, but just bear with me. In Composer land, telling it that your project relies on a library is done by requiring it.

$ composer require <vendor>/<name>

This will instruct Composer to add an entry to the require section of your composer.json file, install the package (usually in a vendor directory), and create and/or update a composer.lock file with info about the version it installed.

npm does the same thing, but with their install command:

$ npm install <package>

This will instruct npm to add an entry to the dependencies section of your package.json file, install the package (in a node_modulesdirectory), and create and/or update a package-lock.json file with info about the version it installed.

Saving Options

You may have PHP or JavaScript dependencies that are only needed for development, and aren’t needed to use your project when it’s deployed. You can specify that those packages are installed as development dependencies:

$ composer require --dev <vendor>/<name>
$ npm install <name> --save-dev

Both Composer and npm can require specific versions of a package:

$ composer require <vendor>/<name>:<version>
$ npm install <name>@<version>

If you omit the version number, they’ll both specify the latest stable version with a carat (^) pre-pended. If you require lodash via npm, it will specify "lodash": "^4.17.20" in your package.json file. This means if you were to tell npm to update Lodash, it would upgrade to newer versions up to the next major version—5.0.0. If you ever get unexpected results from version numbers, you can use these excellent semantic versioning (semver) tools to test:

Install

As the “Dad Joke Dog” meme explains above, the most common command to run is install.

$ composer install

Running this in a folder that has a composer.json file will instruct composer to read that file (along with composer.lock if present) and install any requirements specified.

If the composer.lock file is present, it will install the exact versions specified by that file, even if a newer version exists. If there’s no composer.lock file, composer will install the latest packages according to the version constraints in composer.json and create a composer.lock file with those versions.

Usually packages will go into a vendor directory, next to the composer.json file.

$ npm install

Running this in a folder that has a package.json file will instruct npm to read that file (along with package-lock.json if present) and install any requirements specified.

If the package-lock.json file is present, npm (similarly) will install the exact versions specified by that file, even if a newer version exists. If there’s no package-lock.json file, npm will install the latest packages according to the version constraints in package.json and create a package-lock.json file with the exact versions.

Installing without development dependencies

To install packages without the development dependencies, like you would for a production environment, run either of these commands:

$ composer install --no-dev
$ npm install --production

This will skip installing require-dev or devDependencies for Composer or npm (respectively).

Update

This is one of those sections where I like to ask:

Are you sure you want to do this?

$ composer update
$ npm update

I like to ask are you sure because when you don’t supply any arguments to update, Composer and npm have the potential to make a lot of changes that you may not have intended. Both will use the version constraints to update your specified dependencies (including dev dependencies) and it will update the child dependencies of the packages, too. So, if your version constraints are fairly “loose,” a lot of stuff is going to get updated, possibly some things you didn’t intend.

A more focused approach would be to upgrade one specific package, not all of them. Like this:

$ composer update composer/installers
$ npm update lodash

If you’re curious what is out of date, and what would be updated if you ran the update command without any arguments, you can run an outdated report instead:

$ composer outdated
$ npm outdated

Other useful commands

If you change something in your composer.json file that is unrelated to the version constraints—like reordering the required packages—Composer will complain that your composer.lock file is not up to date. To update just the content-hash part of the composer.lock file without updating any package versions, run:

$ composer update --lock

You can do the same thing with npm:

$ npm install --package-lock-only

Conclusion

As you can see, there are several commands that do the same thing and look the same in both Composer and npm. However, there are also commands that do the same thing but look very different.

It’s good to make sure you know what that command is going to do before you do it, so you don’t have to undo things you didn’t want to happen. 😬

Are there any other commands you use often that I missed? Let us know in the comments.

The post Let’s Get Ready to Rumble! Composer vs npm appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/09/03/composer-npm/feed/ 0 22738
A Better, Cleaner Way to Render HTML with JavaScript https://webdevstudios.com/2019/12/12/render-html-with-javascript/ https://webdevstudios.com/2019/12/12/render-html-with-javascript/#comments Thu, 12 Dec 2019 17:00:35 +0000 https://webdevstudios.com/?p=21492 As a team of WordPress developers, we often stumble upon a task where we need to request a set of data using AJAX and render it to the browser. Most of the the time we do it like this: View the code on Gist. It works. However, it’s difficult to maintain this code, and most Read More A Better, Cleaner Way to Render HTML with JavaScript

The post A Better, Cleaner Way to Render HTML with JavaScript appeared first on WebDevStudios.

]]>
As a team of WordPress developers, we often stumble upon a task where we need to request a set of data using AJAX and render it to the browser.

Most of the the time we do it like this:

View the code on Gist.

It works. However, it’s difficult to maintain this code, and most of the time, the HTML markup we need to use is much more complex than the example above. As more updates and changes occur in the markup, we find it increasingly difficult to work with this code.

Enter wp.template

If you are familiar with Underscore.js or {{ mustache }}, wp.template is an underscore-based JavaScript templating helper shipped with WordPress.

So, how do we use it?

Create and render your HTML markup template

View the code on Gist.

Just with this, we can immediately see how easy it is to maintain our HTML markup.

Notes

1. It is important that the HTML markup template is wrapped with <script type=“text/html” id=“tmpl-[TEMPLATE-NAME]”></script>.
2. The id needs to be prefixed with tmpl-.
3. data is the variable passed to the template from the JavaScript. You’ll see this shortly.
4. JavaScript logic goes inside <# #>.
5. <# _.forEach() #> is an Underscore function. See Underscore.js.
6. Use {{ }} for escaping output.
7. Use {{{ }}} for unescaped output. Using {{ }} with data containing markup will convert the tags to HTML entities. So for example, if the data is <img src=""/> and we indeed want to render the image, we need to use {{{ }}}.

Load wp-util

The code for wp.template is inside wp-util, so we need to make sure that wp-util.js is loaded.

You can do this by adding wp-util as a dependency of your JavaScript. Like this:
wp_enqueue_script( 'custom_js', plugins_url( 'js/custom.js', __FILE__ ), [ 'jquery', 'wp-util' ] );

The JavaScript

View the code on Gist.

A few more notes…

1. We omit tmpl- in wp.template( 'display-posts' ).
2. The data we pass to display_posts_template() is the data variable we use in our template.

Conclusion

While we used <# _.forEach() #> in our example, it is a good idea to minimize the JavaScript logic in your template. The goal is to separate the “view” and “logic.”

For example, you can approach our example like this:

JavaScript

View the code on Gist.

Template

View the code on Gist.

wp.template is a good tool to create clean and maintainable code. Another advantage of using this technique is you don’t need to modify your JavaScript when you modify your HTML template. As a developer, it means no re-compiling / bundling / minifying / purging of JavaScript cache is needed.

What do you think? Will these tips help you with a better, cleaner way to render HTML with JavaScript? Leave us a comment below. Need a team to offer up solutions like this for your website project? Contact us today.

The post A Better, Cleaner Way to Render HTML with JavaScript appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/12/12/render-html-with-javascript/feed/ 1 21492
Headless WordPress with React and NextJS (Part 1) https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/ https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/#comments Thu, 03 Jan 2019 17:30:57 +0000 https://webdevstudios.com/?p=19391 Editor’s Note: The following is Part 1 in a two-part series titled, “Headless WordPress with React and NextJS.” You can read Part 2 here. Keep in mind that this article was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current Read More Headless WordPress with React and NextJS (Part 1)

The post Headless WordPress with React and NextJS (Part 1) appeared first on WebDevStudios.

]]>
Editor’s Note: The following is Part 1 in a two-part series titled, “Headless WordPress with React and NextJS.” You can read Part 2 here. Keep in mind that this article was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current content on Headless CMS and Headless WordPress, click here. Visit the WebDevStudios GitHub to access our Next.js WordPress Starter.

A little disclaimer: I refer to some of the things below as “easy.” To clarify, none of this is “easy,” but relative to the alternatives they could be considered “easier.”

The future of web development is JavaScript. It’s only natural when you consider the advancements in technology, device speed, and general user desire for more of an all-around, app-like experience. Libraries like Vue.js and React, among others, are leading the charge. You might be thinking that this sounds great. Why aren’t we all doing this? Let’s make the internet better, faster… we have the technology.

A GIF image from the TV show "Six Billion Dollar Man," used for a blog post about Headless WordPress with React and NextJS.

Limitations

There are, as is the case with any new technology, limitations. Using JavaScript to build an app for something like a Google Chrome extension or an iPhone/Android or Desktop app is fairly simple all things, considered.

  1. You have an idea.
  2. You build the thing.
  3. You use something like Electron or React Native to get your project in the hands of users.

I say “fairly simple” because you don’t have to necessarily worry about things that are required for a website to exist and for Google or Bing to find it, index it, and validate it.

Currently, Google requires a website to render on the server side in order to crawl the site for content, images, etc., which a pure JavaScript application does not do out of the box—although admittedly, Google is making strides to accommodate JavaScript apps. Also required are metadata, descriptions, title, etc., which isn’t available in the framework by default. I’m of the opinion that reactive JavaScript technology never intended to be used to build a website and only ever expected to be used as an application.

The Benefits of Headless

Other limitations are time and money. We don’t always have the ability to completely rebuild a website infrastructure and database(s) from the ground up. In an ideal world, a clean slate would be the way to go, but for the website that’s been around for 10 years and only needs a face lift, you’re going to spend more time trying to clean up the database than it’s probably worth, truth be told.

Enter the “headlessness” of it all. A headless website means just that—unlike a WordPress website handling the content and site rendering, the database and backend are decoupled from the frontend. More simply, your data lives in one place; your website lives in another. This can be a fantastic way to use your existing website data with a brand new shiny JavaScript website on the frontend. Most web platforms have an API that can be used to access your website’s data, from there, it’s a matter of manipulating that data to your whim. WordPress, for example, has its own Rest API baked into the core which makes it easy to display posts and pages without much fuss.

Of course, downsides exist with a headless setup. Let’s talk WordPress: widgets, themes or settings inside the admin for modifying your website are now void. If you want that feature, you have to build your own thing. If you want access to a plugin or menu data and those don’t have an API endpoint already, you need to make one. Those devs on GitHub that came before offer solutions, or plugins, or code snippets to help you along, but you can say goodbye to a simple ready-to-launch website out of the box. This will now take work.

Is It Worth the time?

I would argue yes. It’s ultimately up to you. If you’re not getting a lot of website traffic, or the entirety of your website consists of four pages and five blog posts, then the answer is no. If you’re consistently looking to improve your ever-increasing site traffic, user experience, speed, and interactivity, then yes.

In either case, if you’re thinking about going headless and decoupling your website in favor of a more future-proof, app-like website, then you should work smart, plan everything, and know what you’re getting into. So, let’s get started.

The Setup

We’ll be building a super-simple decoupled headless website using WordPress and React. In building a website, we have a couple of requirements we need to meet before pressing forward.

  • Must be server-side rendered so that our website is relevant to Google
  • Needs to be able to route pages the same way we would on any other website
  • Needs to be efficient and pass Google Lighthouse testing

Anything else I realize up front, like SEO considerations, we will need to build. I’ll touch on that a little bit, but we’ll save that for another blog post.

Given these requirements of the project, I’ve decided to use WordPress as my decoupled backend CMS and React alongside Next.js to handle the frontend app, SSR, performance, and routing. It’ll be a bit of work, but the payoff will be more than worth it.

Let’s Get Started

First things first, you’ll need to set up a WordPress install either online or locally. You can do that fairly quickly using Local by Flywheel. I won’t get into details here, but there are many options for doing this and many hosting providers that allow you spin up a new WordPress website in a matter of minutes, like WP Engine, for example.

For our new app, we’ll make a new folder so that we can get everything running in a different location from our WordPress install. There are repos and frameworks out there that have been pre-built or pre-configured to handle all of this setup for you, but we’re going to walk through the app step-by-step so that we can fully understand what’s going on.

Let’s get started! Create a new folder and install everything we need and then jump into that folder:

$ mkdir nextjs
$ cd nextjs
$ npm init
$ npm install --save next react react-dom axios

After running those commands you should see a package.json, package-lock.json file, and a node_modules folder.

We’ll replace the test script with some simple scripts inside our package.json file to allow us to easily start our project and build our necessary files.

"scripts": {
    "dev": "next -p 8080",
  "build": "next build",
  "start": "next start -p 8080"
},

NOTE: The -p 8080 specifies that we’ll be using port 8080 instead of 3000 to make sure our app is secure.

At this point, we basically have everything we need to get started. In the next few steps, we’re going to set up our folder structure, set up routing, configure our API request to get posts, and finally toward the end, talk about dealing with metadata.

Folder Structure

Anything inside a pages directory will be treated as a page. Anything inside components will be treated as a component (a non-rendered element). So, let’s add both.

Similarly, although we won’t set this up today, the styles folder could be used to add and compile any new CSS, SCSS, Sass, or LESS files on the fly.

Inside pages let’s add an empty file named index.js which we’ll use as our entry point. At this point, let’s test things out and make sure they are working as expected. Inside that file, let’s add one line of code (longhand):

export default () => {
  return <h1>Your new server-side rendered React.js app!</h1>
}

From there, let’s run the command npm run dev that we added above and visit http://localhost:8080/. If all went well, we should see:

Excellent! Now, let’s move on.

Routing

We’re going to make this pretty simple and just shove everything into a single component for now. Inside our components folder, let’s add a new file and name it Navigation.js. Inside this file we’ll setup our routes. For now, we’ll just provide access to our homepage, our index.js file, and our page of posts that we’ve yet to create. Let’s do that now. Inside pages let’s add a new file called posts.js and add a similar bit of code to separate it from our index.js file.

export default () => {
    return
Our Posts Page!

}

We’ll change this up later, but for now, we’ll use this to make sure our routes are working once they’re set up.

Here’s the final result for our simple Navigation.js router.

import Link from 'next/link'

export default () => (
    <ul>
        <li><Link href="/"><a href="/">Home</a></Link></li>
        <li><Link href="/posts"><a href="/posts">Posts</a></Link></li>
    </ul>
)

We’ll import Link from next/link which is already baked into Next.js. It operates in much the same way that Link from react-router-dom would. We’ll wrap the <a href> in the Link component as directly adding a string to a Link was deprecated, so we avoid some errors here, although, omitting it would still technically work. This is pretty simple now, but we’ll get a little more complicated later on.

Now that that’s done, let’s go back to our index.js and posts.js files inside the pages directory and make some updates.

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
      <Navigation/>
      <h1>Your new server-side rendered React.js app!</h1>
  </Fragment>
)

and

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
    <Navigation/>
    <h1>Our Posts Page!</h1>
  </Fragment>
)

I like to use Fragment whenever I can to avoid unnecessary extra markup. The function only needs a wrapping parent element, but a div would work just fine.

We end up with something like this:

Not pretty, feel free to add some style objects to make that a bit nicer, but for now, it works, so we’ll go with it. If you’re still running your project via npm run dev you’ll find that if you click “Posts” you’ll see your posts page you created earlier:

Our URL is updated and our content is dynamically updated. This is a fairly simple use of routing and all we need to get things working. I’d suggest, however, to avoid having to call your Navigation component on every new page you make, look into the React Router Docs to see how you might be able to extend its functionality.

Let’s Get Our Data

So we’ve set up our simple app, we’re rending both server- and client-side and we’re routing, very simply. Before we can get into building our app further, we need to get our data from our WordPress install we set up at the top.

Now, I’m going to use a package called Axios to make API requests. React docs recommend using fetch, but I’m not a huge fan specifically since there are some compatibility issues and some extra steps involved in those requests. Axios has graceful fallbacks for older browsers and takes the guesswork out of making an API request. It makes things more, for lack of a better term, simple.

We’ll be making our API request inside the posts.js file we created.

First, I’ll import axios and react:

import axios from 'axios'
import React, { Component } from 'react'

If I were building a more complex website, I’d probably think about writing reusable functions for things like this, but for sake of clarity, I’m going to have each route make a request.

Next, I’m going to convert my default function into a class that extents React.component so that we can set our initial props (our API data) and render our component—the stuff we’ve already built.

import Navigation from '../components/Navigation'
import React, { Component, Fragment } from 'react'
import axios from 'axios'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps () {

    // Make request for posts.
    const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts')

    // Return response to posts object in props.
    return {
      posts: response.data
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Our Posts Page!</h1>
      </Fragment>
    )
  }
}

I’ve moved my original default function into the render function.

Let’s break down the API request.

// Resolve promise and set initial props.
static async getInitialProps () {

  // Make request for posts.
  const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts')

  // Return response to posts object in props.
  return {
    posts: response.data
  }
}

I need to make sure to make an async request, and resolve the promise we’ll get via axios and then assign that data value to a prop that we can access inside our render function.

We will then access that data inside our render function as this.props.posts. And we’ll use some JSX to output each post title into a list.

render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Our Posts Page!</h1>
        <ul>
          {
            this.props.posts.map( post => {
              return (
                <li key={ post.id }>{ post.title.rendered }</li>
              )
            })
          }
        </ul>
      </Fragment>
    )
 }

For now, we’ll just output a simple list of rendered titles and end up with something like this:

Fantastic! So let’s take a look at our final posts.js file:

import Navigation from '../components/Navigation'
import React, { Component, Fragment } from 'react'
import axios from 'axios'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps() {

    // Make request for posts.
    const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts' )

    // Return response to posts object in props.
    return {
      posts: response.data
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>hOur Posts Page!</h1>
        <ul>
          {
            this.props.posts.map( post => {
              return (
                <li key={ post.id }>{ post.title.rendered }</li>
              )
            })
          }
        </ul>
      </Fragment>
    )
  }
}

What’s Next?

From here, we’ve done what we aimed to. Headless application? Check. Server-side rendered? Check. Routing? Check. That said, what we’ve built really doesn’t provide a final product, something like what you would expect to see. You might, for example, expect to be able to click one of those posts and read the content or expect the title in the tab to change based on your route, or for the head description to change, or for any content that exists behind the scenes update as we navigate through our app.

We’ll take a look at that in Part 2.

The post Headless WordPress with React and NextJS (Part 1) appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/feed/ 12 19391
Advanced Custom Fields and Gutenberg https://webdevstudios.com/2018/12/11/advanced-custom-fields-and-gutenberg/ https://webdevstudios.com/2018/12/11/advanced-custom-fields-and-gutenberg/#comments Tue, 11 Dec 2018 17:00:36 +0000 https://webdevstudios.com/?p=19363 WordPress 5.0 ships with a new editor called Gutenberg. Here at WebDevStudios, we’re excited to build custom editorial solutions using Gutenberg and to see how the experience evolves from the classic editor. With that said, we’re huge fans of Advanced Custom Fields (ACF). It provides a robust set of field types that enables us to create Read More Advanced Custom Fields and Gutenberg

The post Advanced Custom Fields and Gutenberg appeared first on WebDevStudios.

]]>
WordPress 5.0 ships with a new editor called Gutenberg. Here at WebDevStudios, we’re excited to build custom editorial solutions using Gutenberg and to see how the experience evolves from the classic editor.

With that said, we’re huge fans of Advanced Custom Fields (ACF). It provides a robust set of field types that enables us to create flexible and friendly content management solutions for our clients. The time we save from writing, testing, and maintaining code with ACF makes it worth paying for an ACF PRO license. Our wd_s  starter theme includes commonly-used content blocks built on ACF.

ACF 5.8 has added support for Gutenberg. You can add ACF fields to a Gutenberg block without any JavaScript code. In this article, you will learn how to build a custom Gutenberg block for hero area using ACF without writing a single line of JavaScript code.

Adventurous, right?

ACF and Gutenberg

To build custom blocks using Gutenberg, you must be familiar with writing Modern JavaScript using the latest syntax (ES6, ES7, ES8, JSX), as well as creating components using React. To see this in action, here are some code examples to demonstrate a classic “Hello World” example for Gutenberg.

Custom Gutenberg Block with Vanilla JavaScript:

View the code on Gist.

Custom Gutenberg block with Modern JavaScript:

View the code on Gist.

The second example is smaller and cleaner but requires a build tool setup to compile Modern JavaScript syntax and JSX into browser supported code. You can get a head start by using create-gutenberg-block created by Ahmad Awais to scaffold a Gutenberg block without learning how to set up build tools.

Side Note: Learn JavaScript Deeply

Matt Mullenweg recommended that the WordPress community Learn JavaScript deeply in 2015. If you’re a frontend developer, this still applies—not only for Gutenberg but JavaScript frameworks like React, Angular, and Vue are now widely-adopted and in-demand. Here are some resources to level up your JavaScript skills:

Hero Block

You will be recreating a simpler version of the hero area that is included with wd_s. This is the end result of the custom Gutenberg block that you will create:

Requirements:

  1. Gutenberg (WordPress 5.0)
  2. Advanced Custom Fields PRO 5.8.0

Step 1: Register the Hero Block

ACF introduced acf_register_block function with 5.8, which you will be using to register a custom Gutenberg Hero Block.

The example below shows how to register the hero block. You can drop this function in the functions.php file of your theme.

View the code on Gist.

To learn more details about each parameter of the acf_register_block  function, visit the official documentation.

Step 2: ACF field group for Hero Block

A field group is a set of fields that can be assigned to a WordPress post, page, widget, etc., and now a custom Gutenberg blocks registered with acf_register_block.

Next, you’ll add a new field group for the Hero Block from the Custom Fields page.

The basic field requirements for this block are:

  • Tab field: Block Content
  • Title field
  • Text field
  • Button text field
  • Button URL field
  • Tab field: Background Options
  • Background image field

 

 

Next, assign the field group to the Hero Gutenberg Block.

To reiterate, Block is a new rule type in ACF which refers to all Gutenberg blocks registered with acf_register_block.

Save your changes!

This is how these fields will display in Gutenberg:

Step 3: Set up the Hero Block template

Custom Gutenberg Block created with ACF will use a template file to display it within the Gutenberg editor and on the frontend.

Create a template file template-parts/gutenberg/hero.php within your theme’s folder to match with render_template parameter of acf_register_block defined in Step 1.

The template file will contain HTML markup to add layout and return data from the fields.

View the code on Gist.

The get_field function from ACF is used to get data from the ACF fields.

The rest of the markup is basic HTML for setting up the Hero block’s layout. Just to appreciate the power of this feature by ACF, I want to point out that you didn’t have to write a single line of JavaScript. That’s amazing!

This is how the block looks within the Gutenberg editor:

Step 4: Styling the Hero Block template.

The final step is to style your Gutenberg Block.

To do this, you will be using the enqueue_block_assets action. This hook is used to enqueue assets for Gutenberg’s editor and frontend. If you want to have a separation between frontend and backend styling, you can use enqueue_block_editor_assets to enqueue assets only within the Gutenberg editor.

Drop the following code in your functions.php file to enqueue the stylesheet for your custom Gutenberg Hero Block:

View the code on Gist.

Create gutenberg.css in the root of your theme’s folder and drop the following code for styling the block:

View the code on Gist.

CSS is compiled from Sass.

This finishes your block setup with zero JavaScript code. Congratulations! This is how your Hero Block will look in the Gutenberg editor:

And this is how it will look on the frontend:

 

In my opinion, ACF provides a solid platform that fills the gap between PHP and JavaScript developers. ACF makes the whole Gutenberg Block creation process easier, faster and reliable. Even though I can foresee the limitation of ACF when a complex Gutenberg Block will come in action, I still appreciate and applaud ACF’s approach on making the whole process super simple for all level of developers.

Technically, acf_register_block is extremely powerful considering that a filter can be added to settings array to be used by other themes and plugins to make it even better (or worse).

The post Advanced Custom Fields and Gutenberg appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2018/12/11/advanced-custom-fields-and-gutenberg/feed/ 10 19363
Paths to Learning Web Development https://webdevstudios.com/2018/11/27/learning-web-development/ https://webdevstudios.com/2018/11/27/learning-web-development/#respond Tue, 27 Nov 2018 17:00:20 +0000 https://webdevstudios.com/?p=19504 Computer programming is a vast and complex field. For those interested in the ins and outs of engineering, determining a path to learning relevant information can seem incredibly daunting. Even once you narrow your focus to a particular area of the field, there is far more information out there than you can possibly master. Newcomers Read More Paths to Learning Web Development

The post Paths to Learning Web Development appeared first on WebDevStudios.

]]>
Computer programming is a vast and complex field. For those interested in the ins and outs of engineering, determining a path to learning relevant information can seem incredibly daunting. Even once you narrow your focus to a particular area of the field, there is far more information out there than you can possibly master. Newcomers frequently proclaim, “I don’t even know where to begin!”

This guide aims to provide direction and help you discover the right paths for learning web development.

The Circle of Knowledge

Before we begin, let’s discuss briefly what I like to call the Circle of Knowledge (aka, the generalized way in which I like to think about knowledge acquisition). Consider the following image:

The Circle of Knowledge: three layers containing topics you have never heard of in the outer ring, things you have heard about in the middle ring, and things you know in the innermost ring

For the purpose of this article, let’s assume you are interested in learning to build your first website. In the Circle of Knowledge, the outer edge broadly establishes the topic of Web Development. The inner circles define your level of familiarity with the general topic’s more specific subtopics. These interior circles divide your understanding of the larger topic into three sections: topics you know (or think you know), topics you have heard about, and topics you are unaware even exist.

Initially, the innermost circle is probably pretty small, because you’re just starting to dig into what you need to learn in order to understand web development. Maybe you know how to turn on a computer; you understand that something called a browser lets you access the internet (which you know some people also call the web); you can search for topics of interest, and parse the search results to determine which of those accurately represent the answers to your questions.

It may not seem like much, but this is a great starting point. You already have something in common with the vast majority of computer programmers in the world: if we don’t know something, we look it up.

Your First Search

Imagine you search for the phrase “how to build a website” and encounter the following results:

Web search results for how to build your own website

You just populated the middle segment of your Circle of Knowledge. Although you may not understand what they mean, terms like domain, hosting, Wix and eCommerce are now on your radar. Next, you click the link labeled How to Create a Website: Step-by-Step Guide for Beginners (2018) and are greeted with an additional set of terms: WordPress, content management system, HTML, CSS, Drupal, and so on.

Prior to each click, all of these terms occupied your outermost circle (topics you were unaware even existed), but through the process of research, one-by-one you are now moving them to the middle circle: topics you have heard about. This is excellent progress!

The process of learning anything—web development, baking, running for Congress—can be broken down into these steps. Beginning with just a single search, you will learn a whole new set of terms, notice patterns (domain and hosting came up multiple times in our initial search), and start piecing together the puzzle. The goal for your Circle of Knowledge is to grow the inner circle—the things you know—as much as possible. To do that, first you need to expand the middle segment by discovering new concepts, then selecting those on which to focus your efforts.

“That’s great, but where do I go from here?”

I’ll give you a head start: 100% of all websites are composed of HyperText Markup Language, more easily recognized by its initialism: HTML. This language defines the structure of a website’s content and indicates to your browser the differences between headings, sections, paragraphs, images, bulleted lists, numbered lists, and so on. Well-structured HTML is readable both by browsers and devices that assist web users with impaired vision. It’s the foundation of the internet. It’s also the most important language you can learn to write well at the beginning of your web development career.

Of course, websites are powered by more than just well-structured content. Some are beautifully designed. Some have extremely dynamic interactions, and others work like native computer applications. On occasion, you find a site that does it all.

While learning about HTML, you may find yourself asking some new questions:

  • “How can I make this look better?”
  • “Do I really need to create this navigation menu in every file?”
  • “Can I save information that I enter into a form?”
  • “Is my markup accessible?”

Once again, search is your friend; and by leveraging your research skills, you will learn new information. You will perhaps discover that CSS is responsible for the way a website looks. Languages like PHP let you to create reusable templates to split up distinct pieces of content such as navigation. Database languages such as MySQL allow you to save form data. And writing semantic markup goes a long way toward making your content accessible.

A photo image of a snowy road that forks into two different roads used for a blog post titled, "Paths to Learning Web Development."

The Fork in the Road

You will begin to see new learning paths as you continue to acquire more knowledge; and where there are paths, there are choices. Whether you care more about how a website looks and how users interact with it, or how a website saves and makes available its data, is going to inform your decision to pursue specified knowledge in those areas. We define a website’s look and collection of user interfaces as its “frontend,” and its data structures and application logic as its “backend.”

My friend and colleague, Justin Foell, previously published an article that asked whether you should first learn JavaScript or PHP. An alternate question might be, “Should I start by learning to build user interfaces or systems?” That is the primary difference between frontend and backend development.

Frontend Development

The frontend of a site comprises the publicly-visible content that regular visitors will see. As you’ve learned, HTML provides the structure for that content, but the responsibility for the visual appearance of that content belongs to Cascading Style Sheets, or CSS. Additionally, some behavior of your site that responds to user input, such as triggering a slideshow or using keyboard commands to trigger different settings, is written in a language called JavaScript. Developing a mastery of HTML, CSS, and JavaScript is essential to becoming a frontend web engineer.

Frontend Development: templates, presentation styles, animations, handling user interactions.

Resources

One of my favorite book series for an introduction to frontend development is Web Design with HTML, CSS, JavaScript, and jQuery Set, written by Jon Duckett. These books are a wonderful introduction to each of the three primary frontend languages, and they’re beautiful. too.

For CSS development, CSS Tricks has a great beginner’s guide for learning HTML and CSS. Once you have exhausted their collection of those articles, they have loads more about more general frontend development.

A Book Apart regularly publishes books about a variety of topics from renowned experts in the field. You might be interested in their Front-end Fundamentals series. Then shortly after, check out both the series on Responsive Design and Front-end Next Steps.

Smashing Magazine is another great general resource for frontend development. Smashing publishes loads of articles, tutorials, and books for free, and also offers memberships that provide deep discounts to that content. They also host several live events throughout the year.

Backend Development

The backend (sometimes called “server-side”) of a site typically consists of:

  1. a mechanism for storing data in a persistent fashion
  2. a collection of files that a web server understands

Data can be stored in files, but it’s more likely that you will be using a database instead. The open-source content management system WordPress uses a combination of MySQL (database language) and PHP (otherwise known as Pre-HyperText PHP, a server-side language) to dynamically generate HTML content.

Backend: databases, server-side languages, application logic, application programming interfaces.

If you’re interested in learning how to make a website dynamic, then we recommend you consider learning PHP immediately after you learn HTML.

PHP began as a templating language. As such, you can create HTML templates that use PHP to pull in your dynamic data. This makes it incredibly versatile for building your site’s structure, as you can separate reusable content like navigation menus into separate files. Thus, if that part of your site changes, it can be easily updated everywhere that part is used.

Of course, the true power of PHP is in application development. Because it’s a backend language, most of your PHP code won’t be outputting templates. Instead, it will be used to connect to data sources like a database or application programming interface to retrieve, manipulate, and update that data. Once you learn how to use PHP for templating, introducing a database to the mix and learning how to write queries is the next logical path.

Resources

There are, in my view, two definitive resources for learning PHP. First, PHP has a glorious online manual that will be your go-to resource any time you have questions. Second, PHP The Right Way is an online book that covers everything from templating to servers and deployment, so you can focus on an area of the language that’s right for your skill level.

Of course, in looking for other resources while researching this article, I just found out that Jon Duckett is publishing a new book about server-side development with PHP and MySQL. I don’t own this, but knowing how great the frontend series books are, I’m pre-ordering this today!

In my view, good online MySQL resources are a bit harder to come by, but sites like Lynda.com and Laracasts have some solid instructional videos, if you’re willing to pay for a subscription.

Still with me?

Good! That fork in the road is important, because your initial question, “How do I build a website?” will lead you down many paths. Some will be fulfilling, and some you’ll find are better left unexplored. They are left there for you to discover.

Earlier, I suggested that computer programming contains far more subtopics than any single person could possibly hope to learn. As a part of choosing your own path, you must continually ask yourself whether the information you are learning is necessary in helping you reach your personal goals. Only you can know that for sure.

A photo image of a person on a hiking path in the woods with some fog overhead.

Continuing Down a Path

Once you spend enough time learning front or backend development basics, you can no longer say you’ve heard of their languages. Instead, you can confidently say that you are proficient with them. Congratulations! You successfully moved one or more topics into the innermost section of your Circle of Knowledge: “topics you know.”

However, learning doesn’t stop because you are proficient. During the course of learning frontend development, you may discover other topics: CSS preprocessors like Sass or LESS, templating engines like Twig or Blade, or JavaScript frameworks like React, Vue, or Angular. Or, while learning backend development, you will hear about dependency management via Composer, unit testing with PHPUnit, or development practices like SOLID. In either path, you might find websites discussing version control, content management applications, responsive design, intrinsic web design, or a concept called “test driven development.”

Summing Up

Regardless of your path, bringing knowledge into your inner circle leads to new information, questions, and ways of thinking about a topic. At that point, it’s up to you to evaluate your own proficiency, level of interests, and next areas of focus. There are no right or wrong paths. Thankfully, there are some folks out there who have published suggested routes.

One such example is Kamran Ahmed’s “Developer Roadmap – 2018”, published on GitHub. Kamran offers recommended paths for both frontend and backend development. His paths are rich with information, but can seem overwhelming, if it’s the absolute first thing you look into. We recommend you start with the basics described above and revisit Kamran’s articles once you feel ready to learn more. Also, take note of new terms or information that come up during the process of learning. The frequency at which you see those terms will inform which topics to dig into next.

Be sure to check in with yourself regularly and evaluate whether or not you are learning topics that you enjoy. If so, great! You have discovered topics rich with new information that are right within your areas of interest. If not, that’s okay, too. There are some aspects of the field that are less thrilling but still important to know to attain long-term success. Sometimes, a topic is simply not for you. Depending how far along you are on your path, you may discover the path itself isn’t the right one. Evaluating your interest in the information you are learning goes a long way toward guiding your path.

Good luck!

The post Paths to Learning Web Development appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2018/11/27/learning-web-development/feed/ 0 19504
We’re Headed to the OC! https://webdevstudios.com/2017/06/08/were-headed-to-the-oc/ https://webdevstudios.com/2017/06/08/were-headed-to-the-oc/#respond Thu, 08 Jun 2017 16:00:34 +0000 https://webdevstudios.com/?p=17125 It’s already turning out to be one WordCamp-filled summer! And this weekend, WebDevStudios (WDS) is headed to the OC for WordCamp Orange County (WCOC), Saturday and Sunday, June 10-11. Not only does this educational WordPress event offer a bevy of informative sessions and workshops, including “How to Get Started with Building a Website for your Business” and Read More We’re Headed to the OC!

The post We’re Headed to the OC! appeared first on WebDevStudios.

]]>
It’s already turning out to be one WordCamp-filled summer! And this weekend, WebDevStudios (WDS) is headed to the OC for WordCamp Orange County (WCOC), Saturday and Sunday, June 10-11. Not only does this educational WordPress event offer a bevy of informative sessions and workshops, including “How to Get Started with Building a Website for your Business” and “Becoming a Better Blogger,” but this particular WordCamp also features plugin competition Plugin-A-Palooza. Our own Backend Developer, Russell Aaron, will be entering his self-developed plugin, Plugins Admin Bar, into the contest. Last year, Russ walked away with second place. Not too shabby, huh?

“Plugins Admin Bar is a simple plugin adding quick links to the WP-Admin bar, in order to get to the plugins screen,” Russell explains his plugin. “As of now, it takes two or three clicks to get to your plugins admin page, four clicks if you want to add a new plugin, and five if you want to add a new plugin and search. With Plugins Admin Bar, I’ve reduced those numbers down to two or three total.”

But as if that wasn’t enough, Russ is also speaking on plugin development during his discussion, “Best Practices for Plugin Building,” 2 p.m. on Saturday.

“There are many things to learn about building a plugin,” says Russell. “The WCOC session is an open discussion involving all parties present to contribute to my conversation and teach everyone in the audience. I think a more open discussion about plugin building can help others who are there to learn.”

Senior Frontend Developer, Carrie Forde, will also be presenting at WCOC. Her topic is “Using Component Libraries for Rapid Theme Development,” which takes place at 4:30 p.m. on Saturday, Venture track.

“I love atomic design and pattern libraries,” Carrie says, “And there is a real opportunity for increasing theming productivity using component libraries, which are heavily related to atomic design. I want to share what I know about component libraries, and how we can better work with them within the WordPress ecosystem.”

Carrie’s looking forward to connecting with WDS coworkers, making new friends, and attending some of the JavaScript (JS) workshops. She hopes to meet Zac Gordon in-person and possibly snagging a JavaScript for WordPress laptop sticker for her collection. (Carrie is in the process of completing Zac’s master course.)

“While I haven’t delved too deeply into any of the hot JS frameworks, I have been following the React vs. Vue.js debate, and I’m really interested in learning more about Vue in Jacob Arriola’s session,” says Carrie.

If you can’t make this WordCamp event, skip the FOMO and just follow the WCOC buzz on Twitter. Catch Carrie at her next presentation at WordCamp Sacramento. And keep up with where WDS will be next by visiting our WDS Gives Back page.

The post We’re Headed to the OC! appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/06/08/were-headed-to-the-oc/feed/ 0 17125
Level Up With jQuery Dimensions https://webdevstudios.com/2016/09/28/level-up-jquery-dimensions/ https://webdevstudios.com/2016/09/28/level-up-jquery-dimensions/#comments Wed, 28 Sep 2016 15:30:29 +0000 https://webdevstudios.com/?p=12873 It’s hard to believe that I’m well into my second year of being a front-end dev here at WDS. It has been an awesome experience and I’m truly blessed to work with such a great group of people. Halfway through 2015, I officially caught the bug known as Javascript and I started really trying to learn Read More Level Up With jQuery Dimensions

The post Level Up With jQuery Dimensions appeared first on WebDevStudios.

]]>
It’s hard to believe that I’m well into my second year of being a front-end dev here at WDS. It has been an awesome experience and I’m truly blessed to work with such a great group of people. Halfway through 2015, I officially caught the bug known as Javascript and I started really trying to learn the language. This inevitably also meant expanding my knowledge of jQuery.

As a quick aside, you might be asking, “jQuery in 2016? Really?” My answer to this is HECK yes. According to BuiltWith, 80% of the top 1 million websites use jQuery.

Learning Javascript is more of a marathon than a sprint.

It’s becoming more and more clear along the way there are concepts and techniques that will really go far in leveling my skill-set as a front-end developer. Two of these concepts are dimensions and offsets. For me, it’s not so much about implementing the code for these concepts but having an in-depth knowledge of their meaning.

It wasn’t until recently that I started experimenting with the real power of each concept. Use them in conjunction and you can do some pretty crazy DOM manipulation!

For this post, we will focus on dimensions and follow up with another post on offsets.

jQuery provides six functions that we can use to get the height and width of an element. Your first response might be why is there a need for six functions just to get the height and width of an element? The answer…the box model. Height and width can vary depending on if you are including padding, borders, and margins.

Let’s take a brief look at each function jQuery provides along with a quick explanation. Remember: Like other jQuery functions, these are both getters and setters. Passing in a value to the function makes them a setter.

Height

.height() – Will return the height of the content. In the image below, the content is the dark grey area.

.innerHeight() – Returns the height of the content + padding.

.outerHeight() – This will return the value of the content + padding + border.

.outerHeight( true ) – Returns the value of content + padding + border + margin.

height-c

Width

.width() – Returns the width of the content. The dark grey area in the image below.

.innerWidth() – Returns the width of the content + padding.

.outerWidth() – Returns the width of the content + padding + border.

.outerWidth( true ) – Returns the width of the content + padding + border + margin

width-c

How About a Use Case?

There have been many times when I’ve needed to transform a primary desktop menu into both a ‘tablet’ or ‘mobile’ menu depending on the width of the browser. You can make this happen seamlessly with a combination of CSS and jQuery. The approach is simple. Fire an event that will change the CSS appropriately and perform any other DOM manipulations when the browser size is above or below a certain breakpoint.

Here is a nifty little function that will do exactly what we need it to. (Thanks for Aubrey for this nice utility function.)

/**
 * Check if window width is equal or less than breakpoint
 * 
 * @param breakpoint Width to check against
 **/
function screenLessThan ( breakpoint ) {
    
    // Get the width of the current window
    var windowWidth = $( window ).width();

    // Return true/false if window with is equal or smaller than breakpoint
    // parseInt() is being used to ensure we are working with integers
    return ( parseInt( windowWidth ) <= parseInt( breakpoint ) );
}

We can leverage the function above to allow us to make certain changes based on the current size of the browser! In the gif below, we are making both the background color and text change based on breakpoints that the function above is checking against.

mobile tablet desktop

Checkout the CodePen below to view the full code. Also, feel free to let me know of ways this code could be optimized!

The Takeaway

Learning and understanding what each of these dimension functions do will level up your skill-set! I’d recommend taking a bit of time to play around with them by combining them with different events. Having familiarity with them is HUGE in my book.

The post Level Up With jQuery Dimensions appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/09/28/level-up-jquery-dimensions/feed/ 1 12873
Helpful Books for Front-End Developers https://webdevstudios.com/2016/07/05/books-for-front-end-developers/ https://webdevstudios.com/2016/07/05/books-for-front-end-developers/#respond Tue, 05 Jul 2016 16:49:46 +0000 https://webdevstudios.com/?p=13271 “Please, no matter how we advance technologically, please don’t abandon the book. There is nothing in our material world more beautiful than the book.” –Patti Smith There are many great pathways to glean new information out there, whether it be on the web or in a class. Your mileage may vary depending on your learning Read More Helpful Books for Front-End Developers

The post Helpful Books for Front-End Developers appeared first on WebDevStudios.

]]>

“Please, no matter how we advance technologically, please don’t abandon the book. There is nothing in our material world more beautiful than the book.” –Patti Smith

There are many great pathways to glean new information out there, whether it be on the web or in a class. Your mileage may vary depending on your learning style or the topic at hand. With the tech industry, evolution often occurs at a faster rate than print media can keep up.

Still, sometimes a good ol’ print version of what you need comes along that earns its place on your bookshelf. Maybe it got there after you heard it mentioned for the tenth time. Maybe it is the book you always find yourself lending out to someone when they want to dip their feet in to a new niche (regardless of the evolution of name-your-favourite-framework-here.js). Maybe it is the book that someone leant to you at a crucial step of your learning. There are brilliant books for front-end developers out there–and they are definitely worth looking over.

A single book won’t be able to provide you with the breadth of information necessary, especially with today’s multi-dimensional coding ecosystems. Often, books cite wonderfully curated online resources so you are able to use their foundation as a jumping off point for knowledge expansion.

The WordPress-specific

WebDevStudios is abundant with people who know more than a few things about WordPress–with a stack of books to their credit, no less! One book from this list is Professional WordPress: Design and Development, which starts from a top-level view on WordPress then digs down into all the nitty-gritty. Sure, I’m biased, but this is a wonderful additional to any WordPress developer’s bookshelf.

The Process

For those who want to know more about the principles of intuitive navigation and information design, Don’t Make Me Think: A Common Sense Approach to Web Usability, by Steve Krug, is an excellent straight-forward resource for both beginners and the more-seasoned on how people connect with interfaces. This is a good resource for management, designers, and developers alike.Print book covers displayed in line

The Visual

Are you more visually inclined? Jon Duckett’s books on HTML/CSS and JavaScript/jQuery may be a good fit. They each include code examples and there is a general assumption of little-to-no previous programming experience that make these a good beginner’s starting point and reference.

The Varied

Smashing Magazine offers many great resources and one compilation is Smashing Book 5: Real-Life Responsive Web Design. While responsive design is a default these days, this gathers techniques and strategies on everything from workflow to SVGs to debugging. (There is a level of assumed knowledge and experience in many chapters.)

The Non-Code Code Books
  • Code: The Hidden Language of Computer Hardware and Software: Starting with Morse Code and working its way linearly through telegraphs, barcodes and I/O devices, this isn’t going to teach you how to better implement code but you will likely have a new respect for the history behind the work you’re doing (Published in 2000, so don’t expect discussion of technologies beyond)
  • Quiet: The Power of Introverts in a World That Can’t Stop Talking: Okay, this one has truly nothing to do specifically with code. This book explores the dominant values of business culture and how the leadership potential of introverts is often overlooked.

What are some other must-reads that you have on your bookshelf?

The post Helpful Books for Front-End Developers appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/07/05/books-for-front-end-developers/feed/ 0 13271
Is Clever Code OK? https://webdevstudios.com/2016/05/17/is-clever-code-ok/ https://webdevstudios.com/2016/05/17/is-clever-code-ok/#respond Tue, 17 May 2016 15:53:22 +0000 https://webdevstudios.com/?p=12982 “Clever code” is a term that you may have heard before, accompanied by sighs and groans from other developers. Often, people seem to think of clever code as annoying, and perhaps even harmful. In this article, I’m going to give a brief overview of what clever code is, why it’s often avoided, and how it can Read More Is Clever Code OK?

The post Is Clever Code OK? appeared first on WebDevStudios.

]]>
“Clever code” is a term that you may have heard before, accompanied by sighs and groans from other developers. Often, people seem to think of clever code as annoying, and perhaps even harmful. In this article, I’m going to give a brief overview of what clever code is, why it’s often avoided, and how it can be turned into a learning experience.

What is “clever code?”

For most, clever code is code that does not immediately “explain” itself. What that means is that the average developer might see it and have to spend more than a few seconds reading the context around it to understand what it does. Here’s an example in PHP:

$foo = 'bar';
// snip
$value = $foo ?: false;

Considering I’ve been writing PHP for nearly sixteen years, I was bewildered when I first saw this in a co-worker’s code a few weeks ago.

“Pretty nifty, huh?”

You bet! I want to use that in the future, and it is a prime example of clever code–the slang of a programming language.

Opposition to clever code

If you’ve used clever code in the workplace, or in other projects where collaboration is a part of what you do, then you’ve probably run across a decent number of people who don’t like it. Some examples of feedback:

  • “So, why did you do it like this?”
  • “What am I looking at?”
  • “Don’t do that again.”

All very reasonable responses. Clever code is often cited as bringing a disadvantage beyond reading comprehension; it’s also viewed as a source of bugs. Implementing code that is harder to read means it’s more likely that you or a developer working in the same file later are more likely to not read the proper flow of the program. Here’s an example of using PHP’s Bitwise And operator:

// Bitwise And.
$foo = false;
$foo &= false;
$foo &= true;
$foo &= false;

var_dump( $foo ); // int(0)

$foo = false;
$foo &= false;
$foo &= true;

var_dump( $foo ); // int(0)

In the first example, you might expect the outcome of false, or “int(0)”. But the second example is a bit confusing–didn’t that end with setting $foo to true? The Bitwise And operator instead looks at both the left-hand value of “$foo” and the right-hand value when making its assignment; thus, if $foo is false even once, the equation will always look like “$foo = ( 0 * 1 = 0 = false ).” This can be extremely useful, but also incredibly confusing.

Another example of Bitwise confusion comes from the Javascript Bitwise NOT operator:

var a = ["f", "o", "o", "b", "a", "r" ];

if ( a.indexOf( "g" ) > -1 ) {
    console.log( "Typical style" );
}

if ( !!~a.indexOf( "g" ) ) {
    console.log( "Clever style" );
}

Again, we can see that the “tilde” operator, coupled with a double negative “!!”, creates clean code that won’t make sense to the average programmer.

How to be smart and clever

This all leads to what I’d like programmers to start doing when considering clever code: create a learning environment for other developers. I’ve seen clever solutions criticized on StackOverflow, and a particular question about it on the Programmer’s StackExchange asking for advice on how to avoid writing clever code in the first place. 

This, to me, is a great example of how programmers see clever code: it’s a party trick; it’s dangerous; it is to be avoided by “serious” programmers.

On the other hand, I think we can start to turn clever code into a learning experience. Once you recognize clever code, you can start to document it when you use it so others on the project know what you’re doing:

function check_user( $can_go_on ) {
    /**
     * NB, Clever: Using PHP's bitwise And operator.
     * See: http://php.net/manual/en/language.operators.bitwise.php
     */
    if ( ! current_user_can( 'manage_network' ) ) {
        $can_go_on &= false;
    }

    return $can_go_on;
}

function check_screen( $can_go_on ) {
    $screen = get_current_screen();

    if ( ! $screen || 'post' !== $screen->base ) {
        $can_go_on &= false;
    }

    return $can_go_on;
}

add_filter( 'can_we_continue', 'check_user' );
add_filter( 'can_we_continue', 'check_screen' );

$can_go_on = apply_filters( "can_we_continue", true );

In the above example, the ‘check_user’ function is documented to give a clear and distinct “Hey! I’m doing something weird here,” as opposed to the second method ‘check_screen’ which quietly uses the Bitwise And without any discussion. Most any programmer would be forgiven for missing it or thinking it’s a typo, and a scrutinizing lead would almost certainly see it and think “Great–now I have to change this and test everything this filter touches.”

A real world example looks like this:

/**
 * CLEVER CODE ALERT. This shorthand ternary accepts the tested value as the value returned if
 * true, otherwise the else value. NB this does not work in reverse (i.e. $a = $b ? 'value' :; ).
 */
$blog_id = $blog_id ?: get_current_blog_id();

Here’s that nifty shorthand ternary again! This saves some characters and looks pretty neat, but there’s a pretty hefty comment above it to explain what’s going on. The comment alone negates the time saved in not writing out the whole ternary, but for me the point of code like this, and the associated documentation, is to teach and inform others.

As programmers working in an increasingly collaborative world, we should be making strides in documentation–not only to guide other developers through the big ins and outs, but also to illuminate the many tricks and secrets that the language holds.

Happy coding!

The post Is Clever Code OK? appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/05/17/is-clever-code-ok/feed/ 0 12982