<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Carlos Guzmán</title>
    <description>The latest articles on DEV Community by Carlos Guzmán (@carlosguzman).</description>
    <link>https://dev.to/carlosguzman</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F177008%2Fb473afc1-3351-4d93-a0b2-20c4ca84b1d5.jpeg</url>
      <title>DEV Community: Carlos Guzmán</title>
      <link>https://dev.to/carlosguzman</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/carlosguzman"/>
    <language>en</language>
    <item>
      <title>How to update meta fields of multiple posts in WordPress using a single REST request</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Sat, 05 Oct 2024 17:10:51 +0000</pubDate>
      <link>https://dev.to/carlosguzman/how-to-update-meta-fields-of-multiple-posts-in-wordpress-using-a-single-rest-request-29fp</link>
      <guid>https://dev.to/carlosguzman/how-to-update-meta-fields-of-multiple-posts-in-wordpress-using-a-single-rest-request-29fp</guid>
      <description>&lt;p&gt;Building a custom settings page in WordPress using React, I faced the situation where I wanted to update meta fields of multiple posts at once. I want to share the approach I used with the WordPress REST API.&lt;/p&gt;

&lt;p&gt;The WordPress REST API has a framework for making a series of REST API calls at once. It is handy to update meta fields of multiple posts using a single REST request. The framework name is &lt;a href="https://make.wordpress.org/core/2020/11/20/rest-api-batch-framework-in-wordpress-5-6/" rel="noopener noreferrer"&gt;REST API Batch Framework&lt;/a&gt;. Next are the steps I took to use it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Registration of the meta fields in the REST API
&lt;/h2&gt;

&lt;p&gt;First I registered the custom meta field in the REST API using the &lt;a href="https://developer.wordpress.org/reference/functions/register_post_meta/" rel="noopener noreferrer"&gt;register_post_meta&lt;/a&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add_action( 'init', function() {
    register_post_meta(
        'post',
        'my_custom_field_name',
        [
            'single' =&amp;gt; true,
            'type' =&amp;gt; 'string',
            'show_in_rest' =&amp;gt; true,
        ]
    );
} );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The first argument I used here is &lt;code&gt;'post'&lt;/code&gt;, which means that the custom field is applied for items saved in the posts table (posts, pages and custom post types). Here you can use other entities like &lt;code&gt;'comment'&lt;/code&gt;, &lt;code&gt;'term'&lt;/code&gt; or &lt;code&gt;'user'&lt;/code&gt;. If the meta field is used in a custom post type, then the custom post type should support custom fields. During the &lt;a href="https://developer.wordpress.org/reference/functions/register_post_type/" rel="noopener noreferrer"&gt;custom post type registration&lt;/a&gt;, you can use the &lt;code&gt;supports&lt;/code&gt; field to add &lt;code&gt;custom-fields&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The second argument is &lt;code&gt;'my_custom_field_name'&lt;/code&gt; which is the key name used for the meta field.&lt;/li&gt;
&lt;li&gt;The last argument describes the meta field. In this example, the meta field has one value per post only, its type is string and its value is accessible via the REST API. Indeed, the value of the &lt;code&gt;'show_in_rest'&lt;/code&gt; key can be an array with the key &lt;code&gt;'schema'&lt;/code&gt; to describe its data structure in the REST API.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Using the Batch Framework to update meta fields of multiple posts in WordPress
&lt;/h2&gt;

&lt;p&gt;The React component uses the Batch Framework and it is in charge of doing the request to update the posts. It has a function to update the meta fields of multiple posts in WordPress using a single request. The request looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requests = [
    {
        path: '/wp/v2/posts/10',
        method: 'POST',
        body: {
            meta: {
                my_custom_field_name: 'hello world',
            },
        },
    },
    {
        path: '/wp/v2/posts/11',
        method: 'POST',
        body: {
            meta: {
                my_custom_field_name: 'lorem ipsum...',
            },
        },
    },
    {
        path: '/wp/v2/posts/12',
        method: 'POST',
        body: {
            meta: {
                my_custom_field_name: '123abc',
            },
        },
    }
];
apiFetch( {
    path: 'batch/v1',
    method: 'POST',
    data: { requests },
} )
    .then( response =&amp;gt; handleBatchResponse( response, requests ) )
    .catch( err =&amp;gt; console.log( err ) );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;apiFetch&lt;/code&gt; call use the next config object:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;path&lt;/code&gt; and the &lt;code&gt;method&lt;/code&gt; properties of the Batch Framework endpoint, &lt;code&gt;batch/v1&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt; respectively.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;data&lt;/code&gt; property is an object with the property &lt;code&gt;requests&lt;/code&gt; which contains an array with the configuration of each one of the requests we want to execute. Each configuration is an object with the required property &lt;code&gt;path&lt;/code&gt; and optionally the properties &lt;code&gt;method&lt;/code&gt;, &lt;code&gt;headers&lt;/code&gt; and &lt;code&gt;body&lt;/code&gt;. In this case, these are the configuration to make the requests to &lt;a href="https://developer.wordpress.org/rest-api/reference/posts/#update-a-post" rel="noopener noreferrer"&gt;the WordPress endpoint &lt;code&gt;POST /wp/v2/posts/&amp;lt;id&amp;gt;&lt;/code&gt;&lt;/a&gt; to update the posts.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Handling the response
&lt;/h2&gt;

