One place for hosting & domains

      Common

      How to Fix Common SSL Issues in WordPress (5 Key Solutions)


      A few years ago, Google announced that it would begin flagging websites that don’t have a Secure Sockets Layer (SSL) certificate installed. While setting up an SSL certificate tends to be pretty straightforward, you may encounter some errors in the process.

      The good news is that many of these errors have simple fixes. Therefore, if you run into a problem when trying to move a current WordPress site to SSL, there’s no need to panic. All it takes is a little troubleshooting to get your site working properly (and securely) in no time.

      In this post, we’ll start by discussing the importance of SSL certificates on your website. Then we’ll provide you with a list of five common SSL issues and show you how to fix them on your WordPress site. Let’s get started!

      Do More with DreamPress

      DreamPress’ automatic updates and strong security defenses take server management off your hands so you can focus on content creation.

      An Overview of SSL (And Why It’s Important)

      SSL enables you to ensure that your website delivers a secure connection via Hypertext Transfer Protocol Secure (HTTPS) protocol. In a nutshell, this is the updated, secure version of HTTP. Since it’s encrypted, HTTPS increases the security of any data that is transferred.

      Installing an SSL certificate on your WordPress site is important for several reasons. For starters, it enables the web server and browser to communicate over a secure connection.

      Moreover, SSL/HTTPS can help prevent security breaches that can compromise not only your personal information but your customers’ as well. For this reason, Google now penalizes sites that don’t have an SSL certificate.

      For example, it may display a “not secure” or “your connection is not private” warning message to users who try to access the site.

      A “Your connection is not private” warning message in Google Chrome.

      The exact wording of the message may vary depending on the browser you’re using, but the concept is the same. Ultimately, this can hurt your engagement. Additionally, it can hamper your Search Engine Optimization rankings.

      Finally, not having SSL properly configured can also limit what type of site you’re able to run. For instance, if you want to start an online store, you’ll need SSL/HTTPS encryption to accept online payments via gateways such as Stripe, PayPal, and Authorize.net.

      How to Fix Common SSL Issues in WordPress (5 Key Solutions)

      Now that we understand a little more about what SSL/HTTPS is and why it’s important, let’s get into the issues that can come from it. Below are five of the most common SSL problems in WordPress and how to resolve them.

      1. The NET::ERR_CERT_INVALID Error

      If you’re a Google Chrome user, one of the most common issues you might run into is an error message that reads “NET::ERR_CERT_INVALID.”

      A CERT: ERR_AUTHORITY_INVALID error message in Chrome.

      This can happen in other browsers, too, though the message may differ slightly. In any case, it simply means that the connection to the site is not secure.

      If you have an SSL certificate installed on your site, this likely means something is wrong with the settings or configuration, and therefore the browser cannot read and accept it properly. When this is the case, there are a few steps you can take.

      First, you’ll want to make sure the certificate is assigned to the correct domain or subdomain. Next, you’ll need to check that your certificate is not expired. You can do this by clicking on the padlock icon to the left of the browser address bar.

      Details of the certificate will appear, and you’ll want to make sure it says “Valid.” If it says “not valid,” you’ll need to renew it as soon as possible through the issuing provider, also listed here.

      If you installed the certificate yourself, you could try reinstalling it. However, you may want to use a different provider this time, as your browser may not recognize the issuing authority of your current certificate. We recommend using Let’s Encrypt.

      The Let’s Encrypt website.

      Finally, if the certificate is assigned to the correct domain and is updated, you may want to contact your hosting provider. If they installed the certificate, they might know what steps to take to resolve the issue.

      2. Mixed Content Errors

      Another common type of error you may encounter when moving to SSL is mixed content warnings. In a nutshell, this is what happens when images, scripts, or stylesheets on your site load while using the old, unsecured HTTP protocol. In other words, some of your WordPress content is secure while other parts aren’t.

      There are two methods you can use to fix mixed content errors. The first is to use a plugin such as Really Simple SSL.

      The Really Simple SSL plugin.

      Once you install and activate the tool on your website, you can locate the plugin settings by navigating to Settings > SSL.

      The Really Simple SSL plugin settings in WordPress.

      However, you don’t need to take any further action to fix the mixed content errors. The plugin automatically does that upon activation.

      The second method you can use is to manually fix the warnings. To get started, you can navigate to Settings > General in WordPress.

      Under WordPress Address (URL) and Site Address (URL), check to make sure that the URLs are using “https.”

      The WordPress General settings screen.

      After you save your changes, you can install the Better Search Replace plugin.

      The WordPress Better Search Replace plugin.

      With this tool, you can easily search for, find, and replace old URLs within your WordPress database. Once you activate it, you can navigate to Tools > Better Search Replace.

      The Better Search Replace plugin settings.

      In the Search for field, you can add your website URL with “http” at the beginning. Then, add “https” to the Replace with field.

      When you’re done, save your changes. Now the mixed content errors should be gone when you refresh your site.

      3. Too Many Redirects

      Another SSL issue you may run into is the too many redirects error. This might happen because WordPress lets you enforce SSL/HTTPS for the admin area of your site.

      To resolve this error, you’ll need to edit your wp-config.php file. You can locate this file by using a Secure File Transfer Protocol (SFTP) client like FileZilla or the file manager in your web hosting account.

      If you have a DreamHost account, start by navigating to Websites > Files in the sidebar. Then, locate your domain and click on the Manage Files button.

      Accessing the file manager in your DreamHost account

      This will take you to the file manager. To access your site’s directory, you’ll need to open the folder labeled with your domain name. Inside it, you’ll find the wp-config.php file.

      If you’re using FileZilla, the first step is to connect to your WordPress site. If this is your first time using the FTP client, you’ll need to obtain your credentials from your web host. Once connected, locate the wp-config.php file in your site’s directory.

      Locating the wp-config.php file in FileZilla.

      Open the file and insert the following snippet of code:

      define('FORCE_SSL_ADMIN', true);
      
      // in some setups HTTP_X_FORWARDED_PROTO might contain
      
      // a comma-separated list e.g. http,https
      
      // so check for https existence
      
      if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
      
             $_SERVER['HTTPS']='on';

      Note that you should add this at the bottom of the file, right before the line that reads, “That’s all, stop editing! Happy blogging.” When you’re ready, save your changes and close the file.

      4. HTTP to HTTPS Redirect

      By default, WordPress won’t automatically redirect your site from HTTP to HTTPS. Instead, you’ll need to tell it to do so. In some cases, you can use a plugin such as Really Simple SSL.

      However, you can also manually configure the HTTP to HTTPS redirect by editing your .htaccess file. Again, you can do this via SFTP or the file manager in your hosting account.

      Locate and open the .htaccess file, then add in the following code:

      <IfModule mod_rewrite.c>
      
      RewriteEngine On
      
      RewriteCond %{HTTPS} off
      
      RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
      
      </IfModule>

      Remember to save your changes when you’re done. If you’re not comfortable editing your site’s files, we recommend using a plugin or contacting your hosting provider for assistance.

      5. A Name Mismatch Error

      A fifth common SSL issue you may run into is the name mismatch error, which we briefly touched on earlier. This occurs when your domain name listed in the SSL certificate does not match the browser URL. This normally happens when you purchase a certificate from a third-party seller.

      To fix this error, you’ll simply need to add the following code to your .htaccess file:

      <IfModule mod_rewrite.c>
      
      RewriteEngine On
      
      RewriteCond %{HTTPS} off
      
      RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
      
      </IfModule>

      Save your changes when you’re done. Then, when you revisit your WordPress site, you should no longer see any SSL error messages.

      Protect Your Website with DreamShield

      For just $3/month, our premium security add-on scans your site weekly to ensure it is free of malicious code.

      How to Fix Other Common WordPress Errors

      Do you want to learn how to resolve other technical issues on your site? We’ve put together several guides to help you troubleshoot some of the most common WordPress errors:

      Check out our WordPress Tutorials section if you’re looking for tips and best practices for running a WordPress site. This is a collection of expert-written guides designed to help you navigate the WordPress dashboard like a pro.

      Conclusion

      Adding an SSL certificate to your WordPress website is essential. This will help you ensure that your content is accessed via a secure HTTPS connection. However, setting one up can cause a variety of issues.

      In this post, we discussed five common SSL errors and showed you how to resolve them:

      1. The NET::ERR_CERT_INVALID error. This suggests that your certificate needs to be renewed or reinstalled.
      2. Mixed content errors. You can fix this manually or with a plugin such as Really Simple SSL.
      3. Too many redirects. You may be able to resolve this issue by adding code to your wp-config.php file.
      4. A WordPress HTTP to HTTPS redirect. You can configure this manually via your site’s .htaccess file or by using a plugin such as Really Simple SSL.
      5. A name mismatch error. This happens when the certificate domain and browser URL do not match, in which case you’ll need to add code to your .htaccess file.

      Do you need help choosing and installing an SSL certificate on your WordPress site? When you use DreamHost as your hosting provider, this is an effortless process. Check out our DreamPress plans to learn more!



      Source link

      How To Use Downshift in Common Dropdown Use Cases


      Introduction

      Downshift is a library that helps you build simple, flexible, WAI-ARIA compliant enhanced input React components. Its major use case is for building autocomplete components, but it can also be used to build dropdown components.

      In this tutorial, we’ll walk through some common use cases solved with Downshift.

      Prerequisites

      To follow this tutorial, you need Node and NPM installed on your machine. A basic understanding of React will help you get the most out of this tutorial.

      If you don’t have Node.js installed, go to the Node website and install the recommended version for your operating system.

      Step 1 — Setting Up the Application

      We’ll make use of Create React App to create a simple React app with no build configuration. If you don’t have Create React App installed, run npm i create-react-app in your terminal to install it.
      Once you have it on your machine, run the following command to set up a new React project in a directory called downshift-examples and move to this new directory by running these commands:

      • create-react-app downshift-examples
      • cd downshift-examples

      Once you’re in the downshift-examples directory, run the following command to install Downshift and some other packages:

      • yarn add downshift axios react-popper

      Open the App.css file in the src folder and add the following styles:

      src/App.css

          input {
            margin: 1rem;
            width: 20rem;
            padding: 1rem .5rem;
          }
          .downshift-dropdown {
            margin: 0 auto;
            width: 20rem;
            border: 1px solid whitesmoke;
            border-bottom: none;
          }
          .dropdown-item {
            padding: 0.5rem;
            cursor: pointer;
            border-bottom: 1px solid whitesmoke;
            font-size: 1rem;
            text-align: left;
          }
          .dropdown-button {
            padding: 0.6rem;
            border-radius: 3px;
            background: white;
            cursor: pointer;
          }
          .popper-div {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 5rem;
          }
          .popper-item {
            padding: .5rem;
            border-bottom: 1px solid whitesmoke;
          }
      

      With everything set up, let’s look at some basic Downshift concepts.

      Overview of Downshift Concepts

      When using Downshift, the only component we need is <Downshift />. We call the <Downshift /> component and pass it some props and it works its magic. Here are some of the most used props:

      1. onChange: This function is called when the user selects an item and the selected item has changed. It returns the selectedItem.
      2. itemToString: This function is used to determine the string value for the selected item which is used to compute the inputValue.
      3. inputValue: This represents the value the input field should have.
      4. getInputProps: This function returns the props you should apply to the input element that you render.
      5. getItemProps: This function returns the props you should apply to any menu item elements you render.
      6. isOpen: This is a boolean that indicates whether or not the menu is open.
      7. selectedItem: This represents the currently selected item input.
      8. render: This is where you render whatever you want to based on the state of Downshift. This function is called with an object.

      You can check the documentation for the full list of props. Now let’s put this knowledge to use.

      Step 2 — Creating a Select Field

      Our first Downshift use case is a select field. Go ahead and create a DownshiftOne.js file in the src folder in the root directory of your app. Add the following code to it:

      src/DownshiftOne.js

          import React from 'react'
          import Downshift from 'downshift';
      
          const books = [
            { name: 'Harry Potter' },
            { name: 'Net Moves' },
            { name: 'Half of a yellow sun' },
            { name: 'The Da Vinci Code' },
            { name: 'Born a crime' },
          ];
      
          const onChange = (selectedBook) => {
            alert(`your favourite book is ${selectedBook.name}`)
          }
      
          export default () => {
            return (
              <Downshift onChange={onChange} itemToString={books => (books ? books.name : '')}>
                {/* we'll insert a callback here */}
              </DownShift>
            )
          }
      

      In the code above, we import React and Downshift and declare an array of books, an onChange function, and also a functional component that returns the <Downshift/> component. In the <Downshift/> component, we pass the onChange and itemToString props. Inside the <Downshift/> component, we’ll pass other props to a callback and render our input field.

      Next, we’ll pass the props we need in a callback to the <Downshift/> component. Update your functional component with the following:

      src/DownshiftOne.js

          ...
      
          export default () => {
            return (
              <Downshift onChange={onChange} itemToString={books => (books ? books.name : '')}>
                // pass the downshift props into a callback
                {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => (
                  <div>
                    // add a label tag and pass our label text to the getLabelProps function
                    <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Choose your favourite book</label> <br />
                    // add our input element and pass our placeholder to the getInputProps function
                    <input {...getInputProps({ placeholder: "Search books" })} />
                    // if the input element is open, render the div else render nothing
                    {isOpen ? (
                      <div className="downshift-dropdown">
                        {
                          // filter the books and return items that match the inputValue
                          books
                            .filter(item => !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase()))
                            // map the return value and return a div
                            .map((item, index) => (
                              <div
                                className="dropdown-item"
                                {...getItemProps({ key: item.name, index, item })}
                                style={{
                                  backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                                }}>
                                {item.name}
                              </div>
                            ))
                        }
                      </div>
                    ) : null}
                  </div>
                )}
              </Downshift>
            )
          }
      

      In the code snippet above, we passed our Downshift props as parameters to a callback:

          {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => ()}
      

      In the callback, we add our input tag and pass it our getInputProps props:

          <input {...getInputProps({ placeholder: "Search books" })} />
      

      Next, we check if the input element is open. If it is, we return a div element containing our menu and return null if it’s not:

          { isOpen ? (<div className="downshift-dropdown">...</div>) : null }
      

      Lastly, in the div element which we’re returning, we filter through our books array, returning only the items that include the inputValue. We then map through the filtered books and render them on the page.

      We also passed the getItemProps function to the div rendered in the map function. It returns the props that we applied while rendering the items.

      Let’s import our component to the parent App component, and see our functional select field:

      src/App.js

          import React, { Component } from 'react';
          import logo from './logo.svg';
          import './App.css';
          import DownshiftOne from './DownshiftOne'; // import the component
      
          class App extends Component {
            render() {
              return (
                <div className="App">
                  <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                  </header>
                  <DownshiftOne /> // render the component
                </div>
              );
            }
          }
          export default App;
      

      Ensure your server is running by running npm start in your terminal. If you open http://localhost:3000 in your browser, you will see the app running.

      Step 3 — Using Downshift with Axios

      In our next example, we’ll use Downshift to create a search field for movies. In the src folder, create a DownshiftTwo.js file and add the following code:

      src/DownshiftTwo.js

          import React, { Component } from 'react'
          import Downshift from 'downshift';
          import axios from 'axios';
      
          export default class DownshiftTwo extends Component {
            constructor(props) {
              super(props)
              this.state = {
                movies: []
              }
              this.fetchMovies = this.fetchMovies.bind(this)
              this.inputOnChange = this.inputOnChange.bind(this)
            }
            // onChange method for the input field
            inputOnChange(event) {
              if (!event.target.value) {
                return
              }
              this.fetchMovies(event.target.value)
            }
            // input field for the <Downshift /> component
            downshiftOnChange(selectedMovie) {
              alert(`your favourite movie is ${selectedMovie.title}`)
            }
            // method to fetch the movies from the movies API
            fetchMovies(movie) {
              const moviesURL = `https://api.themoviedb.org/3/search/movie?api_key=APIKey&query=${movie}`;
              axios.get(moviesURL).then(response => {
                this.setState({ movies: response.data.results })
              })
            }
            render() {
              return (
                <Downshift onChange={this.downshiftOnChange} itemToString={item => (item ? item.title : '')}>
                // pass the downshift props into a callback
                  {({ selectedItem, getInputProps, getItemProps, highlightedIndex, isOpen, inputValue, getLabelProps }) => (
                    <div>
                      // add a label tag and pass our label text to the getLabelProps function
                      <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Choose your favourite movie</label> <br />
                      // add a input tag and pass our placeholder text to the getInputProps function. We also have an onChange eventlistener on the input field
                      <input {...getInputProps({
                        placeholder: "Search movies",
                        onChange: this.inputOnChange
                      })} />
                      // if the input element is open, render the div else render nothing
                      {isOpen ? (
                        <div className="downshift-dropdown">
                          {
                            // filter the movies in the state
                            this.state.movies
                              .filter(item => !inputValue || item.title.toLowerCase().includes(inputValue.toLowerCase()))
                              .slice(0, 10) // return just the first ten. Helps improve performance
                              // map the filtered movies and display their title
                              .map((item, index) => (
                                <div
                                  className="dropdown-item"
                                  {...getItemProps({ key: index, index, item })}
                                  style={{
                                    backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                    fontWeight: selectedItem === item ? 'bold' : 'normal',
                                  }}>
                                  {item.title}
                                </div>
                              ))
                          }
                        </div>
                      ) : null}
                    </div>
                  )}
                </Downshift>
              )
            }
          }
      

      In the code above, we have a class component where we’re rendering the <Downshift/> component and passing our props to it. In the input field in the <Downshift/> component, we have an onChange event listener that listens for new input to the field.

      If there’s an input, we call the fetchMovies method which takes the value of the input field and makes an AJAX request to the movies API using Axios. We set the request response to the component state, then filter through them to return the matching item as done in the previous example.

      Import and render the component in the parent App component as we did in the previous example. Visit your browser and try searching for your favorite movie.

      Step 4 — Creating a Dropdown with Downshift

      One other use case for Downshift is powering dropdowns. Dropdown’s API helps us build simple dropdown components. Let’s create a DownshiftThree.js file in the src folder and see how to achieve this.

      In the DownshiftThree.js file, add the following code:

      src/DownshiftThree.js

          import React, { Component } from 'react'
          import Downshift from 'downshift';
      
          export default class DownshiftThree extends Component {
            constructor(props) {
              super(props)
              this.books = [
                { name: 'Harry Potter' },
                { name: 'Net Moves' },
                { name: 'Half of a yellow sun' },
                { name: 'The Da Vinci Code' },
                { name: 'Born a crime' },
              ];
      
              this.state = {
                // currently selected dropdown item
                selectedBook: ''
              }
      
              this.onChange = this.onChange.bind(this)
            }
      
            onChange(selectedBook) {
              this.setState({ selectedBook: selectedBook.name })
            }
      
            render() {
              return (
                <Downshift onChange={this.onChange} selectedItem={this.state.selectedBook} itemToString={books => (books ? books.name : '')}>
                // pass the downshift props into a callback
                  {({ isOpen, getToggleButtonProps, getItemProps, highlightedIndex, selectedItem: dsSelectedItem, getLabelProps }) => (
                    <div>
                      // add a label tag and pass our label text to the getLabelProps function
                      <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Select your favourite book</label> <br />
                      // add a button for our dropdown and pass the selected book as its content if there's a selected item
                      <button className="dropdown-button" {...getToggleButtonProps()}>
                        {this.state.selectedBook !== '' ? this.state.selectedBook : 'Select a book ...'}
                      </button>
                      <div style={{ position: 'relative' }}>
                        // if the input element is open, render the div else render nothing
                        {isOpen ? (
                          <div className="downshift-dropdown">
                            {
                              // map through all the books and render them
                              this.books.map((item, index) => (
                                <div
                                  className="dropdown-item"
                                  {...getItemProps({ key: index, index, item })}
                                  style={{
                                    backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                    fontWeight: dsSelectedItem === item ? 'bold' : 'normal',
                                  }}>
                                  {item.name}
                                </div>
                              ))
                            }
                          </div>
                        ) : null}
                      </div>
                    </div>
                  )}
                </Downshift>
              )
            }
          }
      

      In the code above, we have a DownshiftThree class component where we render the <Downshift/> component. In the callback passed to it, we have a button where we pass the getToggleButtonProps function. The button houses a ternary operator where we set the content the button based on whether the selectedBook in the component’s state is set.

      Next, we call the isOpen prop to see if the dropdown is open or not. If it is open, we map through all the books and render them in the dropdown.

      In the onChange method passed to the <Downshift/> component, whenever an item is selected, we set it the state, thereby updating the content of the button.
      Import and render the component to the parent App component and reload your browser to see the app at this point.

      Step 5 — Creating Forms with Downshift

      In this example, we’ll be using a Downshift input component as input fields in a form and attempting to submit the form data. In the src directory, let’s create two files: DownshiftInputField.js and DownshiftFour.js.

      In the DownshiftInputField.js, we’ll create an input component with Downshift and use it to render some input fields in the DownshiftFour.js file. Let’s create a functional component in our DownshiftInputField.js file:

      src/DownshiftInputField.js

          import React from 'react'
          import Downshift from 'downshift';
      
          export default ({ items, onChange, label, placeholder, name }) => {
            return (
              <Downshift onChange={onChange} itemToString={items => (items ? items.name : '')}>
                {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => (
                  <div>
                  // add a label tag and pass our label text to the getLabelProps function
                    <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>{label}</label> <br />
                    // add an input tag and pass our placeholder text to the getInputProps function
                    <input name={name} {...getInputProps({ placeholder })} />
                    // if the input element is open, render the div else render nothing
                    {isOpen ? (
                      <div className="downshift-dropdown">
                        {
                          items
                            // filter the items and return those that includes the inputValue
                            .filter(item => !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase()))
                            // map through the returned items and render them to the page
                            .map((item, index) => (
                              <div
                                className="dropdown-item"
                                {...getItemProps({ key: item.name, index, item })}
                                style={{
                                  backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                                }}>
                                {item.name}
                              </div>
                            ))
                        }
                      </div>
                    ) : null}
                  </div>
                )}
              </Downshift>
            )
          }
      

      In the code above, our functional component takes in an array of items, an onChange function, a label and placeholder text, and finally a name. The component returns a <Downshift/> component which receives all the required props in a callback function. In the callback, we have a label and an input field.

      As with other examples, we pass the isOpen prop to a ternary operator. If the input field is open, we filter through the array of items to return items that match the inputValue, then we map through the returned items and render them to the DOM.

      Now that our input field component is ready, let’s import it into the DownshiftFour.js file:

      src/DownshiftFour.js

          import React, { Component } from 'react'
          import DownshiftInputField from './DownshiftInputField';
      
          export default class DownshiftFour extends Component {
            constructor(props) {
              super(props)
              this.state = {
                books: [
                  { name: 'Harry Potter' },
                  { name: 'Net Moves' },
                  { name: 'Half of a yellow sun' },
                  { name: 'The Da Vinci Code' },
                  { name: 'Born a crime' },
                ],
                movies: [
                  { name: 'Harry Potter' },
                  { name: '12 Strong' },
                  { name: 'Half of a yellow sun' },
                  { name: 'Gringo' },
                  { name: 'Black Panther' },
                ],
                book: '',
                movie: ''
              }
              this.onSubmit = this.onSubmit.bind(this);
              this.onChange = this.onChange.bind(this);
            }
      
            onSubmit(event) {
              event.preventDefault();
              alert(`
              Favourite book: ${this.state.book}
              Favourite movie: ${this.state.movie}
              has been submitted
              `)
            }
      
            onChange(selectedBook, stateAndHelpers) {
              const element = document.querySelector(`#${stateAndHelpers.id}-input`)
              this.setState({ [element.name]: selectedBook.name })
            }
      
            render() {
              return (
                <form onSubmit={this.onSubmit}>
                  <DownshiftInputField
                    items={this.state.books}
                    onChange={this.onChange}
                    label="Select your favourite book"
                    name="book"
                    placeholder="Search your favourite book" />
                  <DownshiftInputField
                    items={this.state.movies}
                    onChange={this.onChange}
                    label="Select your favourite movie"
                    name="movie"
                    placeholder="Search your favourite movie" />
                  <input type="submit" value="Submit" className="dropdown-button" />
                </form>
              )
            }
          }
      

      In our DownshiftFour.js file, we imported our input field component and created a class component. In our component state, we have an array of books and movies and we render our input field component twice in a form: one as an input field for books and another for movies.

      Downshift’s onChange function takes in a second parameter called stateAndHelpers which gives us some information about Downshift’s current state.

      In the onChange method, we find the input field the user is currently interacting with by getting it’s id from the stateAndHelpers argument and querying the DOM for it. Once we have the element, we set it to the component state.

      When the user hits the submit button, the onSubmit method, gets the selected book and movie from the state and does whatever we want with it.

      Import and render the <DownshiftFour/> component in the parent App component and let’s give it a spin in the browser.

      Step 6 — Using Downshift with Popper.js

      In our last example for this article, we’ll be using Popper.js to change the directions of a Downshift popup. Popper is a library that makes positioning tooltips or popups a more manageable task.

      We already installed the react-popper package while setting up the application, so let’s create a DownshiftFive.js file in the src folder.

      Let’s add the following code to the new file:

      src/DownshiftFive.js

          import React, { Component } from 'react'
          import Downshift from 'downshift';
          import { Popper, Manager, Target } from 'react-popper';
      
          export default class DownshiftFive extends Component {
            // define some default props
            static defaultProps = {
              positions: [
                'top',
                'top-start',
                'top-end',
                'bottom-start',
                'bottom',
                'bottom-end',
              ]
            }
      
            render() {
              return (
                <div className="popper-div">
                // wrap the whole component in Popper's <Manager/> component
                  <Manager>
                    <Downshift render={({ inputValue, getInputProps, getItemProps, isOpen, selectedItem, highlightedIndex }) => (
                      <div>
                      // wrap our input element in Popper's <Target/> component
                        <Target>
                          <input {...getInputProps({ placeholder: 'Enter a position' })} />
                        </Target>
                        <div className="downshift-dropdown">
                          {isOpen ? (
                          // pass the selected item to Popper
                            <Popper
                              placement={selectedItem || 'bottom'}
                              style={{ backgroundColor: 'skyblue' }}
                            >
                              {
                              // filter through all the positions and return the ones that include the inputValue
                                this.props.positions
                                  .filter(item => !inputValue || item.includes(inputValue.toLowerCase()))
                                  // map through all the returned positions and render them
                                  .map((item, index) => (
                                    <div className="downshift-item popper-item"
                                      {...getItemProps({ item })}
                                      key={item}
                                      style={{
                                        cursor: 'pointer',
                                        backgroundColor: highlightedIndex === index ? '#bed5df' : 'transparent',
                                        fontWeight: selectedItem === item ? 'bold' : 'normal',
                                      }}>
                                      {item}
                                    </div>
                                  ))
                              }
                            </Popper>
                          ) : null}
                        </div>
                      </div>
                    )}></Downshift>
                  </Manager>
                </div>
              )
            }
          }
      

      In the code snippet above, we create a DownshiftFive class components with a default position props. These are the positions Popper will use to render our popup. In the render method of the component, we’re returning a <Downshift/> component wrapped in a <Manager/> component:

          return (
            <div className="popper-div">
              <Manager>
                <Downshift render={({ inputValue, getInputProps, getItemProps, isOpen, selectedItem, highlightedIndex }) => (
                  {/* all of our remaining code goes here */}
                )}>
                </DownShift>
              </Manager>
            </div>
          )
      

      The Manager component is a wrapper exposed by Popper that needs to surround all other react-popper components on the page to make them communicate with each other.

      If you look closely, you’ll see we’re passing a render prop to the <Downshift/> component. This is another way to pass our props to the <Downshift/> component. Basically, we moved our callback and passed it to the render prop.

      In the callback passed to the render prop, we wrap our input field in a <Target/> component. This informs Popper that this is the input field around which the popup should be rendered.

      Next, we check if our input is open and render a <Popper/> component and pass our selectedItem to its placement prop. This helps Popper reposition the popup whenever a new position is selected. Lastly, as with other examples, we filter all the default prop positions, return the positions that include the inputValue, map through them and render them on the page.

      Finally, import and render the <DownshiftFive/> component in the parent App component and check it out in the browser. You will see the final product.

      Conclusion

      In this post, you’ve created an application to explore common React dropdown use cases solved with Downshift.



      Source link

      How to Fix 16 Common Image Issues in WordPress


      High-quality imagery can do wonders for your website. When used right, images can make your content highly engaging and easier to digest. More importantly, blog posts with images tend to rank better in search engines than those lacking visuals. Therefore, it’s essential to know how to use images on your site adequately.

      WordPress enables excellent flexibility when it comes to adding photos to pages and posts. You can format your images and arrange them within your content any way you wish. You can also make your site more visually appealing with features such as photo galleries, headers, and background images.

      If you want to learn more about using images on your WordPress site, you’ve come to the right place. In this post, we’ll show you how to fix 16 common image issues in WordPress with clear, step-by-step instructions. Let’s get started!

      We Make WordPress Easier for You

      Leave migrating your site, installing WordPress, managing security and updates, and optimizing server performance to us. Now you can focus on what matters most — growing your website!

      1. How to Upload Images in WordPress

      To upload an image in a WordPress post or page, simply click on the black button with the plus symbol (in this post, we’ll refer to it as the Add Block button). This will ask you to choose a block to insert into your content.

      Select the Image button, and a block will appear.

      Uploading an image in WordPress.

      Next, click on the Upload button and select the image you want to add. Select Open, and then you’re done!

      2. How to Align an Image to the Left or Right

      When you select an image, a toolbar will appear above it. Click on the alignment button and choose Align left or Align right.

      Aligning an image in WordPress.

      As you can see, this toolbar also gives you other options as well. This includes replacing the image and adding a link to it.

      3. How to Add Captions Below Images

      To add a caption, simply click on your image, and you’ll see the option to write something below.

      Writing an image caption in WordPress.

      Note that you’ll also get a few styling options for your caption. You can link to another page by clicking on the third button in the caption toolbar.

      4. How to Display Images in Columns and Rows

      If you want to display images in columns and rows, you can click on the Add Block button and select Gallery from the options. Next, click on Upload in the gallery block, and then select the images you want to add and choose Open.

      Adding an image gallery in WordPress.

      Once your images have been uploaded, you’ll be able to move them around. To do this, you can click on an image and use the arrow buttons. You’ll also see an option to write a caption for your images and the gallery.

      5. How to Create Responsive Image Galleries

      The default WordPress gallery is very basic. If you use your site to showcase your photography, you might want to consider adding a plugin that lets you build and customize your own image galleries.

      For beautiful responsive galleries, we recommend using the Envira Gallery plugin. After installing and activating the plugin, navigate to Envira Gallery > Add New. There you can create your first gallery, which you can then insert into your posts by selecting the Envira Gallery block.

      The Envira Gallery settings page.

      You can start by uploading some photos to your gallery and then clicking on Config to select the number of columns, set the lazy loading delay, and use the other available features.

      Adding an Envira Gallery in WordPress.

      Remember to name your galleries. This way, you’ll be able to find them more easily when adding them to your posts.

      6. How to Set Featured Images for Posts

      WordPress lets you select a featured image for your posts. This image will be attributed to your post when it appears in your blog feed. Without a featured image, your post will have a missing thumbnail image. A post thumbnail is a reduced-size picture that appears on your blog’s homepage to help users sort through and identify relevant content.

      To set a featured image, head to the sidebar on the right, select the Post tab, and navigate to the Featured image section.

      Setting a featured image in WordPress.

      Next, click on Set featured image and upload your image file. Alternatively, you can choose an image that is already uploaded to your site by clicking on the Media Library tab.

      7. How to Add Cover Images in Posts and Pages

      If you’re writing a long post, you might want to add a wide cover image between different sections so that your content is more digestible. To add a cover image, start by clicking on the Add Block button and typing “cover” into the search bar.

      Once you select the Cover button, the block will appear. Click on Upload to add an image from your computer, or select Media Library to choose an image you’ve already uploaded to your site.

      Adding a cover image in a WordPress post.

      If you want to make some changes to the cover image, you can use the options in the tool section in the post.

      8. How to Fix the Featured Image Appearing Twice

      Some WordPress themes display the featured images at the top of published posts. This image will not be visible in your post when using the content editor.

      Therefore, you might think you have to insert it into your content in addition to setting it as the featured image (as shown in step six). If you do this, you’ll get the same image twice in your live post.

      Fixing a featured image appearing twice issue.

      To fix the multiple images problem, simply delete the image from the post editor. Then you can just use the one you selected in the Set featured image box.

      9. How to Crop Images

      WordPress offers some basic photo editing features. To edit a photo, you can go to your WordPress dashboard and navigate to Media > Library. After you select the image, a window will pop up.

      Cropping images manually in WordPress.

      Click on the Edit Image button below the image, and you’ll be taken to a page with editing tools. Select the Crop button at the top, and drag the corners of the box to crop the image to your liking.

      Alternatively, you can change the image size by entering the dimensions and aspect ratio in the right sidebar.

      Cropping images in WordPress.

      At the top, you can find options to rotate and flip the image. Once you’ve finished editing your photo, click on Save. Note that the changes will be applied to the original photo.

      10. How to Add Header Images

      Some WordPress themes feature header images. To change the default header image, go to your dashboard and navigate to Appearance > Customize.

      On the customization page, click on Header Image. If you can’t see this option in the menu, it means that your current theme does not support header images.

      Changing the header of a WordPress theme.

      On the Header Image page, select Add new image to replace the default image in your header.

      Changing the header of your WordPress site.

      When you’re done, you can click on the Publish button at the top of the screen. This will save your changes.

      11. How to Add Background Images

      Your WordPress theme might also come with support for background images. To set a one, access the theme’s customization page by navigating to Appearance > Customize from your WordPress dashboard.

      Next, click on Colors. Locate Body Background and click on Select image.

      Changing the background of your WordPress site.

      When you set your background image, you’ll get some options for adjusting the preset and image position. Remember to save your changes before exiting.

      12. How to Find Free Images for Your WordPress Site

      When sourcing images for your posts and pages, we recommend accessing free stock photo sites to avoid copyright infringement. Several sites offer royalty-free images, including Pixabay, UnsplashFlickr Creative Commons, and Pexels.

      A site offering free stock photos.

      The images available on these sites are free to use. However, it’s always a good idea to credit the photographer or artist with a link in the image caption.

      13. How to Tag Images

      Tags make it easier to organize and filter photos on your site. However, WordPress currently does not offer an image tagging feature. Therefore, you might want to download a plugin that lets you sort your images with categories and tags.

      For categorizing and tagging images, we recommend using the Media Library Assistant plugin. Start by installing and activating the plugin, and then head to Media > Library.

      You can see all the photos you’ve uploaded to your WordPress site on the Media Library page. Click on the list view button at the top, then find the photo you want to tag and click on Edit.

      The WordPress Media Library.

      On the Edit Media page, find the Att. Categories and Att. Tags sections on the right-hand side, and start adding categories and tags to your image.

      Tagging images in WordPress.

      You can also rename your image on this page, write a caption, and add alternative text. When you’re done, click on the Update button on the right to save your changes.

      14. How to Import External Images to WordPress

      To import external images to WordPress, you’ll need to access your old website’s files directly using a Secure File Transfer Protocol (SFTP) tool such as FileZilla. Locate your site’s root directory, and then go to wp-content/uploads.

      Accessing the WordPress uploads folder.

      There, you’ll find the media files that you’ve uploaded to your site. Download them to a secure location, and then log into your new WordPress site. Navigate to wp-content/uploads again, and copy over your media files.

      You may still encounter image-related errors after doing this since your image URLs may be pointing back to your old site. If that’s the case, you’ll need to go through and update your image URLs so they point to your new site instead, which can be a time-consuming process.

      To avoid that problem, we recommend using a plugin such as Duplicator to move your website between domains or web hosts. You may also benefit from reaching out to your new host for assistance to make sure everything on your site gets transferred over properly.

      15. How to Require a Featured Image in Your Posts

      If your site has multiple authors, you might want to set a reminder for everyone to select a featured image before publishing a post. To do this, you’ll need to add some custom code to your site.

      Before getting started, we recommend backing up your site and creating a child theme. Then you can add the following code at the end of your theme’s functions.php file:

      <?php
      
      /**
      
      * Require a featured image to be set before a post can be published.
      
      */
      
      add_filter( 'wp_insert_post_data', function ( $data, $postarr ) {
      
      $post_id              = $postarr['ID'];
      
      $post_status          = $data['post_status'];
      
      $original_post_status = $postarr['original_post_status'];
      
      if ( $post_id && 'publish' === $post_status && 'publish' !== $original_post_status ) {
      
      $post_type = get_post_type( $post_id );
      
      if ( post_type_supports( $post_type, 'thumbnail' ) && ! has_post_thumbnail( $post_id ) ) {
      
      $data['post_status'] = 'draft';
      
      }
      
      }
      
      return $data;
      
      }, 10, 2 );
      
      add_action( 'admin_notices', function () {
      
      $post = get_post();
      
      if ( 'publish' !== get_post_status( $post->ID ) && ! has_post_thumbnail( $post->ID ) ) { ?>
      
      <div id="message" class="error">
      
      <p>
      
      <strong><?php _e( 'Please set a Featured Image. This post cannot be published without one.' ); ?></strong>
      
      </p>
      
      </div>
      
      <?php
      
      }
      
      } );

      Save your changes, and users will be required to add featured images to all post types that support them.

      16. How to Set a Default Featured Image

      If you want to set a default featured image for those occasions when you can’t find the right photo, the Default Featured Image plugin is a handy tool to have. It lets you choose a photo that will automatically appear as the featured image for posts published without one.

      After installing and activating the plugin, navigate to Settings > Media in your dashboard.

      Using the Default Featured Image plugin.

      Click on the Select default feature image button and choose your photo. Finally, hit Save Changes at the bottom of the page.

      Take Your WordPress Website to the Next Level

      Whether you need help navigating the WordPress dashboard, choosing the perfect product image, or writing alt text, we can help! Subscribe to our monthly newsletter so you never miss an article.

      Additional WordPress Resources

      If you’re new to WordPress, you may run into some common issues while working with images and other content. To help you navigate any WordPress problem you encounter, we’ve put together several how-to guides:

      If you’re looking for more WordPress tips and hacks, check out our WordPress Tutorials. This collection of guides will help you set up and design your first WordPress site.

      Now You Can Fix That Common Image Issue

      Images can improve your site’s User Experience (UX) and increase the visibility of your content in search engine results. Therefore, it’s important to know how to use photos to engage readers with your content.

      Fortunately, WordPress makes it easy to upload and manage photos on your site. It lets you crop and customize images, as well as create beautiful photo galleries and headers to make your pages more interesting.

      If your business relies on high-quality imagery, you might want to consider using a web hosting service that offers full WordPress support. Our DreamPress plans are perfect for site owners who want to focus on growing their businesses and spend less time troubleshooting errors in WordPress.



      Source link