{"id":2114,"date":"2022-11-22T23:03:00","date_gmt":"2022-11-22T16:03:00","guid":{"rendered":"https:\/\/wptips.dev\/?p=2114"},"modified":"2023-04-27T21:29:32","modified_gmt":"2023-04-27T14:29:32","slug":"responsive-cover-block","status":"publish","type":"post","link":"https:\/\/pixelstudio.id\/blog\/responsive-cover-block\/","title":{"rendered":"How to Create Responsive Cover Block? (Updated 2023)"},"content":{"rendered":"\n<p>One basic feature that is lacking from Gutenberg&#8217;s Cover block is setting different images for desktop and mobile.<\/p>\n\n\n\n<p>In this article, we will show<strong> two methods<\/strong> to do it: Simple and Advanced.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Simple Method: Custom Style<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"411\" src=\"https:\/\/pixelstudio.id\/blog\/wp-content\/uploads\/2022\/03\/rescover-custom-styles.jpg\" alt=\"\" class=\"wp-image-2125\" srcset=\"https:\/\/pixelstudio.id\/blog\/wp-content\/uploads\/2022\/03\/rescover-custom-styles.jpg 750w, https:\/\/pixelstudio.id\/blog\/wp-content\/uploads\/2022\/03\/rescover-custom-styles-480x263.jpg 480w\" sizes=\"auto, (max-width: 750px) 100vw, 750px\" \/><\/figure>\n\n\n\n<p>Create two custom styles: &#8220;Desktop Only&#8221; and &#8220;Mobile Only&#8221;.<\/p>\n\n\n\n<p>Then<strong> create two Cover blocks<\/strong>, each having its respective style. This way you can set different image for the one appearing in Desktop and Mobile.<\/p>\n\n\n\n<p>It&#8217;s not pretty, but it works!<\/p>\n\n\n\n<p>Here&#8217;s the code to register custom styles and the CSS:<\/p>\n\n\n\n<pre title=\"functions.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">add_action('init', 'my_register_cover_styles');\nadd_action('wp_enqueue_scripts', 'my_enqueue_cover_assets', 99);\n\nfunction my_register_cover_styles() {\n  register_block_style('core\/cover', [\n    'name' =&gt; 'desktop-only',\n    'label' =&gt; 'Desktop Only',\n  ]);\n\n  register_block_style('core\/cover', [\n    'name' =&gt; 'mobile-only',\n    'label' =&gt; 'Mobile Only',\n  ]);\n}\n\nfunction my_enqueue_cover_assets() {\n  $dir = get_stylesheet_directory_uri() . '\/css';\n  wp_register_style('my-cover', $dir . '\/my-cover.css', false);\n}<\/code><\/pre>\n\n\n\n<pre title=\"css\/my-cover.css\" class=\"wp-block-code\"><code lang=\"css\" class=\"language-css\">@media (max-width: 768px) {\n  .wp-block-cover.is-style-desktop-only {\n    display: none;\n  }\n}\n\n@media (min-width: 767px) {\n  .wp-block-cover.is-style-mobile-only {\n    display: none;\n  }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Advanced Method: Custom Control<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"455\" src=\"https:\/\/pixelstudio.id\/blog\/wp-content\/uploads\/2022\/03\/rescover-custom-control.jpg\" alt=\"\" class=\"wp-image-2124\" srcset=\"https:\/\/pixelstudio.id\/blog\/wp-content\/uploads\/2022\/03\/rescover-custom-control.jpg 750w, https:\/\/pixelstudio.id\/blog\/wp-content\/uploads\/2022\/03\/rescover-custom-control-480x291.jpg 480w\" sizes=\"auto, (max-width: 750px) 100vw, 750px\" \/><\/figure>\n\n\n\n<p>Use JavaScript to add new control into the Cover block as shown above. This <strong>looks more professional<\/strong>, although quite complex to implement.<\/p>\n\n\n\n<p>Our goal is to wrap the image in a <code>&lt;picture&gt;<\/code>. This way, the browser will not load the desktop image on mobile and vice versa.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"html\" class=\"language-html\">&lt;!-- BEFORE --&gt;\n\n&lt;div class=\"wp-block-cover\"&gt;\n  &lt;img class=\"wp-block-cover__image-background\" src=\"...\"&gt;\n  ...\n&lt;\/div&gt;\n\n&lt;!-- AFTER --&gt;\n\n&lt;div class=\"wp-block-cover\"&gt;\n  &lt;picture&gt;\n    &lt;source srcset=\"...\" media=\"(max-width:767px)\"&gt;\n    &lt;img class=\"wp-block-cover__image-background\" src=\"...\"&gt;\n  &lt;\/picture&gt;\n  ...\n&lt;\/div&gt;<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>STEP 1: The JavaScript<\/strong><\/p>\n\n\n\n<p>Here we have <code>my-cover.js<\/code>. We won&#8217;t explain the syntax since it&#8217;s quite complex. If you want to learn from the basics, check out our <a rel=\"noreferrer noopener\" href=\"https:\/\/pixelstudio.id\/blog\/custom-block-without-plugin\/\" data-type=\"URL\" data-id=\"https:\/\/pixelstudio.id\/blog\/custom-block-without-plugin\/\" target=\"_blank\">Gutenberg Tutorial<\/a>.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/hrsetyono\/7c756e46b1d1fc0c902950b7d0deae75.js\"><\/script>\n\n\n\n<p>Then, enqueue the script. Change the directory according to your folder structure:<\/p>\n\n\n\n<pre title=\"functions.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">add_action('enqueue_block_editor_assets', 'enqueue_responsive_cover', 100);\n\nfunction enqueue_responsive_cover() {\n  $dir = get_stylesheet_directory_uri() . '\/js';\n  wp_enqueue_script('my-cover', $dir . '\/my-cover.js', [ 'wp-blocks', 'wp-dom' ] , null, true);\n}<\/code><\/pre>\n\n\n\n<p>Now check out the Cover block in Editor. Does the Mobile Upload section show up?<\/p>\n\n\n\n<p><strong>A common mistake<\/strong> is enqueuing the wrong directory. Open the browser&#8217;s console to see whether there is a 404 error for the JS file.<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>STEP 2: Modify Rendering Function<\/strong><\/p>\n\n\n\n<p>We will filter the rendering method and use Regex to wrap the image in <code>&lt;picture&gt;<\/code>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p><strong>(Update 2023)<\/strong> As of latest WordPress, if you set the Cover to &#8220;Fixed Background&#8221;, the <code>&lt;img&gt;<\/code> will be replaced with <code>&lt;div role=\"img\"&gt;<\/code>. That means we can no longer uses <code>&lt;picture&gt;<\/code>.<\/p><p>The code below has conditional to check that. If using <code>&lt;div&gt;<\/code>, it will add extra CSS variable instead of wrapping it in <code>&lt;picture&gt;<\/code><\/p><\/blockquote>\n\n\n\n<pre title=\"functions.php\" class=\"wp-block-code\"><code lang=\"php\" class=\"language-php\">add_filter('render_block_core\/cover', 'my_responsive_cover_render', 10, 2);\n\nfunction my_responsive_cover_render($content, $block) {\n  \/\/ If has mobile image\n  if (isset($block['attrs']['mobileImageURL'])) {\n    $image = $block['attrs']['mobileImageURL'];\n\n    preg_match('\/&lt;div role=\"img\"\/', $content, $is_fixed);\n\n    \/\/ If fixed background, add CSS variable\n    if ($is_fixed) {\n      $content = preg_replace(\n        '\/(&lt;div role=\"img\".+style=\".+)(\"&gt;)\/Ui',\n        \"$1;--mobileImageURL:url({$image});$2\",\n        $content\n      );\n    }\n    \/\/ If not fixed, wrap in &lt;picture&gt;\n    else {\n      $content = preg_replace(\n        '\/&lt;img class=\"wp-block-cover__image.+\\\/&gt;\/Ui',\n        \"&lt;picture&gt;&lt;source srcset='{$image}' media='(max-width:767px)'&gt;$0&lt;\/picture&gt;\",\n        $content\n      );\n    }\n  }\n\n  return $content;\n}<\/code><\/pre>\n\n\n\n<p>Then add this in your CSS to replace the background-image on mobile:<\/p>\n\n\n\n<pre title=\"css\" class=\"wp-block-code\"><code lang=\"css\" class=\"language-css\">@media (max-width:768px) {\n  .wp-block-cover__image-background[style*=\"--mobileImageURL\"] {\n    background-image: var(--mobileImageURL) !important;\n  }\n}<\/code><\/pre>\n\n\n\n<p>Done! Try resizing your browser&#8217;s window and you will see the image changing when it reaches the breakpoint.<\/p>\n\n\n\n<p>Note that this setting <strong>only affect the frontend<\/strong>. It won&#8217;t be applied in the admin editor.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p><strong>So which method to choose?<\/strong><\/p>\n\n\n\n<p>If it&#8217;s your personal website, using the Simple method is fine.<\/p>\n\n\n\n<p>But for the client website, it will look more professional if you use the Advanced method. It&#8217;s easier to edit and less prone to mistakes too.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Let me know if you have any question in the comment below. Thank you for reading.<\/p><\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>Want to have a different image for the Cover block on Desktop and Mobile? Visit us to learn how.<\/p>\n","protected":false},"author":1,"featured_media":2127,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-2114","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-gutenberg"],"blocksy_meta":"","_links":{"self":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts\/2114","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/comments?post=2114"}],"version-history":[{"count":24,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts\/2114\/revisions"}],"predecessor-version":[{"id":2256,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/posts\/2114\/revisions\/2256"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/media\/2127"}],"wp:attachment":[{"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/media?parent=2114"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/categories?post=2114"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pixelstudio.id\/blog\/wp-json\/wp\/v2\/tags?post=2114"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}