&lt;p&gt;Finally here is how to handle the response of the request to update meta fields of multiple posts in WordPress. In the React component, I defined the next function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleBatchResponse = ( batchResponse, requests ) =&amp;gt; {
    batchResponse.responses.forEach( ( requestResponse, idx ) =&amp;gt; {
        // Get the data of the request related to the current response.
        const requestData = requests[idx];

        // Check if the response was not successful.
        if ( 200 !== requestResponse.status ) {
            // Show error message here.
        }
    } );
} );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The custom function &lt;code&gt;handleBatchResponse&lt;/code&gt; expects 2 parameters, the response of the batch request and the array of requests sent in the batch request. This function is called when the response of the request is received and parsed by the &lt;code&gt;apiFetch&lt;/code&gt; call. The response of the batch requests is an object with the property &lt;code&gt;responses&lt;/code&gt; which is an array of enveloped responses objects for each one of the requests sent in the batch request. Each enveloped response has the properties &lt;code&gt;status&lt;/code&gt;, &lt;code&gt;headers&lt;/code&gt; and &lt;code&gt;body&lt;/code&gt;. The order of the items in the &lt;code&gt;responses&lt;/code&gt; array corresponds to the order of the items in the &lt;code&gt;requests&lt;/code&gt; array sent in the batch request, so the first object in &lt;code&gt;batchResponses.responses&lt;/code&gt; is the response of the first object in the &lt;code&gt;requests&lt;/code&gt; array.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;It is possible to update meta fields of multiple posts in WordPress using a single REST requests. The REST API Batch Framework allows to run multiple requests at once in WordPress. However, take into account that it accepts up to 25 requests in a single batch. Additionally, the framework doesn’t support GET requests. Using parallel requests or &lt;a href="https://developer.wordpress.org/rest-api/using-the-rest-api/linking-and-embedding/" rel="noopener noreferrer"&gt;linking and embedding&lt;/a&gt; are the recommendation in this case.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/update-meta-fields-of-multiple-posts-in-wordpress-with-the-rest-api/" rel="noopener noreferrer"&gt;How to update meta fields of multiple posts in WordPress using a single REST request&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev" rel="noopener noreferrer"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>development</category>
      <category>wordpress</category>
      <category>restapi</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Prevent access to WooCommerce downloadable products in WPEngine</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Fri, 08 Oct 2021 13:20:07 +0000</pubDate>
      <link>https://dev.to/carlosguzman/prevent-access-to-woocommerce-downloadable-products-in-wpengine-111j</link>
      <guid>https://dev.to/carlosguzman/prevent-access-to-woocommerce-downloadable-products-in-wpengine-111j</guid>
      <description>&lt;p&gt;If you are using WPEngine, WooCommerce and you sell digital products, then you might have realized that your downloadable products are public to anyone. You can use &lt;a href="https://anchor.host/protecting-static-files-with-php-script-and-wp-engine/"&gt;redirect rules to protect access&lt;/a&gt; to WooCommerce downloadable products in WPEngine. But now it has a feature called &lt;a href="https://wpengine.com/support/web-rules/"&gt;web rules&lt;/a&gt; that allows you to block access in a similar way that .htaccess does.&lt;/p&gt;

&lt;p&gt;First go to the dashboard of your site in WPEngine. Then click on the &lt;strong&gt;Web rules&lt;/strong&gt; option at the bottom in the sidebar menu:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Q5egwYNv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2021/09/wpengine-site-sidebar-menu.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Q5egwYNv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2021/09/wpengine-site-sidebar-menu.jpg" alt="WPEngine site sidebar menu"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then you just need to create an access rule to block direct access to the WooCommerce downloadable products in WPEngine:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mzwZSROQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2021/09/protect-woocommerce-downloadable-products-in-wpengine.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mzwZSROQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2021/09/protect-woocommerce-downloadable-products-in-wpengine.jpg" alt="Protect WooCommerce downloadable products in wpengine"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When you are creating the new rule, use the next configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Order: 1 (or a lower value order than any rule that could interfere)
Action: Deny
IP: All
Condition type: URI
Condition Operator: Regex matches (~)
Condition value: wp-content/uploads/woocommerce_uploads/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This configuration blocks the direct access to the files in the WooCommerce uploads folder. When your downloadable products is bought, then WooCommerce gives a link to the customer. Then the customer uses this link to download the product.&lt;/p&gt;

&lt;p&gt;Do you need help with the configuration of your website? Don’t hesitate into &lt;a href="https://www.webilop.com/hire-a-wordpress-developer-now/"&gt;hire me now&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now that you have protected your files, let’s see what is the “issue”. The summarized explanation is that WPEngine uses &lt;a href="https://www.nginx.com/"&gt;Nginx&lt;/a&gt; instead Apache as web server. WooCommerce creates an .htaccess file in its upload folder. Apache uses it to block the access to the content in the folder. However, the .htaccess file doesn’t work in Nginx. This web server works in another way and it is configured in other way. Unfortunately, WooCommerce doesn’t have a way to make this configuration and only the administrator of the web server can setup the configuration and block the access. Before it was possible to &lt;a href="https://docs.easydigitaldownloads.com/article/683-protecting-file-downloads-on-wp-engine"&gt;prevent direct downloads in WPEngine&lt;/a&gt; using redirect rules. &lt;a href="https://wpengine.com/support/web-rules/"&gt;Now WPEngine has a feature named &lt;strong&gt;web rules&lt;/strong&gt;&lt;/a&gt; that allows us to make this configuration and block the access to some sections in our website easily.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/prevent-access-to-woocommerce-downloadable-products-in-wpengine/"&gt;Prevent access to WooCommerce downloadable products in WPEngine&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>development</category>
      <category>wordpress</category>
      <category>woocommerce</category>
      <category>wpengine</category>
    </item>
    <item>
      <title>Responsive dynamic background images in WordPress</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Mon, 19 Oct 2020 12:46:32 +0000</pubDate>
      <link>https://dev.to/carlosguzman/responsive-dynamic-background-images-in-wordpress-71j</link>
      <guid>https://dev.to/carlosguzman/responsive-dynamic-background-images-in-wordpress-71j</guid>
      <description>&lt;p&gt;The most common ways to show images in a website are using the HTML tags &lt;code&gt;&amp;lt;img&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;picture&amp;gt;&lt;/code&gt; or using the CSS property &lt;code&gt;background-image&lt;/code&gt;. There are &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images"&gt;attributes in the HTML tags to show different images&lt;/a&gt; based on the browser viewport. Or you can use &lt;a href="https://cloudfour.com/thinks/responsive-images-101-part-8-css-images/"&gt;media queries to show different images&lt;/a&gt; with background-image. You could find the article &lt;em&gt;&lt;a href="https://nystudio107.com/blog/the-css-background-image-property-as-an-anti-pattern"&gt;The CSS background-image property as an anti-pattern&lt;/a&gt;&lt;/em&gt; very interesting. If you are using background-image anyway, this article describe how to use it to have a responsive dynamic background images in WordPress.&lt;/p&gt;

