0

I want to create a block to display the latest post. The post are loading as it should but i want to use "props.attributes.selectAllignment" and pass that as a class inside the php function. This props.attributes.selectAllignmentwill output "left right or center" as a class. I can directly put the class in the html in php but I want to give the user the ability to select the class from InspectorControls

Block.js code as below

registerBlockType("buik/block-lead", {

title: __("Lead Block"), 
icon: "minus",
category: "layout",
keywords: [__("lead "), __("lead bootstrap"), __("buik")],
attributes: {
    heading: {
        type: "string",
        default:
            "Lead paragraph. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.",
    },
    customClass: {
        type: "string",
    },
    selectAllignment: {
        type: "string",
        default: "",
    },
    cover: {
        type: "string",
        default: "", // keep it empty so it doesn't get saved in the post content
    },
},

edit: (props) => {
    const focus = props.focus;

    const onChangeheading = (value) => {
        props.setAttributes({ heading: value });
    };

    const { selectAllignment } = props.attributes;

    function onChangeselectAllignment(newValue) {
        props.setAttributes({ selectAllignment: newValue });
    }

    const blockProps = useBlockProps();
    const posts = useSelect((select) => {
        return select("core").getEntityRecords("postType", "post", {
            per_page: 3,
        });
    }, []);

    return [
        <div className={props.className}>
            {!posts && "Loading"}
            {posts && posts.length === 0 && "No Posts"}
            {posts && posts.length > 0 && (
                <div>
                    <ul>
                        {posts.map((post) => {
                            return (
                                <li
                                    style={{
                                        textAlign: `${props.attributes.selectAllignment}`,
                                    }}
                                >
                                    <img src={post.fimg_url} />
                                    <a href={post.link}>{post.title.rendered}</a>
                                </li>
                            );
                        })}
                    </ul>
                </div>
            )}

            <RichText
                tagName="p"
                placeholder="Edit paragraph "
                className={selectField}
                focus={focus}
                value={props.attributes.heading}
                onChange={onChangeheading}
                keepPlaceholderOnFocus={true}
            />
        </div>,
        <InspectorControls>
            <SelectControl
                label="Text alignment"
                value={selectAllignment}
                options={[
                    { value: "left", label: "default" },
                    { value: "center", label: "Center" },
                    { value: "left", label: "Left" },
                    { value: "right", label: "Right" },
                ]}
                onChange={onChangeselectAllignment}
            />
        </InspectorControls>,
    ];
},


save: (props) => {
    return null;
},

});

php code that renders the output in frontend

add_action('plugins_loaded', 'register_latest_post');
function register_latest_post() {
    register_block_type('buik/block-lead', [ 'render_callback' => 'render_latest_post'
    ]);
}
function render_latest_post() {
$latest_posts = wp_get_recent_posts( [

    'numberposts' => 3,
    'post_status' => 'publish'
    ] );
if(empty($latest_posts)){
    return '<p>No posts</p>';
}
$posts_output = '<div class="latest-postss">'; 
foreach($latest_posts as $post ) {

$post_id = $post['ID'];

$post_thumbnail = get_the_post_thumbnail_url( $post_id, 'full' );
$posts_output .= '<div class="post-title ">
                        <img src="'. $post_thumbnail .'" class="img-fluid" loading="lazy" />
                        <h2>
                            <a href="'.get_permalink($post_id). '">
                                '.get_the_title( $post_id ).'
                            </a>
                        </h2>
                        
                  </div>';
}
$posts_output .= '</div>';

return $posts_output;

}

add_action('rest_api_init', 'register_rest_images' );
function register_rest_images(){
    register_rest_field( array('post'),
        'fimg_url',
        array(
        'get_callback' => 'get_rest_featured_image',
        'update_callback' => null,
        'schema' => null,
        )
    );
}
function get_rest_featured_image( $object, $field_name, $request) { if( $object['featured_media'] ) {
    $img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' ); return $img[0];
}
return false;
}

function parse_blocks1( $content ) {

$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );

$parser = new $parser_class();
return $parser->parse( $content );

}

1 Answer 1

0

The render_callback function receives the block attributes as the first argument:

function render_latest_post( $attributes ) {
    $column_size = $attributes['columnSize'];
    // etc.
}
7
  • i get this error: Undefined variable $attributes i am sorry I dont know much php. Nov 28, 2022 at 1:25
  • Updated the question and the code. Nov 28, 2022 at 1:47
  • Your updated code isn’t using my suggestion? Nov 28, 2022 at 4:21
  • I tried. It gives an error Undefined variable $column_size function render_latest_post1( $attributes ) { $column_size = $attributes['selectAllignment']; } Since the function render_latest_post() already exist I added function render_latest_post1() Nov 28, 2022 at 4:49
  • Are you also using the render function somewhere else? Nov 28, 2022 at 4:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.