PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label wordpress-gutenberg. Show all posts
Showing posts with label wordpress-gutenberg. Show all posts

Monday, May 16, 2022

[FIXED] How to disable widget block editor of WordPress?

 May 16, 2022     php, widget, wordpress, wordpress-gutenberg, wordpress-rest-api     No comments   

Issue

WP 5.8 comes with a new system to manage events named "Widgets Block Editor". How can I disable this new system and restore the classic widget editor of WordPress?


Solution

To disable the new WordPress widget editor system you can use one of following methods.

1. Install and Activate the Disable Widget Block Editor plugin.

2. Use use_widgets_block_editor filter to disable it. You can place following code in your theme functions.php file or your plugin.

add_filter( 'use_widgets_block_editor', '__return_false' );

3. Use following code in functions.php of your theme to declare that your theme doesn't support the new widget editor system.

remove_theme_support( 'widgets-block-editor' )


Answered By - Hossein
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, May 15, 2022

[FIXED] How to share node_modules and package.json files between two directories?

 May 15, 2022     gutenberg-blocks, node-modules, package.json, wordpress, wordpress-gutenberg     No comments   

Issue

As I experiment with WordPress's new Gutenberg development methods, I noticed that I need to create individual block folders within the plugins directory. These are essentially the components that makeup the front-end and editor side of things.

I would like to understand two things:

  1. How to install node_modules and package.json files so that commands are accepted when not in a specific block directory folder.

  2. I would like to run certain builds with specific scripts, what are the proper commands to hand this procedure when outside of a block directory?

How do I setup my environment so that when I type in a command, it understand to compile no matter which plugin directory I am in?


Solution

The create-block package has scaffolding that allows you to create blocks and the package is undergoing heavy development right now that will allow you to have multiple blocks within one folder.



Answered By - Will
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 12, 2022

[FIXED] How to define default style for InnerBlocks template for Gutenberg Block Editor (WordPress)

 March 12, 2022     gutenberg-blocks, reactjs, wordpress, wordpress-gutenberg     No comments   

Issue

I am using gutenbergs' core block to make another block using InnerBlock. So, I want to change their default style like text align center.To start, I used officially supported way to create blocks Create-Guten-Block. My codes are as follows:

import {
    InnerBlocks, useBlockProps
} from '@wordpress/block-editor';
import './editor.scss';

export default function Edit() {
    return (
        <div { ...useBlockProps() }>
            <InnerBlocks
                template={ [
                    [ 'core/columns', {},
                        [
                            [ 'core/column', {}, [
                                    [ 'core/paragraph', { content: '$200' } ],
                                ]
                            ],
                            [ 'core/column', {}, [
                                    [ 'core/button', { placeholder : 'Buy Now' } ],
                                ]
                            ],
                        ]
                    ],
                ] }
                templateLock="all"
            />
        </div>
    );
}
WordPress uses has-text-align-left class to align a text in the block. Is there any way to define default style inside the core/button's text-align to center inside the template.


Solution

Yes, the core/button block supports align and can be set in the block attribute align within the InnerBlocks template, eg:

...
    ['core/button', { placeholder: 'Buy Now', align: 'center' }],
...

The resulting HTML then has the built-in style aligncenter applied and the button is now center aligned:

<div class="wp-block-button aligncenter">
    <a class="wp-block-button__link">Buy Now</a>
</div>


Answered By - S.Walsh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I make a dropdown list control that fetches names of custom posts types?

 March 12, 2022     gutenberg-blocks, javascript, php, wordpress, wordpress-gutenberg     No comments   

Issue

How can I make a dropdown list control that fetches names of custom posts types? In my project I want to select a post type name and fetch it in drop down selector in my custom Gutenberg Block!.. How can I do this?


Solution

If creating a dropdown list (select) for the edit() function of a Gutenberg block, registered post types can be retrieved with getPostTypes() via useSelect() in JavaScript. An example of this is the dropdown in the Query Block to select a Post Type.

Below is a simplified example that uses a <SelectControl/> to display a list of all viewable post types, and enables a selected postType to be saved the blocks attributes.

block.json

{
    ...
    "attributes": {
        "postType": {
            "type": "string",
            "default": "post"
        }
    }
}