&lt;p&gt;Nowadays one trend is to use eye-catching images at the top of articles and news in websites to draw the attention of visitors. Downloading images in a website is one of the main factors in the speed loading. Large images increase the quantity of data to download. Most of the traffic of websites is done through mobile devices. Optimize the loading of these images is important.&lt;/p&gt;

&lt;p&gt;WordPress has the field &lt;a href="https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/"&gt;featured image&lt;/a&gt; in to link a representative image with an article. Some websites use this image in the header of the article. The next solution also works if the image is not in the featured image field but in a custom field of the article.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Define the CSS breakpoints
&lt;/h2&gt;

&lt;p&gt;CSS breakpoints define the ranges of device screen width where the content responds in a certain way. In example, the framework &lt;a href="https://getbootstrap.com/docs/4.5/layout/overview/#responsive-breakpoints"&gt;Twitter Bootstrap defines 4 breakpoints and 5 ranges&lt;/a&gt;: extra small, small, medium, large and extra large.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Extra small screens: &amp;lt;576px&lt;/li&gt;
&lt;li&gt;Small screens: ≥576px&lt;/li&gt;
&lt;li&gt;Medium screens: ≥768px&lt;/li&gt;
&lt;li&gt;Large screens: ≥992px&lt;/li&gt;
&lt;li&gt;Extra large screens: ≥1200px&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Register image sizes for each screen width range
&lt;/h2&gt;

&lt;p&gt;Each screen width range defined by the CSS breakpoints requires to define the dimensions to show the image in the range. Let’s continue with the example of Twitter Bootstrap. We are using its &lt;a href="https://getbootstrap.com/docs/4.5/layout/overview/#containers"&gt;containers&lt;/a&gt; and we are displaying the image using the full width of the container, then we could define the next dimensions(WxH):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;576×350 for containers in extra small screens&lt;/li&gt;
&lt;li&gt;540×350 for containers in small screens&lt;/li&gt;
&lt;li&gt;720×350 for containers in medium screens&lt;/li&gt;
&lt;li&gt;960×400 for containers in large screens&lt;/li&gt;
&lt;li&gt;1140×400 for containers in extra large screens&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The WordPress function &lt;a href="https://developer.wordpress.org/reference/functions/add_image_size/"&gt;add_image_size&lt;/a&gt; registers images dimensions. WordPress creates a cropped version of the image for each registered dimension when an image is uploaded.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// register image sizes
add_image_size('header-image-xs', 576, 350);
add_image_size('header-image-sm', 540, 350);
add_image_size('header-image-md', 720, 350);
add_image_size('header-image-lg', 960, 400);
add_image_size('header-image-xl', 1140, 400);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Include the image in the theme template
&lt;/h2&gt;

&lt;p&gt;A WordPress theme has different templates for different kind of pages. In this example, we are displaying the images for the articles. Thus we edit the &lt;em&gt;single-post.php&lt;/em&gt; template to include the image.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ... content before the background image

&amp;lt;div class="site-content"&amp;gt;
  &amp;lt;div class="header-image-container"&amp;gt;
    // ... some content over the background image
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

// ... content after the background image
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Include the media queries
&lt;/h2&gt;

