[Support request] Generate CSS from the generateblocks code dynamically

Home Forums Support [Support request] Generate CSS from the generateblocks code dynamically

Home Forums Support Generate CSS from the generateblocks code dynamically

  • This topic has 10 replies, 4 voices, and was last updated 5 months ago by Tom.
Viewing 11 posts - 1 through 11 (of 11 total)
  • Author
    Posts
  • #2150148
    Philipp

    Hi!

    Very new to GP, love it so far but still struggling a lot πŸ™‚

    So I wanted to replace the category pages with custom ones. My idea was to create a custom post type (so I have a Gutenberg editor with all the GenerateBlocks and other good stuff) and then display it’s contents in the category.php

    I have around 250 category pages so I wanted to create a “default” post where I could replace some parts programmatically and then add more and more custom category pages so they appear instead of the default one (this part works fine).

    Now in the category.php I was hoping to do just that and see the page just like I have styled it in Gutenberg:

    $post = get_post($postid);			
    echo do_shortcode($post->post_content);

    Of course, this doesnt work πŸ™‚ This is the HTML I am getting out of it:

    <!-- wp:paragraph -->
    <p>This is a default continent category page</p>
    <!-- /wp:paragraph -->
    
    <!-- wp:columns -->
    <div class="wp-block-columns"><!-- wp:column -->
    <div class="wp-block-column"><!-- wp:paragraph -->
    <p>1</p>
    <!-- /wp:paragraph --></div>
    <!-- /wp:column -->
    
    <!-- wp:column -->
    <div class="wp-block-column"><!-- wp:paragraph -->
    <p>2</p>
    <!-- /wp:paragraph --></div>
    <!-- /wp:column -->
    
    <!-- wp:column -->
    <div class="wp-block-column"><!-- wp:paragraph -->
    <p>3</p>
    <!-- /wp:paragraph --></div>
    <!-- /wp:column --></div>
    <!-- /wp:columns -->
    
    <!-- wp:generateblocks/container {"uniqueId":"d66db2cd","innerContainer":"full","backgroundColor":"#e41a1a","isDynamic":true,"blockVersion":2} -->
    <!-- wp:paragraph -->
    <p>test</p>
    <!-- /wp:paragraph -->
    <!-- /wp:generateblocks/container -->

    Now I have read in other support topics that the CSS is generated for each page (?) on the fly and obviously my content is not being processed properly.

    Is there a way to force the CSS generation dynamically from the content string? Just like the WordPress have the do_shortcode() method to process shortcodes from text?

    Or is there something I am completely missing? Or is there a better way to accomplish that?

    I have looked into the Elements and Dynamic content and it seems it is limited a bit – keep in mind I need to check which content to return first (default or custom for this specific category) and replace a couple of things in the default template before displaying it.

    Thank you for your time!

    #2150281
    Fernando
    Customer Support

    Hi Philipp,

    Here is an article that may assist you with regards to this: https://docs.generateblocks.com/article/adding-content-sources-for-dynamic-css-generation/

    Hope this helps. Kindly let us know how it goes. πŸ™‚

    #2150767
    Philipp

    Unfortunately, it didn’t help. I can see that the content of my custom post was added to the content within this function and the return includes my custom post content, but the styling is still missing – the HTML shows the same output as before.

    Is it possible that this filter only works when you are inside of a post? And I am actually on a category page that is loading a custom post to display.

    #2150796
    David
    Staff
    Customer Support

    Hi there,

    do you have an example of what it is you’re trying to achieve ? As a LOT can be done with a Block Element – Content Template.

    #2150974
    Philipp

    Hi David!

    Like I wrote in my original post I am basically trying to display a post (from a custom post type) instead of the category page. I want to replace some of the content in that template based on the category’s custom fields. The point of faking the categories is to keep the site structure and the breadcrumbs in place, so I don’t want to do that with pages.

    I took a look at the block elements but had the impression that it’s dynamic content capabilities are very limited. So if I can use that and do some additional replacements on it before displaying that would work too I guess.

    This generateblocks_do_content sounds a bit easier for me but apparently it doesn’t work within category pages I guess.

    For the context – I have categories for countries that will list specific posts for these countries. So for these category pages I want to have more content – nicely designed and formatted with GenerateBlocks in Gutenberg – and then list the posts for that country manually

    #2151565
    Tom
    Lead Developer
    Lead Developer

    Can you show me how you’re using the generateblocks_do_content filter right now? It should work, but you need to pass the content for it to parse before the content is loaded on the page (so the CSS can be generated).

    #2152303
    Philipp

    I am displaying the content in categories.php – but I see the echoes from the generateblocks_do_content (which is fired twice for some reason) before the echoes of my category page.

    I have more or less copy/pasted the function from the link above:

    add_filter( 'generateblocks_do_content', function( $content ) 
    {
        $post_id = 3425; // A post ID to check the content of. Can be dynamically set.
    
        if ( has_blocks( $post_id ) ) 
    	{
            $block_element = get_post( $post_id );
    
            if ( ! $block_element || 'category_page' !== $block_element->post_type ) {
                return $content;
            }
    
            if ( 'publish' !== $block_element->post_status || ! empty( $block_element->post_password ) ) {
                return $content;
            }
    
            $content .= $block_element->post_content;
        }
    	
    	/*
    	echo "added###";
    	echo $content;
    	echo "###";
    	*/
    
        return $content;
    } );

    category_page is my custom post type name. in the echoes just before the return I see that the correct content was loaded (the one I am displaying on this page later in categories.php) and that it was added to the $content passed to the function

    categories.php:

    <?php
    /**
     * The template for displaying Archive pages.
     *
     * @package GeneratePress
     */
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit; // Exit if accessed directly.
    }
    
    $category = get_queried_object();
    $category_type = get_field('type', 'category_' . $category->term_id);
    
    get_header(); ?>
    
    	<div <?php generate_do_attr( 'content' ); ?>>
    		<main <?php generate_do_attr( 'main' ); ?>>
    			<?php
    			/**
    			 * generate_before_main_content hook.
    			 *
    			 * @since 0.1
    			 */
    			do_action( 'generate_before_main_content' );
    			
    			
    			// check if we have a custom category page for this category
    			$posts = get_posts(array(
    				'numberposts'	=> -1,
    				'post_type'		=> 'category_page',
    				'category__in' 		=> array($category->term_id)
    			));
    			
    			if(count($posts))
    			{
    				
    				$post = get_post($posts[0]);			
    				
    				echo do_shortcode($post->post_content);
    			}
    			else
    			{
    				
    				// check if we have a default category page for this category type
    				$posts = get_posts(array(
    					'numberposts'	=> -1,
    					'post_type'		=> 'category_page',
    					'meta_key'		=> 'type',
    					'meta_value'	=> $category_type
    				));
    				
    				if(count($posts))
    				{					
    					$post = get_post($posts[0]);
    					
    					echo do_shortcode($post->post_content);
    				}
    				else
    				{
    					// fallback (should not happen) - nothing found at all, display the wordpress standard
    					if ( generate_has_default_loop() ) {
    						if ( have_posts() ) :
    
    							/**
    							 * generate_archive_title hook.
    							 *
    							 * @since 0.1
    							 *
    							 * @hooked generate_archive_title - 10
    							 */
    							do_action( 'generate_archive_title' );
    
    							/**
    							 * generate_before_loop hook.
    							 *
    							 * @since 3.1.0
    							 */
    							do_action( 'generate_before_loop', 'archive' );
    
    							while ( have_posts() ) :
    
    								the_post();
    
    								generate_do_template_part( 'archive' );
    
    							endwhile;
    
    							/**
    							 * generate_after_loop hook.
    							 *
    							 * @since 2.3
    							 */
    							do_action( 'generate_after_loop', 'archive' );
    
    						else :
    
    							generate_do_template_part( 'none' );
    
    						endif;
    					}
    
    					/**
    					 * generate_after_main_content hook.
    					 *
    					 * @since 0.1
    					 */
    					do_action( 'generate_after_main_content' );
    				}
    			}
    			
    			
    			
    
    			
    			?>
    		</main>
    	</div>
    
    	<?php
    	/**
    	 * generate_after_primary_content_area hook.
    	 *
    	 * @since 2.0
    	 */
    	do_action( 'generate_after_primary_content_area' );
    
    	generate_construct_sidebars();
    
    	get_footer();

    And while I have cateched the developer – how can I set the $post_id in the generateblocks_do_content dynamically? I vasically need the id of the current category to figure it out

    #2152474
    Philipp

    Meanwhile, I did some more tests without any luck:

    – Tried to disable all plugins except of Custom Post Type UI, GP Premium and GenerateBlocks.

    – Tried to display other custom post types and regular posts with the help of generateblocks_do_content.

    – Tried to display the custom post type in a regular post (inside of single.php).

    – When I preview the custom post type alone (without embedding it anywhere), the styling works just fine.

    Still the same result. Got a feeling that I’m missing something small but important here.

    #2152539
    Tom
    Lead Developer
    Lead Developer

    Can you try setting the CSS Print Method to Inline Embedding in “GenerateBlocks > Settings”? If you can see the content being loaded, it likely means the CSS files need to be regenerated.

    And while I have cateched the developer – how can I set the $post_id in the generateblocks_do_content dynamically? I vasically need the id of the current category to figure it out

    Where exactly is the post ID coming from? Are you creating these as pages and then displaying them in category.php?

    #2153096
    Philipp

    What the …? It works now! I am sure that I have tried out all of these options before – “Inline Embedding” and “Regenerate CSS Files” without any effect.

    However, since then I have learned that the proper way to display post content is with apply_filters( 'the_content', $post->post_content), so maybe it’s the combination of both that did the trick.

    Anyways, it works now with both Inline embedding and external files although I have no idea why (and it scares me a bit). Is there something to read about the CSS creation in GeneratePress?

    A bonus question – since the CSS is apparently generated for each page can it cause problems if I merge all CSS with RankMath? Or do I need to exclude some files there?

    Thank you very much for your patience and top notch support – you guys rock πŸ™‚

    And I have figured it out with the dynamic $post_id as well – I just need to do pretty much the same stuff I do in category.php. Here is the final generateblocks_do_content part, it might help someone:

    add_filter( 'generateblocks_do_content', function( $content ) 
    {
    	// if it's a category we need to generate css for the custom post type that will be displayed instead
    	if(is_category())
    	{
    		// get current category
    		$category = get_queried_object();	
    
    		// get category type (continent or country)
    		$category_type = get_field('type', 'category_' . $category->term_id);		
    		
    		// default post id
    		$post_id = 0;
    
    		// check if we have a custom category page for this specific category (it is assigned to the same category we are displaying)
    		$posts = get_posts(array(
    			'numberposts'	=> -1,
    			'post_type'		=> 'category_page',
    			'category__in' 		=> array($category->term_id)
    		));		
    		
    		if(count($posts))
    		{			
    			$post_id = get_post($posts[0])->ID;	
    		}
    		else
    		{			
    			// check if we have a default category page for this category type (country or continent)
    			$posts = get_posts(array(
    				'numberposts'	=> -1,
    				'post_type'	=> 'category_page',
    				'meta_key'	=> 'type',
    				'meta_value'	=> $category_type
    			));
    			
    			if(count($posts))
    			{					
    				$post_id = get_post($posts[0])->ID;	
    			}
    		}
    		
    		if ( $post_id && has_blocks( $post_id ) ) 
    		{
    			$block_element = get_post( $post_id );
    
    			if ( ! $block_element || 'category_page' !== $block_element->post_type ) {
    				return $content;
    			}
    
    			if ( 'publish' !== $block_element->post_status || ! empty( $block_element->post_password ) ) {
    				return $content;
    			}
    
    			$content .= $block_element->post_content;
    		}
    	}	
    
        return $content;
    } );
    #2153254
    Tom
    Lead Developer
    Lead Developer

    Glad it’s working now!

    Anyways, it works now with both Inline embedding and external files although I have no idea why (and it scares me a bit). Is there something to read about the CSS creation in GeneratePress?

    Only the code, unfortunately.

    1. We get the parsed content:
    https://github.com/tomusborne/generateblocks/blob/1.4.2/includes/generate-css.php#L1694
    https://github.com/tomusborne/generateblocks/blob/b8992bbabb0fdc7858e6daed77ce36c86039157b/includes/functions.php#L101

    2. We take that content and extract the data we need (the attributes from our blocks):
    https://github.com/tomusborne/generateblocks/blob/b8992bbabb0fdc7858e6daed77ce36c86039157b/includes/generate-css.php#L25

    3. We take that data and build the CSS: https://github.com/tomusborne/generateblocks/blob/b8992bbabb0fdc7858e6daed77ce36c86039157b/includes/generate-css.php#L39

    A bonus question – since the CSS is apparently generated for each page can it cause problems if I merge all CSS with RankMath? Or do I need to exclude some files there?

    This depends on how they’re achieving that feature. Only way to find out is to try πŸ™‚

    Thanks!

Viewing 11 posts - 1 through 11 (of 11 total)
  • You must be logged in to reply to this topic.