Home > Web Front-end > CSS Tutorial > Using Web Components in WordPress is Easier Than You Think

Using Web Components in WordPress is Easier Than You Think

Joseph Gordon-Levitt
Release: 2025-03-21 11:09:11
Original
592 people have browsed it

Using Web Components in WordPress is Easier Than You Think

Now that we have learned that both web components and interactive web components are easier to use than you think, let's see how to add them to the content management system, namely WordPress.

There are three main ways to add them. First, by manually entering into the website – putting them directly into a gadget or text block, basically anywhere you can place other HTML. Second, we can add them as theme output in the theme file. Finally, we can add them as output of custom blocks.

Article series

    <li> Web components are easier than you think <li> Interactive web components are easier than you think <li> Using web components in WordPress is easier than you think (you're here) <li> Enhanced built-in elements with web components is easier than you think <li> Context-aware web components are easier than you think <li> Web component pseudo-classes and pseudo-elements are easier than you think

Loading web component files

Regardless of the way you end up adding web components, we have to ensure the following:

    <li> When we need a template for custom elements, it must be available; <li> Any JavaScript we need is registered correctly; <li> Any unencapsulated styles we need are registered.

We will add from my previous article on interactive web components<zombie-profile></zombie-profile> Web components. Please check the code on CodePen.

Let's look at the first point. Once we have the template, it's easy to add it to the footer.php file of the WordPress theme, but rather than adding it directly to the theme, hook it to wp_footer so that the component's loading is independent of the footer.php file and the entire theme - assuming the theme uses wp_footer , most themes do this. If the template does not appear in your theme when trying, double check if wp_footer is called in the footer.php template file of your theme.

 <?php function diy_ezwebcomp_footer() { ?><?php }
add_action( &#39;wp_footer&#39;, &#39;diy_ezwebcomp_footer&#39;);
Copy after login

Next is JavaScript that registers components. We can also add JavaScript through wp_footer , but registration is the recommended way to link JavaScript to WordPress. So let's put JavaScript in a file named ezwebcomp.js (this name is completely arbitrary), place the file in the JavaScript directory of the theme (if any), and register it (in the functions.php file).

 wp_enqueue_script( 'ezwebcomp_js', get_template_directory_uri() . '/js/ezwebcomp.js', '', '1.0', true );
Copy after login

We need to make sure that the last parameter is set to true , i.e. it loads JavaScript before the ending body tag. If we load it into the head, it won't find our HTML template and it will be very angry (throw a bunch of errors).

If you can completely encapsulate your web components, then you can skip the next step. However, if you (like me) can't do this, you need to register those unencapsulated styles so that they are available anywhere you use the web components. (Similar to JavaScript, we can add it directly to the footer, but registering styles is the recommended method). So we will register our CSS file:

 wp_enqueue_style( 'ezwebcomp_style', get_template_directory_uri() . '/ezwebcomp.css', '', '1.0', 'screen' );
Copy after login

This is not too difficult, right? If you don't plan to let any user except administrator use it, you can add them anywhere you want to use them. But that's not always so we'll keep moving forward!

Don't filter out your web components

WordPress has several different ways to help users create valid HTML and prevent your Uncle Eddie from pasting the "funny" images obtained from Shady Al directly into the editor (including scripts for hacking all of your visitors).

So when adding web components directly to blocks or widgets, we need to be careful with the code filtering built in WordPress. Disabling it completely will make Uncle Eddie (and Shady Al) do whatever he wants, but we can modify it to allow our web components to pass through the gate (luckily, it blocks Uncle Eddie).

First, we can use the wp_kses_allowed filter to add our web components to the list of elements that should not be filtered out. It's kind of like we're whitelisting the component, which we do by adding it to the allow tag array passed to the filter function.

 function add_diy_ezwebcomp_to_kses_allowed( $the_allowed_tags ) {
  $the_allowed_tags['zombie-profile'] = array();
}
add_filter( 'wp_kses_allowed_html', 'add_diy_ezwebcomp_to_kses_allowed');
Copy after login

We<zombie-profile></zombie-profile> The component adds an empty array because WordPress filters out properties as well as elements - this brings us another problem: slot attributes are not allowed by default. Therefore, we have to explicitly allow it on every element that is expected to use it, and, accordingly, the user may decide to add it to any element in it. (Wait, even if you've reviewed it with each user six times, these elements lists are also different...who knows?) So, below, I set slot to true for use<span></span> ,<img alt="Using Web Components in WordPress is Easier Than You Think" > and<ul></ul> , I put these three elements<zombie-profile></zombie-profile> Component slots.

 function add_diy_ezwebcomp_to_kses_allowed( $the_allowed_tags ) {
  $the_allowed_tags['zombie-profile'] = array();
  $the_allowed_tags['span']['slot'] = true;
  $the_allowed_tags['ul']['slot'] = true;
  $the_allowed_tags['img']['slot'] = true;
  return $the_allowed_tags;
}
add_filter( 'wp_kses_allowed_html', 'add_diy_ezwebcomp_to_kses_allowed');
Copy after login

We can also enable slot attributes in all allowed elements using a method similar to the following code:

 function add_diy_ezwebcomp_to_kses_allowed($the_allowed_tags) {
  $the_allowed_tags['zombie-profile'] = array();
  foreach ($the_allowed_tags as &$tag) {
    $tag['slot'] = true;
  }
  return $the_allowed_tags;
}
add_filter('wp_kses_allowed_html', 'add_diy_ezwebcomp_to_kses_allowed');
Copy after login

Unfortunately, there is another possible problem. If all elements in your slot are inline/phrase elements, you may not have this problem, but if you have a block-level element to put into your web component, you may have conflicts with the block parser in the code editor. You may be better at boxing than I do, but I always lose.

For reasons I can't fully explain, the client parser assumes that the web component should only contain inline elements if you put one there

or

or some other block-level element that moves the ending web component tag after the last inline/phrase element. Worse, according to the notes in the WordPress developer manual, it is currently "cannot replace the client parser".

While this is frustrating and you have to let your web editor learn this, there is a workaround. If we put our web components directly in a custom HTML block in the block editor, the client parser won't let us cry, sway back and forth on the sidewalk and question our ability to code... Of course, this never happened to anyone...especially those who write articles...

Add components to theme

As long as it is not updated outside of HTML blocks, it is very easy to output our beautiful web components in the theme file. We add it the way we add it in any other context, and, assuming we have the templates, scripts, and styles installed, things will work.

But, suppose we want to output content for WordPress posts or custom post types in a web component. You know, write a post, and this post is the content of the component. This allows us to use the WordPress editor to output<zombie-profile></zombie-profile> Archive of elements. This is great because the WordPress editor already has us typing one of them<zombie-profile></zombie-profile> Most of the UI required for component content:

    <li> The post title can be used as the name of the zombie. <li> Regular paragraph blocks in post content can be used for zombie statements. <li> Featured pictures can be used for profile pictures of zombies.

That's most of the content! But we still need fields of zombies’ age, infection date and interest. We will create these fields using WordPress’s built-in custom field feature.

We will use the template part of the process of printing each post (e.g. content.php) to output the web component. First, we will print the open one<zombie-profile></zombie-profile> Tags, then post thumbnails (if present).

<zombie-profile> <?php // If there are post-featured pictures...
    if (has_post_thumbnail()) {
      $src = wp_get_attachment_image_url(get_post_thumbnail_id()); ??> <img  slot="profile-image" src="<?php%20echo%20%24src;%20?>" alt="Using Web Components in WordPress is Easier Than You Think" > <?php }
  ??></zombie-profile>
Copy after login

Next, we will print the title used for the name

 <?php // If the post title field exists...
  if (get_the_title()) { ??><?php echo get_the_title(); ??>
  <?php }
?>
Copy after login

In my code, I tested whether these fields exist before printing them for two reasons:

    <li> In most cases, hiding labels and elements around empty fields is a good programming practice. <li> If we end up outputting an empty name<span></span> (For example, `),那么该字段将在最终的个人资料中显示为空,而不是使用我们Web组件内置的默认文本、图像等。(例如,如果你希望文本字段在没有内容时为空,你可以在自定义字段中输入空格,或者跳过代码中的).

Next, we will take the custom fields and place them in the slot to which they belong. Again, this will go to the topic template for outputting the post content.

 <?php // Zombie age $temp = get_post_meta(the_ID(), &#39;Age&#39;, true);
  if ($temp) { ??><?php echo $temp; ??>
    <?php }
  // Zombie infection date $temp = get_post_meta(the_ID(), &#39;Infection Date&#39;, true);
  if ($temp) { ??><?php echo $temp; ??>
    <?php }
  // Zombie Interest $temp = get_post_meta(the_ID(), &#39;Interests&#39;, true);
  if ($temp) { ??>
Copy after login

One of the disadvantages of using WordPress custom fields is that you can't do any special formatting. A non-technical web editor that populates this content needs to be written for each interest item in the list<li> tags (e.g., 20. ). (You may be able to resolve this interface limitation by using more powerful custom field plugins such as Advanced Custom Fields, Pods, or similar plugins.) Finally, we add the zombie statement and ending<zombie-profile></zombie-profile> Label.

 <?php $temp = get_the_content();
      if ($temp) { ??><?php echo $temp; ??>
      <?php }
    ?>
Copy after login

Since we use the body of the post as our statement, we get some extra code, such as paragraph tags surrounding the content. Putting profile statements in custom fields can mitigate this, but depending on your purpose, it may also be the expected/desired behavior.

Then you just post each post as one and you can add as many posts/zombie profiles as you want!

Block Party: Web Components in Custom Blocks

Creating custom blocks is a great way to add web components. Your users will be able to fill in the fields you want and get the magic of web components without any code or technical knowledge. Also, the block is completely theme-independent, so we can use this block on one website and then install it on other WordPress sites – it's a bit like how we expect web components to work!

There are two main parts of the custom block: PHP and JavaScript. We will also add some CSS to improve the editing experience.

First is PHP:

 function ez_webcomp_register_block() {
  // Register the JavaScript required to build custom blocks
  wp_register_script(
    'ez-webcomp',
    plugins_url('block.js', __FILE__),
    array('wp-blocks', 'wp-element', 'wp-editor'),
    filemtime(plugin_dir_path(__FILE__) . 'block.js')
  );

  // Register component's CSS file wp_register_style(
    'ez-webcomp',
    plugins_url('ezwebcomp-style.css', __FILE__),
    array(),
    filemtime(plugin_dir_path(__FILE__) . 'ezwebcomp-style.css')
  );

  // Register custom block register_block_type('ez-webcomp/zombie-profile', array(
    // We already have external styles; these are only used 'editor_style' when we use the WordPress editor => 'ez-webcomp',
    'editor_script' => 'ez-webcomp',
  ));
}
add_action('init', 'ez_webcomp_register_block');
Copy after login

CSS is not required, it does help prevent zombies' profile pictures from overlapping with what's in the WordPress editor.

 /* Sets the width and height of the image.
 * Your mileage may vary, so please adjust as needed.
 * "pic" is the class we add to the editor in block.js*/
#editor .pic img {
  width: 300px;
  height: 300px;
}
/* This CSS ensures that the correct space is allocated to the image,
 * And also prevents the button from resizing before selecting the image.
*/
#editor .pic button.components-button {
  overflow: visible;
  height: auto;
}
Copy after login

The JavaScript we need is a little more complicated. I've tried to simplify it as much as possible and make it as accessible as possible, so I wrote it using ES5 to eliminate the need for compilation.

Show code

 (function (blocks, editor, element, components) {
  // The function to create element var el = element.createElement;
  // Process text input of block fields var RichText = editor.RichText;
  // Process upload image/media var MediaUpload = editor.MediaUpload;

  // Go back to register_block_type in PHP
  blocks.registerBlockType('ez-webcomp/zombie-profile', {
    title: 'Zombie Profile', // User-friendly name displayed in the block selector icon: 'id-alt', // Icons used in the block selector category: 'layout',
    // Properties are all the different fields we will use.
    // We are defining what they are and how the block editor gets the data from them.
    attributes: {
      name: {
        // Content type: 'string',
        // The location that can be used to obtain information source: 'text',
        // Selector is the way the block editor selects and gets content.
        // These should be unique in an instance of the block.
        // If you only have one img or one<p> etc, you can use the element selector.
        selector: '.zname',
      },
      mediaID: { type: 'number', },
      mediaURL: { type: 'string', source: 'attribute', selector: 'img', attribute: 'src', },
      age: { type: 'string', source: 'text', selector: '.age', },
      infectdate: { type: 'date', source: 'text', selector: '.infection-date' },
      interests: { type: 'array', source: 'children', selector: 'ul', },
      statement: { type: 'array', source: 'children', selector: '.statement', },
    },
    // The edit function handles how to display content in the block editor.
    edit: function (props) {
      var attributes = props.attributes;
      var onSelectImage = function (media) {
        return props.setAttributes({ mediaURL: media.url, mediaID: media.id, });
      };
      // The return statement is what is displayed in the editor.
      // el() Creates an element and sets its different properties.
      return el(
        // Use div instead of zombie-profile web components here for simplicity.
        'div',
        { className: props.className },
        // The name of the zombie el(RichText, {
          tagName: 'h2',
          inline: true,
          className: 'zname',
          placeholder: 'Zombie Name…',
          value: attributes.name,
          onChange: function (value) {
            props.setAttributes({ name: value });
          },
        }),
        el(
          // Zombie profile picture 'div',
          { className: 'pic' },
          el(MediaUpload, {
            onSelect: onSelectImage,
            allowedTypes: 'image',
            value: attributes.mediaID,
            render: function (obj) {
              return el(
                components.Button,
                {
                  className: attributes.mediaID ? 'image-button' : 'button button-large',
                  onClick: obj.open,
                },
                !attributes.mediaID ? 'Upload Image' : el('img', { src: attributes.mediaURL })
              );
            },
          })
        ),
        // We will include the title el('h3', {}, 'Age') of the zombie age in the block editor,
        // Age field el(RichText, {
          tagName: 'div',
          className: 'age',
          placeholder: 'Zombie\'s Age…',
          value: attributes.age,
          onChange: function (value) {
            props.setAttributes({ age: value });
          },
        }),
        // Infection date title el('h3', {}, 'Infection Date'),
        // Infection date field el(RichText, {
          tagName: 'div',
          className: 'infection-date',
          placeholder: 'Zombie\'s Infection Date…',
          value: attributes.infectdate,
          onChange: function (value) {
            props.setAttributes({ infectiondate: value });
          },
        }),
        // Hobby title el('h3', {}, 'Interests'),
        // Hobby field el(RichText, {
          tagName: 'ul',
          // Every time you press the `Enter` key, a new one will be created</p>
Copy after login
<li> multiline: 'li', placeholder: 'Write a list of interests…', value: attributes.interests, onChange: function (value) { props.setAttributes({ interests: value }); }, className: 'interests', }), // Zombie statement title el('h3', {}, 'Statement'), // Zombie statement field el(RichText, { tagName: 'div', className: "statement", placeholder: 'Write statement…', value: attributes.statement, onChange: function (value) { props.setAttributes({ statement: value }); }, }) ); }, // Store content in the database and display it in the front end. // Here we must make sure that the web components are used. save: function (props) { var attributes = props.attributes; return el( // Because using custom elements in WordPress requires some extra steps, we use a normal div. 'div', { className: 'zombie-profile', ...attributes }, // Make sure to verify that all fields exist before printing. attributes.name && el('h2', { className: 'zname' }, attributes.name), attributes.mediaURL && el('img', { src: attributes.mediaURL, slot: 'profile-image' }), attributes.age && el('div', { className: 'age' }, attributes.age), attributes.infectdate && el('div', { className: 'infection-date' }, attributes.infectdate), attributes.interests && el('ul', {}, attributes.interests), attributes.statement && el('div', { className: 'statement' }, attributes.statement) ); }, }); }(window.wp.blocks, window.wp.blockEditor, window.wp.element, window.wp.components));

Connect to web components

Now, wouldn't it be great if some kind-hearted person, article writer, and totally awesome person create a template that you can plug your web components into and use for your website? Well, that guy wasn't available (he went to help charities or something), so I did. It's on github:

Do it yourself - Simple Web Components of WordPress

The plugin is an encoding template that registers your custom web components, registers the scripts and styles required by the component, provides examples of custom block fields you may need, and even ensures that it is beautifully styled in the editor. Just like manually installing any other WordPress plugin, place it in a new folder in /wp-content/plugins , make sure to update it with your specific web component, and then activate it in WordPress on the Installed Plugins screen.

Not bad, right?

Even though it seems like there is a lot of code, we're actually just doing some pretty standard WordPress operations to register and render custom web components. And, since we package it as a plugin, we can put it on any WordPress site and start posting zombie profiles until we are satisfied.

I think the balance point is trying to make the components work as well in the WordPress block editor as the front end. Without this consideration, we can do the job with less code.

Nevertheless, we successfully put the exact same components we made in our previous post into the CMS, which allows us to place any number of zombie profiles on the website. We combine Web component knowledge with WordPress blocks to develop a reusable block for reusable Web components.

What kind of components would you build for your WordPress website? I think there are many possibilities here and I'd love to know what you'll make in the end.

The above is the detailed content of Using Web Components in WordPress is Easier Than You Think. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template