&lt;p&gt;When we show the image using background-image, then we need to use CSS media queries to display the images in a responsive way. We can use the WordPress hook &lt;a href="https://developer.wordpress.org/reference/hooks/wp_head/"&gt;wp_head&lt;/a&gt; to include the CSS code in the head of the HTML document. In the function attached to the hook, then we get the featured image of the article and build the media queries. At this point, we have defined the &lt;a href="http://include-image-in-theme"&gt;HTML structure&lt;/a&gt; and we know the CSS selector required to point to the element where the background-image is used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// print the background CSS rules
add_action('wp_head', function(){
  // link breakpoints and image sizes
  $images = [
    '0' =&amp;gt; 'header-image-xs',
    '576' =&amp;gt; 'header-image-sm',
    '768' =&amp;gt; 'header-image-md',
    '992' =&amp;gt; 'header-image-lg',
    '1200' =&amp;gt; 'header-image-xl',
  ];

  // check if the post/page has a featured image
  if (has_post_thumbnail()) {
    // get the thumbnail images
    array_walk($images, function(&amp;amp;$item) {
        $item = get_the_post_thumbnail_url(get_the_ID(), $item);
    });
    ?&amp;gt;
    &amp;lt;style&amp;gt;
    &amp;lt;?php foreach($args['images'] as $breakpoint =&amp;gt; $image_url): ?&amp;gt;
      &amp;lt;?php if ('0' == $breakpoint): ?&amp;gt;
      .site-content .header-image-container {
        background-image: url("&amp;lt;?= $image_url ?&amp;gt;");
      }
      &amp;lt;?php else; ?&amp;gt;
      @media (min-width: &amp;lt;?= $breakpoint ?&amp;gt;px) {
        .site-content .header-image-container {
          background-image: url("&amp;lt;?= $image_url ?&amp;gt;");
        }
      }
      &amp;lt;?php endif; ?&amp;gt;
    &amp;lt;?php endforeach; ?&amp;gt;
    &amp;lt;/style&amp;gt;
    &amp;lt;?php
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that’s all. You can find &lt;a href="https://wpexperiments.carlosguzman.dev/responsive-background-images/"&gt;here&lt;/a&gt; a demo of this approach:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://wpexperiments.carlosguzman.dev/responsive-background-images/"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cGOlDspi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/10/responsive-bg-images-demo-1024x1002.jpg" alt="Responsive dynamic background images in WordPress"&gt;&lt;/a&gt;Demo of responsive dynamic background images in WordPress&lt;/p&gt;

&lt;p&gt;You might found useful the library &lt;a href="https://github.com/c24o/wp-responsive-background-image"&gt;wp-responsive-background-image&lt;/a&gt;. I created this library which offer an interface with a couple of methods to allow add the background rules easily. It uses the approach mentioned before to insert responsive dynamic background images in WordPress.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/responsive-dynamic-background-images-in-wordpress/"&gt;Responsive dynamic background images in WordPress&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>development</category>
      <category>wordpress</category>
      <category>backgroundimage</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Datetime or Timestamp: readability matters</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Fri, 12 Jun 2020 20:39:48 +0000</pubDate>
      <link>https://dev.to/carlosguzman/datetime-or-timestamp-readability-matters-21ig</link>
      <guid>https://dev.to/carlosguzman/datetime-or-timestamp-readability-matters-21ig</guid>
      <description>&lt;p&gt;When you are designing the schema of the database for your project and you need to store dates and times, then the question about what data type to use appears. Recently, I started a project to build a REST API and I used timestamps, a total mistake. Later, I was applying to a job and again I decided to use timestamps in the project to show my skills. During the interview, the recruiter asked me why I decided to use timestamps and I realized that I didn’t make any analysis for this decision. I just wanted to try it…what a mistake.&lt;/p&gt;

&lt;p&gt;After this, I decided to investigate the pros and cons for the different options to store dates in a database. There are multiple articles about this topic. I want to highlight this &lt;a href="https://www.vertabelo.com/blog/what-datatype-should-you-use-to-represent-time-in-mysql-we-compare-datetime-timestamp-and-int/"&gt;article where it is explained with details, examples and benchmarks using MySQL&lt;/a&gt;. Next is a too short summary about the article:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using &lt;em&gt;DATETIME&lt;/em&gt; allows to make SQL queries using functions related to dates(i.e: WEEKDAY in MySQL) in the SQL server. It allows to use dates from year 1000 to 9999. Queries over &lt;em&gt;DATETIME&lt;/em&gt; are faster than queries over &lt;em&gt;TIMESTAMP&lt;/em&gt;. The format used to print the &lt;em&gt;DATETIME&lt;/em&gt; is user friendly and legible.&lt;/li&gt;
&lt;li&gt;Using &lt;em&gt;TIMESTAMP&lt;/em&gt; also allows to make SQL queries using functions related to dates. It allows dates until 2038 only. &lt;em&gt;TIMESTAMP&lt;/em&gt; is lighter and it saves 1 byte of storage compared with &lt;em&gt;DATETIME&lt;/em&gt;. The format used to print the &lt;em&gt;TIMESTAMP&lt;/em&gt; is user friendly and legible.&lt;/li&gt;
&lt;li&gt;Using &lt;em&gt;UNSIGNED INT&lt;/em&gt; allows dates until 2106. It is not possible to use CURRENT_TIMESTAMP with this data type. SQL queries over INT are much faster than &lt;em&gt;DATETIME&lt;/em&gt; and &lt;em&gt;TIMESTAMP&lt;/em&gt;. To use date functions, the integer should be converted to a date(using function FROM_UNIXTIME in MySQL). In this case the SQL queries are slower than &lt;em&gt;DATETIME&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One of the disadvantages with &lt;em&gt;TIMESTAMP&lt;/em&gt; is the limit of 2038. Personally, I think that the SQL servers will change this in order to preserve compatibility with existing software using this datatype. It is not the same with &lt;em&gt;INT&lt;/em&gt; because it is a datatype not intended to be used for dates. However there are integer types using more bytes of storage like &lt;em&gt;BIGINT&lt;/em&gt; in MySQL.&lt;/p&gt;

&lt;p&gt;After my experience using timestamps in a REST API, definitely I will use &lt;em&gt;DATETIME&lt;/em&gt; in next projects unless performance and storage are critical. When you are debugging, readability matters. When you see a bunch of numbers that not make sense, then you need to expend time converting those numbers to readable dates. Also working in the frontend, sometimes I needed to understand why I was getting those dates and then again it was stressful to see unintelligible numbers in the API response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--z6ebP7QL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/06/timestamps-in-api-response.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--z6ebP7QL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/06/timestamps-in-api-response.png" alt="datetime or timestamp: readability matters"&gt;&lt;/a&gt;Timestamps in a REST API response&lt;/p&gt;

&lt;p&gt;In my opinion, using &lt;em&gt;UNSIGNED INT&lt;/em&gt; has sense if the performance of the app is critical &lt;strong&gt;AND&lt;/strong&gt; you have one or multiple queries that doesn’t require to use date functions and they are in processes that run frequently in the app.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/datetime-or-timestamp-readability-matters/"&gt;Datetime or Timestamp: readability matters&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>development</category>
      <category>database</category>
      <category>debugging</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Running PHPUnit tests in a WordPress plugin with Docker</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Sat, 25 Apr 2020 15:16:24 +0000</pubDate>
      <link>https://dev.to/carlosguzman/running-phpunit-tests-in-a-wordpress-plugin-with-docker-2dm1</link>
      <guid>https://dev.to/carlosguzman/running-phpunit-tests-in-a-wordpress-plugin-with-docker-2dm1</guid>
      <description>&lt;p&gt;There are several resource about running PHPUnit tests in a WordPress plugin with Docker. Here I want to share how I do it. You can find &lt;a href="https://github.com/c4rlosguzm4n/wordpress-docker-dev-environment"&gt;the configuration files in Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I explain how to create the development instance in 5 steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The folder structure&lt;/li&gt;
&lt;li&gt;Build a docker image to host the WordPress site&lt;/li&gt;
&lt;li&gt;Configure the testing environment in your WordPress container&lt;/li&gt;
&lt;li&gt;Docker compose to launch the containers&lt;/li&gt;
&lt;li&gt;Run tests while coding&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  1. The folder structure
&lt;/h2&gt;

&lt;p&gt;Let’s start creating a folder to host all the docker configuration files and the WordPress code including the plugin source files.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://carlosguzman.dev/wp-content/uploads/2020/04/console-project-wp-docker.png"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--d_pd7qer--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/04/console-project-wp-docker-1024x404.png" alt="project folder structure with configuration of wordpress and docker"&gt;&lt;/a&gt;How the folder will look at the end&lt;/p&gt;

&lt;p&gt;This is a picture of how the folder will look at the end. &lt;em&gt;my-project&lt;/em&gt; is the root folder of the project. The &lt;em&gt;wordpress-image&lt;/em&gt; folder contains the Dockerfile and an the entry point script for the WordPress environment. The &lt;em&gt;wordpress&lt;/em&gt; folder contains the files of WordPress and the plugin to work on.&lt;/p&gt;

&lt;p&gt;I use to run the wp-cli tool as the www-data user instead as root. So I assign www-data as group and my user as owner of the &lt;em&gt;wp-content&lt;/em&gt; folder inside the &lt;em&gt;wordpress&lt;/em&gt; folder. Then I give write access to the group to the &lt;em&gt;wp-content&lt;/em&gt; folder. In this way, www-data is able to write on those files without problem and I can edit the files from outside Docker with my user.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Build a docker image to host the WordPress site
&lt;/h2&gt;

&lt;p&gt;I built a custom Docker image based on &lt;a href="https://hub.docker.com/_/wordpress/"&gt;the official Docker image for WordPress&lt;/a&gt;. The purpose of this custom image is to setup the development instance to run the unit tests automatically. This file is placed inside the &lt;em&gt;wordpress-image&lt;/em&gt; folder. Next is the Dockerfile of the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#1. Docker base image
FROM wordpress:php7.4-apache

#2. Install WP-cli and dependencies to run it
RUN apt-get update \
    &amp;amp;&amp;amp; apt-get install -y \
      less \
      subversion \
      sudo \
      default-mysql-client-core \
    &amp;amp;&amp;amp; curl https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar -o /usr/local/bin/wp \
    &amp;amp;&amp;amp; chmod +x /usr/local/bin/wp

#3. Create the files for the testing environment
RUN \
    #3.1 Install phpunit
    curl -L https://phar.phpunit.de/phpunit-7.phar -o /tmp/phpunit \
    &amp;amp;&amp;amp; chmod a+x /tmp/phpunit \
    #3.2 Install wordpress
    &amp;amp;&amp;amp; cp -r /usr/src/wordpress /tmp/wordpress \
    &amp;amp;&amp;amp; curl https://raw.github.com/markoheijnen/wp-mysqli/master/db.php -o /tmp/wordpress/wp-content/db.php \
    #3.3 Install the testing libraries
    &amp;amp;&amp;amp; svn co --quiet https://develop.svn.wordpress.org/tags/5.3.2/tests/phpunit/includes/ /tmp/wordpress-tests-lib/includes \
    &amp;amp;&amp;amp; svn co --quiet https://develop.svn.wordpress.org/tags/5.3.2/tests/phpunit/data/ /tmp/wordpress-tests-lib/data \
    #3.4 set owner and permissions
    &amp;amp;&amp;amp; chown -R www-data:www-data /tmp/wordpress \
    &amp;amp;&amp;amp; chown -R www-data:www-data /tmp/wordpress-tests-lib

#4. Copy the script to create the testing environment when the container is started
COPY init-testing-environment.sh /usr/local/bin/

#5. Run the script and send as an argument the command to run the apache service
ENTRYPOINT ["init-testing-environment.sh"]
CMD ["apache2-foreground"]

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The section #1 in the Dockerfile shows the base image used. In this case the container will run WordPress in a Apache web server running PHP 7.4. You can see other options of &lt;a href="https://hub.docker.com/_/wordpress/"&gt;images for WordPress in Docker Hub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The script installs &lt;a href="https://wp-cli.org/"&gt;wp-cli&lt;/a&gt; in the section #2 . This tool is required to create the testing environment to run unit tests with WordPress easily. I run the wp-cli as the www-data user using the sudo package. Subversion downloads the testing libraries in the next section of the script. The mysql client package is used to check the connection to the database in the configuration of the testing environment later.&lt;/p&gt;

&lt;p&gt;The section #3 creates the files for the testing environment. It is not required to download these files again when the container is started. In this way, there is a saving of data downloaded but mainly the container starts faster. It creates the WordPress instance for testing and download the libraries used by WordPress to run PHPUnit. This section does part of the job of &lt;code&gt;wp scaffold plugin-tests&lt;/code&gt; which will be invoked when the container is launched.&lt;/p&gt;

&lt;p&gt;In sections #4 and #5, the entry point script is copied and its parameters are configured. More about this script follows in the next section.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Configure the testing environment in your WordPress container
&lt;/h2&gt;

&lt;p&gt;In the Dockerfile above, when the container starts, it runs a custom script instead running the Apache service. This script basically finishes the testing environment if it is not complete yet before launching the Apache service. This script is based on the steps to create &lt;a href="https://make.wordpress.org/cli/handbook/plugin-unit-tests/"&gt;a testing environment in WordPress&lt;/a&gt; and it is placed inside the &lt;em&gt;wordpress-image&lt;/em&gt; folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/bin/bash

#1. check if the database is ready
cd /var/www/html/
if ! (sudo -u www-data -- wp db check)
then
    # wait a moment for the database container
    sleep 1
    exit 1;
fi

#2. check if wordpress is already installed/configured
if (sudo -u www-data -- wp core is-installed)
then
    #3. init the testing instance
    sudo -u www-data -- wp scaffold plugin-tests $WP_PLUGIN_FOLDER --force
    cd wp-content/plugins/$WP_PLUGIN_FOLDER &amp;amp;&amp;amp; sudo -u www-data -- bash -c "./bin/install-wp-tests.sh $WP_TESTS_DB_NAME $WORDPRESS_DB_USER $WORDPRESS_DB_PASSWORD $WORDPRESS_DB_HOST latest true"   
fi

#4. back to the root WP folder
cd /var/www/html/

#5. execute the entrypoint of the parent image
bash docker-entrypoint.sh "$@"

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In the section #1 of the script, it checks if the WordPress instance have connection to the database. If it is not the case, then it finish with error core but it sleeps for a bit first to give some time to the database to be ready.&lt;/p&gt;

&lt;p&gt;The script checks if the WordPress instance is already configured in the section #2. The configuration of the testing environment requires the WordPress site to be already installed. If it is not active, then it skips the section #3 and launches the container.&lt;/p&gt;

&lt;p&gt;The section #3 uses &lt;code&gt;wp scaffold plugin-tests&lt;/code&gt; to create the configuration for the environment to run PHPUnit. One of the configuration files is install-wp-tests.sh. The install-wp-tests.sh script creates the WordPress instance in the tmp folder by default. I already created this instance in that folder in the previous step. The script doesn’t download the WordPress files again because the WordPress files are already in the folder. The docker compose file, explained in the next step, passes the values for the variables like &lt;em&gt;WP_TEST_DB_NAME&lt;/em&gt; or &lt;em&gt;WORDPRESS_DB_USER&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The last 2 sections in the script just move back to the main folder and executes the default entry point of the WordPress Docker image.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Docker compose to launch the containers
&lt;/h2&gt;

&lt;p&gt;The next step is to create a docker file to run easily the backend and the database containers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: '3'

services:
    db:
        image: mysql:5.7
        volumes:
            - db-data:/var/lib/mysql
        ports:
            - "3360:3306"
        environment:
            MYSQL_ROOT_PASSWORD: password
            MYSQL_DATABASE: wordpress
            MYSQL_USER: wordpress
            MYSQL_PASSWORD: password

    wordpress:
        depends_on:
            - db
        build: ./wordpress-image
        ports:
            - 8080:80
        restart: on-failure
        volumes:
            - ./wordpress:/var/www/html
        environment:
            WORDPRESS_DB_HOST: db:3306
            WORDPRESS_DB_USER: wordpress
            WORDPRESS_DB_PASSWORD: password
            WORDPRESS_DB_NAME: wordpres
            WP_TESTS_DB_NAME: wptests
            WP_PLUGIN_FOLDER: my-plugin-folder

volumes:
    db-data:
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The first service in the docker compose file launches the container for the database. It is based on the MySQL Docker image. The values for passwords, database and user names are values that you configure at your wish.&lt;/p&gt;

&lt;p&gt;The second service is used for the WordPress container. It is based on the custom WordPress image that I created in the step 2 explained previously. This container uses a volume for the root folder of the WordPress instance. The values used to configure the database connection of the WordPress instance should match the values used for the database container. The official WordPress Docker image doesn’t use the variables &lt;em&gt;WP_TEST_DB_NAME&lt;/em&gt; and &lt;em&gt;WP_PLUGIN_FOLDER&lt;/em&gt;. The script explained in the step 3 uses these custom variables. The first variable is the database name used to run the PHPUnit tests. The second variable is the name of the plugin folder under development and testing.&lt;/p&gt;

&lt;p&gt;Last to highlight is the directive &lt;em&gt;restart&lt;/em&gt; with value on-failure that allows this container to try to be launched again if the script to create the testing instance fails or if there is another problem starting the container. In example, if the database is not ready as we saw in the previous step.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Run tests while coding
&lt;/h2&gt;

&lt;p&gt;The development and testing environment is ready after all this configuration. First go to the project folder and lunch the containers using &lt;code&gt;docker-composer up&lt;/code&gt;. The testing environment will not be configured until you have configured the WordPress site. After lunching the containers by first time, you would need to visit &lt;em&gt;localhost:8080&lt;/em&gt; in your browser to setup the WordPress site.&lt;/p&gt;

&lt;p&gt;The next time you lunch your container, if you have already setup the WordPress site, then the testing environment will be configured automatically. Then you need a bash session in the WordPress container to run the tests:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WPtMKUvi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/04/docker-wp-plugin-environment-bash-1024x556.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WPtMKUvi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/04/docker-wp-plugin-environment-bash-1024x556.png" alt="bash session in the docker container"&gt;&lt;/a&gt;Bash session in the WordPress container&lt;/p&gt;

&lt;p&gt;An alternative is to use composer and install PHPUnit in the plugin’s source code. In the step 2, I already downloaded it and place it in the &lt;em&gt;tmp&lt;/em&gt; folder:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1UlNfKwJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/04/docker-wp-plugin-environment-run-tests-1024x556.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1UlNfKwJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/04/docker-wp-plugin-environment-run-tests-1024x556.png" alt="PHPUnit tests in a WordPress plugin with Docker"&gt;&lt;/a&gt;PHPUnit tests results&lt;/p&gt;

&lt;p&gt;If you want to run your tests automatically while you are coding, you could take a look to a previous article where I explain &lt;a href="https://carlosguzman.dev/running-phpunit-tests-automatically/"&gt;how to run tests automatically using the bash script watch-and-do&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;So this is the way I run PHPUnit tests in a WordPress plugin with Docker. You can find &lt;a href="https://github.com/c4rlosguzm4n/wordpress-docker-dev-environment"&gt;these configuration files in Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/running-phpunit-tests-in-a-wordpress-plugin-with-docker/"&gt;Running PHPUnit tests in a WordPress plugin with Docker&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>wordpress</category>
      <category>docker</category>
      <category>phpunit</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Running PHPUnit tests automatically</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Sun, 01 Mar 2020 17:30:52 +0000</pubDate>
      <link>https://dev.to/carlosguzman/running-phpunit-tests-automatically-1ccn</link>
      <guid>https://dev.to/carlosguzman/running-phpunit-tests-automatically-1ccn</guid>
      <description>&lt;p&gt;I have found test-driven development(TDD) a very interesting development methodology. Just recently I have been applying this in the development of a WordPress plugin. One of the issues during the development was wasting time launching tests manually after making changes to the code. You don’t know what you could do and achieve in those few seconds. Running PHPUnit tests automatically became important to save those precious seconds. In this post I want to share how to run tests automatically when a change in code is detected.&lt;/p&gt;

&lt;p&gt;There are multiple options that you could use for running phpunit tests automatically. In example, &lt;a href="https://github.com/spatie/phpunit-watcher"&gt;phpunit-watcher&lt;/a&gt; is a PHP script that you can install in your project easily through composer. In my case, I created &lt;a href="https://github.com/c4rlosguzm4n/watch-and-do"&gt;watch-and-do&lt;/a&gt;, a bash script and it is now hosted in Github. Honestly I think I didn’t google it well and I didn’t find phpunit-watcher before. But let’s say that I wanted to learn and create a bash script.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bciXTYj3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/02/console-running-phpunit-automatically-1024x610.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bciXTYj3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/02/console-running-phpunit-automatically-1024x610.jpg" alt="console running phpunit automatically"&gt;&lt;/a&gt;Running PHPUnit tests automatically with watch-and-do&lt;/p&gt;

&lt;p&gt;A testing environment with WordPress configured and running is required in order to run tests for the WordPress plugin. In the official documentation of WordPress, you can find &lt;a href="https://make.wordpress.org/cli/handbook/plugin-unit-tests/"&gt;how to create the testing environment for your WordPress plugin&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The bash script is based on &lt;a href="https://linux.die.net/man/1/inotifywait"&gt;inotifywait&lt;/a&gt; to watch and detect changes in the code. This tool can use some filters to notify when a file is created, modified, deleted or moved only:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# listen for changes
inotifywait -m -r -q -e modify -e create -e delete -e move --format "%w%f %e" $WATCHDIR
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;When a change is detected, then the script waits for a couple of seconds before launching the tests. Sometimes I am editing multiple files and then I save all of them. With a delay in the script, the test are launched after the last saving instead launching the tests after saving each file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# increase the stock
echo $(( $(cat $STOCK_FILE) + 1 )) &amp;gt; $STOCK_FILE

# sleep for a moment while more changes are detected
sleep $CHANGES_DETECTION_SLEEP

# decrease stock
echo $(( $(cat $STOCK_FILE) - 1 )) &amp;gt; $STOCK_FILE

# if stock is empty (this discard multiple execution)
if [$(cat $STOCK_FILE) -eq 0]
then
    # run tests
    run_tests $@
fi
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;It is important to run the tests in a new process and store its PID because it is used to stop the process if required. Before launching the tests, it is possible that the tests are under execution due to a previous modification of a file. In order to not get conflicts and to not get a mess in the console, it is a good idea to stop the current execution of the tests. We stop the tests using the PID of the process and the kill command with signal SIGTERM. The tests are not stopped immediately, so it is important to wait until they have been stopped:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while [$LASTPID] &amp;amp;&amp;amp; [$LASTPID -gt 0] &amp;amp;&amp;amp; (ps -p $LASTPID &amp;gt; /dev/null)
do
    # kill previous testing
    if [$KILLING -eq 0]
    then
        KILLING=1    
        kill -SIGTERM $LASTPID
    fi

    # wait until previous tests are finished
    echo "Wait while current tests are stopped..."
    sleep $TESTS_KILLING_SLEEP
done
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Finally, when previous tests have been stopped, the new tests are lunched and the PID of its process is stored. The command to run the tests is passed as an argument to the script. In this way the script is not attached to how phpunit is configured in the system:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# execute tests
echo "Running command: $@"
$@ &amp;amp;

# store the pid of the thread running the tests
echo $! &amp;gt; $PID_FILE
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Using the script requires as arguments the folder to watch and the command to run the tests:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ ./watch-and-do my-base-folder phpunit -v
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;As mentioned before, this script is just an alternative to other tools to watch for changes in your code and run the tests automatically. This bash script is open source and you can find it in Github as &lt;a href="https://github.com/c4rlosguzm4n/watch-and-do"&gt;watch-and-do&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/running-phpunit-tests-automatically/"&gt;Running PHPUnit tests automatically&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>wordpress</category>
      <category>debugging</category>
      <category>phpunit</category>
      <category>testing</category>
    </item>
    <item>
      <title>How to see the error logs in WordPress with Docker in Linux</title>
      <dc:creator>Carlos Guzmán</dc:creator>
      <pubDate>Fri, 24 Jan 2020 17:47:42 +0000</pubDate>
      <link>https://dev.to/carlosguzman/how-to-see-the-error-logs-in-wordpress-with-docker-in-linux-12al</link>
      <guid>https://dev.to/carlosguzman/how-to-see-the-error-logs-in-wordpress-with-docker-in-linux-12al</guid>
      <description>&lt;p&gt;Recently I was working in the development of a WordPress plugin and I didn’t find an easy way to see the error logs in WordPress with Docker. I started to read and learn about Docker some few time ago. I created a WordPress development instance using &lt;a href="https://hub.docker.com/_/wordpress"&gt;the official Docker image for WordPress in Docker Hub&lt;/a&gt;. In some cases, you want to see the log of errors and do not activate the debug mode in WordPress. In example, a plugin can generate warnings that make difficult to debug and that could break responses for Ajax requests in your site.&lt;/p&gt;

&lt;p&gt;My first attempt to see the error logs was to login in a bash session it the Docker container. Then I searched for the error log file but the errors are sent to the I/O stream STDERR by default.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nVOoNyJl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/default-error-logs-wordpress-docker.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nVOoNyJl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/default-error-logs-wordpress-docker.jpg" alt="Default configuration of error logs for WordPress with Docker"&gt;&lt;/a&gt;Default configuration of error logs for WordPress with Docker&lt;/p&gt;

&lt;p&gt;Instead to create a custom image to change this configuration, I tried with the &lt;a href="https://docs.docker.com/engine/reference/commandline/logs/"&gt;Docker cli tool to access to the logs of the container&lt;/a&gt;. Using &lt;code&gt;docker logs ID_CONTAINER&lt;/code&gt;, I was able to see the logs of the web server. It was progress but it wasn’t what I want. I got all logs entries of the web server including access and warning entries. It would be difficult to spot the error entries easily in a website loading multiple resources and doing multiple Ajax requests.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DhL9Dt1r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/console-wordpress-docker-logs.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DhL9Dt1r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/console-wordpress-docker-logs.jpg" alt="Show logs of the Docker WordPress image container."&gt;&lt;/a&gt;Show logs of the Docker WordPress image container.&lt;/p&gt;

&lt;h2&gt;
  
  
  The solution
&lt;/h2&gt;

&lt;p&gt;If we discard the output sent to the standard stream, then the access entries are gone. So using &lt;code&gt;docker logs -f ID_CONTAINER &amp;gt;/dev/null&lt;/code&gt;, we get only the entries sent to the error stream. Most of the entries here are the useful entries for debugging, they are the warning and error messages. The option -f in docker logs command is to follow and refresh automatically the logs in the console.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZMWkZYWO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/console-wordpress-docker-logs-without-access-entries.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZMWkZYWO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/console-wordpress-docker-logs-without-access-entries.jpg" alt=""&gt;&lt;/a&gt;Show entries sent to the error stream only&lt;/p&gt;

&lt;h3&gt;
  
  
  Extra tip
&lt;/h3&gt;

&lt;p&gt;If you want to see the error messages only without changing the error reporting directive, you can use the &lt;em&gt;grep&lt;/em&gt; tool to filter the other entries. Using &lt;code&gt;docker logs -f ID_CONTAINER 2&amp;gt;&amp;amp;1 &amp;gt;/dev/null | grep -i error&lt;/code&gt;, the entries are filtered to display only the lines with the error word in them. This command replaces the output of the standard stream with the output of the error stream. Then &lt;em&gt;grep&lt;/em&gt; filters the content. The option -i in the &lt;em&gt;grep&lt;/em&gt; command is to be case insensitive in the search.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gOwBS3Zc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/console-wordpress-docker-logs-only-errors.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gOwBS3Zc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://carlosguzman.dev/wp-content/uploads/2020/01/console-wordpress-docker-logs-only-errors.jpg" alt="Show only error logs of WordPress with Docker"&gt;&lt;/a&gt;Show only error logs of WordPress with Docker&lt;/p&gt;

&lt;p&gt;Maybe it isn’t the most elegant but at least it is an effective way to see the error logs in WordPress with Docker.&lt;/p&gt;

&lt;p&gt;The post &lt;a href="https://carlosguzman.dev/how-to-see-the-error-logs-in-wordpress-with-docker-in-linux/"&gt;How to see the error logs in WordPress with Docker in Linux&lt;/a&gt; appeared first on &lt;a href="https://carlosguzman.dev"&gt;Carlos Guzman&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>wordpress</category>
      <category>debugging</category>
      <category>docker</category>
      <category>linux</category>
    </item>
  </channel>
</rss>