edit.js

import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { SelectControl } from '@wordpress/components';
import { useBlockProps } from '@wordpress/block-editor';


export default function Edit({ attributes, setAttributes }) {
    // postType defined in block.json
    const { postType } = attributes;

    // useSelect to retrieve all post types
    const postTypes = useSelect(
        (select) => select(coreStore).getPostTypes({ per_page: -1 }), []
    );

    // Options expects [{label: ..., value: ...}]
    var postTypeOptions = !Array.isArray(postTypes) ? postTypes : postTypes
        .filter(
            // Filter out internal WP post types eg: wp_block, wp_navigation, wp_template, wp_template_part..
            postType => postType.viewable == true)
        .map(
            // Format the options for display in the <SelectControl/>
            (postType) => ({
                label: postType.labels.singular_name,
                value: postType.slug, // the value saved as postType in attributes
            })
        );

    return (
        <div {...useBlockProps()}>
            <SelectControl
                label="Select a Post Type"
                value={postType}
                options={postTypeOptions}
                onChange={(value) => setAttributes({ postType: value })}
            />
        </div>
    );
}

The advantage of using JavaScript for the Editor instead of falling back to PHP is you can keep the UI consistent by using Gutenberg controls like <SelectControl/>.

The Settings Sidebar may be a good place to put your <SelectControl/> depending on your goal.



Answered By - S.Walsh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, March 7, 2022

[FIXED] Expose default gutenberg block styles in WordPress rest API

 March 07, 2022     wordpress, wordpress-gutenberg, wordpress-rest-api, wordpress-theming     No comments   

Issue

We're using the WordPress REST API to power a static site. The site is "headless" in the sense that we don't use a WordPress theme; we rely on the content being exposed via the REST API.

Some of the default Gutenberg blocks - the Buttons block for instance - have styles with hashed class names associated with them that don't seem to be exposed in the API. This would be kind of ok if the class names were predictable but, since they aren't, we have no way of providing the styles on our end.

If we do render the blocks in a theme, the styles are rendered in the footer

Here's an example of the style block for the default Buttons block looks like in a WordPress theme
gutenberg wp-container styles

The Rest API endpoint exposes the markup in content.rendered (including the classnames) but no styles
Rendered markup from API

Is this expected behavior for using Gutenberg and the WordPress REST API? If so, is the correct solution to expose the styles via a custom field (for lack of a better term) on the API?


Solution

The unique id (hash) in the classnames are randomly generated each time the blocks are parsed, even when directly calling the REST API. Unfortunately, the inline style attributes like .alignleft are absent from the content markup in the REST API. Being a REST API, it makes sense that style specific information isn't included; this keeps data and presentation of the data separate. It also prevents bloating the API by including style-specific information that would be rarely used outside of WordPress theme.

In your scenario, if you wish to style the resulting HTML content without worrying about the unique id, I'd suggest using css partial selectors, eg:

div[class*="wp-container-"] .wp-block-button{
    ...
}

Alternatively, as you mentioned, its possbile to extend the REST API to include the styles. While I haven't built a working example of this for styles, when blocks where introduced I ended up extended the REST API to include extra meta data. I'd suggest looking at render_block_data to handle adding in the styles into the content.

Eg. For the buttons block, the serialized content stored in the database as:

<!-- wp:buttons {"layout":{"type":"flex","justifyContent":"center"}} -->
<div class="wp-block-buttons"><!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link">Hello</a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->

By using parse_blocks() you can obtain all the block properties into an array and get style information that way. I think this approach is do-able if you just add the generated classnames and not the inline styles. I am keen to know if you find a better way...



Answered By - S.Walsh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 17, 2022

[FIXED] Changing a post's tag / category from a wordpress gutenberg sidebar plugin

 February 17, 2022     javascript, reactjs, taxonomy, wordpress, wordpress-gutenberg     No comments   

Issue

I'm attempting to add / delete a post's tag / category from a WordPress Gutenberg sidebar plugin (using React / JavaScript). There seems to be very little information on the implementation of this use case and am seeking input from the community on a viable approach you may have come across.

Current implementation:

I have a Sidebar plugin, with several panels. Once of these is responsible for adding / removing categories / tags from a Post. The components are rendered using:

MyComponent = props => {
    return (
             <PanelBody title="My Title">
                <PanelRow>
                    <TabPanel
                        className="tab-panel"
                        activeClass="active-tab"
                        onSelect={(tabName) => props.onItemChange(tabName)}
                        tabs={_data}
                    >
                        {tab => (
                            <div className="tab-content">
                                <div
                                    className="description"
                                    dangerouslySetInnerHTML={{ __html: tab.description }}
                                ></div>
                                <div className="actions">
                                    <Button isSecondary onClick={() => props.onTaxonomiesAdd(props.category, props.tag)}>Add Tag / Category!</Button>
                                </div>
                            </div>
                        )}
                    </TabPanel>
                </PanelRow>
           </PanelBody>
     );
};

 

When the button is clicked, I would like to add designated tags / categories to the post. The click event is successfully detected and fired within the WithDispatch Higher Order Component as follows:

export default compose([
    withSelect(select => {  // WithSelect Routines Here  }),
    withDispatch(dispatch => {
        return {
            onTaxonomiesAdd: (category, tag) => {
                 //Add Taxonomy Items here
                 alert("I'm firing successfully");
            }
        }

The closest approach I've stumbled across so far uses:

wp.data.dispatch( 'core' ).editEntityRecord( 'postType', 'contributor', currentPost.id, { 'topic': [ term_id ] } );

...but I'm yet to get something similar working properly.

Have any of you found a solution to achieve this outcome?


Solution

Following on from the link above, I implemented the use case successfully adding the following outside of my component as utility functions (that could be re-used):

//Add Tag & Category in one call
function AddTaxonomies(tag, category){
    AddTag(tag);
    AddCategory(category);
}

//Add Tag & Refresh Panel
function AddTag(tag){

    //Get Current Selected Tags
    let tags = select( 'core/editor' ).getEditedPostAttribute( 'tags' );

    //Get State of Tag Panel
    let is_tag_panel_open = select( 'core/edit-post' ).isEditorPanelOpened( 'taxonomy-panel-tags' );

    //Verify new tag isn't already selected
    if(! tags.includes(tag)){

        //Add new tag to existing list
        tags.push(tag);

        //Update Post with new tags
        dispatch( 'core/editor' ).editPost( { 'tags': tags } );

        // Verify if the tag panel is open
        if ( is_tag_panel_open ) {

            // Close and re-open the tag panel to reload data / refresh the UI
            dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-tags' );
            dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-tags' );
        }            
    }

}

//Add Category & Refresh Panel
function AddCategory(category){

    //Get Current Selected Categories
    let categories = select( 'core/editor' ).getEditedPostAttribute( 'categories' );

    //Get State of Category Panel
    let is_category_panel_open = select( 'core/edit-post' ).isEditorPanelOpened( 'taxonomy-panel-category' );

    //Verify new category isn't already selected
    if(! categories.includes(category)){

        //Add new tag to existing list
        categories.push(category);

        //Update Post with new tags
        dispatch( 'core/editor' ).editPost( { 'categories': categories } );

        // Verify if the category panel is open
        if ( is_category_panel_open ) {

            // Close and re-open the category panel to reload data / refresh the UI
            dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-category' );
            dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-category' );
        }            
    }
}

Hope this is useful for anyone else in the community looking to implement this use case.



Answered By - Matt Woodward
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 12, 2022

[FIXED] Remove Gutenberg CSS

 February 12, 2022     css, wordpress, wordpress-gutenberg     No comments   

Issue

I have Gutenberg plugin installed in WordPress v4.9.8 and am trying to remove the CSS that comes with it so I can supply my own.

This is the sheet that gets included:

<link rel='stylesheet' id='wp-block-library-css'  href='/wp-content/plugins/gutenberg/build/block-library/style.css?ver=1535795173' type='text/css' media='all' />

I have tried the following:

add_action( 'wp_print_styles', 'wps_deregister_styles', 100 );
function wps_deregister_styles() {
    wp_dequeue_style( 'wp-block-library-css' );
    wp_deregister_style( 'wp-block-library-css' );
}

As well as variations of this, but the file persists. How can I remove it?


Solution

I'm adding this as a more complete answer than my comment:

You need to remove the -css when trying to dequeue the script. That's added to the HTML markup and not the actual tag for the css file.

If you search the code (the location of the enqueue may change as Gutenberg gets rolled into core), you can find:

wp_enqueue_style( 'wp-block-library' );

As you can see, there is no -css. This solution may work for other plugins that people have trouble dequeuing styles.

Edit: Since this still gets some traction, here is the code to handle it:

add_action( 'wp_print_styles', 'wps_deregister_styles', 100 );
function wps_deregister_styles() {
    wp_dequeue_style( 'wp-block-library' );
}


Answered By - disinfor
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 5, 2022

[FIXED] Include image assets in a WordPress Gutenberg Block Plugin

 February 05, 2022     webpack, wordpress, wordpress-gutenberg     No comments   

Issue

I am creating a custom WordPress Gutenberg block and I want to use image assets (PNGs, JPGs) from my plugin folder, to be shown in both the Gutenberg editor and on the rendered page.

I am using Webpack to bundle my files for JS and SCSS. I tried adding the webpack image loader, which saves images into an 'assets' folder in my main plugin directory.

However, when I try to use my image assets from my Block's main JS file, I cannot find a way to access the full URL path of my images as running on my WordPress server, currently running in a docker container on localhost.

My hope was to find a WordPress method to return the path of my plugin directory, and use that to point to the image assets regardless of how they are bundled, but I have not been able to find a solution in the documentation.

It's possible to get the plugin directory using PHP using WordPress' built-in function:

function _get_plugin_directory() {
  return __DIR__;
}

This seems like it could help, however I do not know if it's possible to pass the returned plugin path into my JS file.

My plugin structure looks like this:

/assets // generated by Webpack
  - image.png
  - main.js
/blocks
  /block-example
    - image.png // <-- My image asset
    - index.js // <-- I want to use image.png here
  - index.js // loads in my block
blocks.php

The index.js file is where I want to show the image, using the standard WordPress edit and save functions:

import image from './image.png';

edit: props => {
  ...
  <img src={image} />
}

In the WordPress Gutenberg editor, images point to just the image file name (./image.png or assets/image.png etc), instead of the full path of the image where it sits inside the plugin directory (ie localhost:8080/plugins/my-blocks/assets/image.png) which results in the image not being found.


Solution

I'm still looking into whether there's an official Gutenberg way to do this, but for now I've got this working in my plugin with wp_localize_script.

This works to pass data from PHP into enqueued Javascript so that data usually only accessible in PHP is accessible in Javascript as well.

So (likely inside blocks.php from your example), you would have something like:

wp_enqueue_script(
    'my-main-script',
    plugins_url( 'assets/main.js', __FILE__ ),
    array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-components' ),
    '20190804',
    true
);

You can then enqueue any values you want to pass into your JS:

wp_localize_script(
    'my-main-script',
    'js_data',
    array(
        'my_image_url' => plugins_url( 'blocks/block-example/image.png', __FILE__ )
    )
);

This will ensure that the image path is accessible to javascript. Then from within your block itself, you can reference it:

<img src={js_data.my_image_url} />

You should now see your static image asset rendered within your block.



Answered By - Keanan Koppenhaver
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 2, 2022

[FIXED] How to insert gutenberg block inside post_content when using wp_insert_post()?

 February 02, 2022     gutenberg-blocks, php, wordpress, wordpress-gutenberg     No comments   

Issue

I would like to generate a gutenberg block in php.

I'm currently developping a wordpress plugin that import videos from youtube and create a post for each video. I can insert the youtube video inside the post_content but when i edit the post with the gutenberg editor it doesn't display as a block.

I read most of the "Block Editor Handbook" here https://developer.wordpress.org/block-editor/ But i can't find anything except how to create custom block. I searched on google also, but everything i found was also about creating custom block. Yet i found that gutenberg blocks are stored inside post_content as a html comment, but the comment seems to be generated with js via gutenberg WYSIWYG editor.

I know that i could create a post with the blocks and copy the post_content from my database then use it as a "template" but i don't think it's a proper way.

Is there any documentation about using the blocks that come with wordpress (ie: embed, paragraphe) and generate the html comment wich is saved within post_content with php ? Is it even possible ?


Solution

When you manually add a YouTube block, click the "Code Editor" view in the Tools & Options menu (right side). In the Code Editor view you will see the HTML needed for the editor to correctly parse the block.

For example:

<!-- wp:core-embed/youtube {"url":"https://www.youtube.com/watch?v=VIDEOID","type":"video","providerNameSlug":"youtube","className":"wp-embed-aspect-16-9 wp-has-aspect-ratio"} -->
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
https://www.youtube.com/watch?v=VIDEOID
</div></figure>
<!-- /wp:core-embed/youtube -->



Answered By - Tim Jensen
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 7, 2022

[FIXED] Integrating slick.js into wordpress

 January 07, 2022     html, php, slick, wordpress, wordpress-gutenberg     No comments   

Issue

Currently I'm integrating slick.js combined with some ACF fields. In the backend you can actually filter the testimonials on count and certain categories. Everything is working well so far, but when I add the slider class to my html syntax, each testimonial is considered as a different, separate slider. I'd like to have all testimonials combined in 1 slider. Can anyone help me on this one?

My code so far:

block.php

<?php
/**
 * Block Name: Testimonials
 *
 * This is the template that displays the testimonials loop block.
 */

$argType = get_field( 'loop_argument_type' );
if( $argType == "count" ) :
  $args = array( 
    'orderby' => 'title',
    'post_type' => 'testimonials',
    'posts_per_page' => get_field( 'testimonial_count' )
  );
else:
  $testimonials = get_field( 'select_testimonials' );
  $args = array( 
    'orderby' => 'title',
    'post_type' => 'testimonials',
    'post__in' => $testimonials
  );
endif;

$the_query = new WP_Query( $args );

  if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

      <div class="testimonialHolder">
        <?php the_content(); ?>
        <h3><?php the_title(); ?></h3>
        <b><?php the_field('naam', get_the_ID()); ?></b> 
        <?php the_field('samenvatting', get_the_ID()); ?>
      </div>
    
    <?php endwhile; ?>
<?php endif;?>

and slider.js

jQuery(document).ready(function($) {

    //Slick Slider
    $('.testimonialHolder').slick({
        autoplay:true,
        prevArrow: '<div class="slick-prev"><i class="fa fa-angle-left" aria-hidden="true"></i></div>',
        nextArrow: '<div class="slick-next"><i class="fa fa-angle-right" aria-hidden="true"></i></div>'
    });

});

Many thanks in advance!


Solution

Adjusted some of your code. This should work:

<?php

/**
 * Block Name: Testimonials
 *
 * This is the template that displays the testimonials loop block.
 */

$argType = get_field('loop_argument_type');
if ($argType == "count") :
    $args = array(
        'orderby' => 'title',
        'post_type' => 'testimonials',
        'posts_per_page' => get_field('testimonial_count')
    );
else :
    $testimonials = get_field('select_testimonials');
    $args = array(
        'orderby' => 'title',
        'post_type' => 'testimonials',
        'post__in' => $testimonials
    );
endif;


$the_query = new WP_Query($args);

?>

<section class="testimonials">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="testimonialHolder">
                    <?php
                    if ($the_query->have_posts()) {
                        while ($the_query->have_posts()) {
                            $the_query->the_post(); ?>
                            <div class="item">
                                <div class="testimonial">
                                    <?php $image = get_field('foto', get_the_ID()); ?>
                                    <img src="<?php echo $image['url']; ?>" class="img-circle" alt="<?php echo $image['alt']; ?>" />
                                    <h4><?php the_field('naam', get_the_ID()); ?></h4>
                                    <p><?php the_field('samenvatting', get_the_ID()); ?></p>
                                </div>
                            </div>
                        <?php } 
                    } else { ?>
                        <div class="item">
                            <div class="testimonial">
                                <h3>No Testimonials Found</h3>
                            </div>
                        </div>
                    <?php }
                    wp_reset_postdata();
                    ?>
                </div>
            </div>
        </div>
    </div>


Answered By - Harry M
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing