Make notices in Gutenberg within an AJAX running - wordpress

I've a PHP running with AJAX, and I'm wondering how to make notices in Gutenberg.
I've a JS with this code to run the notice:
( function( wp ) {
wp.data.dispatch('core/notices').createNotice(
'error',
'Message of error',
{
isDismissible: true,
actions: [
{
url: '#',
label: 'Button'
}
]
}
);
} )( window.wp );
But I don't know how to make it run, maybe with a variable or something.
How could make it work?

Related

Wordpress REST API: Posting data from a form as a guest user

I started creating an ajax post form that takes name and email as inputs. The idea is to have the anonymous, un-logged user to fill out the fields, and when the forms posting succeeds on the API, the user gets access to download an eBook.
The admin wants to be able to view the data of all the users that have filled out the form on the backend, so what I did is create a new custom post type labeled "ebook-user".
From the researching that I've done online, it seems that a user could only post on post comments to the rest api. Is there a way to enable anonymous posting on a custom post type?
Right now, when I post with my current code, I get a 401 error:
{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create posts as this user.",
"data": {
"status": 401
}
}
Here's my js code:
fetch(`${site_url}/wp-json/wp/v2/ebook-user`, {
credentials: 'same-origin',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': ajax_nonce,
},
body: JSON.stringify(credentials)
})
.then((res) => res.json())
.then((res) => {
console.log(res)
if(res.data.status == 403) {
formMsg.textContent = `Error`
}
console.log('success');
})
.catch((err) => {
console.error(err);
})
Note that I did add this line in my functions.php, which enables comment posting as guest user
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
Since you want to POST with an un-authenticated user, I'd create a custom endpoint to do it.
Something like:
/wp-json/mytld/v1/ebook
Allow POST to the end point but nothing else.
Validate the input VERY CAREFULLY and I'd go so far as to do things like make sure you don't already know the email address before allowing the post to succeed.
This requires a little more code but gives you a lot more control.
=C=
add_action( 'rest_api_init', function () {
register_rest_route( 'getdata/v1', '/author/(?id)', array(
'methods' => 'GET',
'callback' => 'my_bookdata_func',
) );
} );
function my_bookdata_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
Url to access
wp-json/getdata/v1/author/(?id).

Elementor custom media control

I am currently trying to copy Elementor's plugin Media control to do some adjustments to it in wordpress. I tried copying the control from \Elementor\Control_Media changing the name of the class and this method:
class Control_Custom_Media extends \Elementor\Control_Base_Multiple {
...
public function get_type() {
return 'custommedia';
}
}
Then registered it
function register_custom_controls($controls) {
include 'control-custom-media.php';
Plugin::instance()->controls_manager->register_control( 'custommedia', new Control_Custom_Media() );
}
add_action( 'elementor/controls/controls_registered', 'register_custom_controls');
Finally I created a widget with that control
protected function _register_controls() {
...
$this->add_control(
'image',
[
'label' => __( 'Test', 'custom-plugin' ),
'type' => 'custommedia',
'default' => [
'url' => \Elementor\Utils::get_placeholder_image_src(),
],
]
);
...
}
But I can't seem to make it work. The field appears on the elementor sidebar but once I click to open the media library, it doesn't work. Checked the events and the one that fires the 'openFrame' event is not bind for some reason?
To test if the media control was working I added it after and that one works
What I could be doing wrong?
Thanks in advance
I ended up extending the Media control for my custom control and add it as a control view.
var customMediaView = elementor.modules.controls.Media.extend({
onReady: function () {
/* do stuff */
}
});
elementor.addControlView('customMediaView', customMediaView);
On the enqueue method
wp_register_script( 'custommedia-control', plugins_url('/custommedia-control.js', __DIR__), [ 'elementor-editor' ], '1.0.0', true );
wp_enqueue_script( 'custommedia-control' );

Wordpress | Writing custom APIs for ajax calls or reports

If I have to develop a simple custom API to be accessed directly say, to display "Hello World!", then what all steps I need to do?
Let's say the APIs reside in [/themes/my_theme/_apis/]
You need to go to functions.php of your theme file and then write this :
add_action('wp_ajax_my_theme_ajax_method', 'my_theme_ajax_method');
add_action('wp_ajax_nopriv_my_theme_ajax_method', 'my_theme_ajax_method');
function my_theme_ajax_method(){
return 'Hello World'
}
add_action( 'wp_enqueue_scripts', 'my_theme_frontend_custom_scripts' );
function my_theme_frontend_custom_scripts(){
wp_localize_script( 'ajax-script', 'MyTheme', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'action' => array (
'MyAjaxMethod' => 'my_theme_ajax_method',
)
) );
}
And then in your frontend consider index.php you can write this
jQuery(document).ready(function(){
jQuery.ajax ({
type : 'get',
url : MyTheme.ajaxurl,
data : {
action : MyTheme.action.MyAjaxMethod,
},
}).done(function(data){
console.log(data); // <-- prints hello world
})
});

Custom route endpoint for WP-REST API gives "code": "rest_no_route", error

I am following this tutorial to create custom end points to WP-API .
I am always getting this error on hitting /wp-json/custom-plugin/v2/get-all-post-ids/ on postman to test :
{
"code": "rest_no_route",
"message": "No route was found matching
the URL and request method ",
"data": {
"status": 404
}
}
I have created a custom-plugin.php file in /plugins/custom-plugin/ directory .
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action( 'rest_api_init', 'dt_register_api_hooks' );
function dt_register_api_hooks() {
register_rest_route( 'custom-plugin/v2', '/get-all-post-ids/', array(
'methods' => 'GET',
'callback' => 'dt_get_all_post_ids',
)
);
}
// Return all post IDs
function dt_get_all_post_ids() {
if ( false === ( $all_post_ids = get_transient( 'dt_all_post_ids' ) ) ) {
$all_post_ids = get_posts( array(
'numberposts' => -1,
'post_type' => 'post',
'fields' => 'ids',
) );
// cache for 2 hours
set_transient( 'dt_all_post_ids', $all_post_ids, 60*60*2 );
}
return $all_post_ids;
}
?>
Ensure your callback to add_action( 'rest_api_init', 'dt_register_api_hooks' ); is being run.
In my case, my callback was not being called because I was using add_action('rest_api_init', ...) too late; the action had already fired. As in, my call to register_rest_route() never even happened.
I hope my answer can be useful to some as well.
For a very similar problem, while I was designing an API in WordPress, I also got the same "code": "rest_no_route",... error on some websites and not on other ones. I traced it back to the fact that POST requests were transformed into GET requests so they weren't recognized by my plugin.
The conversion from POST to GET was made before WordPress even started. I was able to pinpoint the problem and solve it by adding the following header, as explained in details here:
headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }

Intergrate Jplayer with Wordpress

I want to make a playlist made of files added to a Wordpress custom meta box. jPlayer generates the list using javascript, is there any way to bypass this and use regular html?
Edit:
Or could I get some guidance on how to call a wp function into the playlist? I am getting some ideas from call-php-function-from-jquery, but I am not sure how I would create multiple items/tracks or loop through them in the jquery script?
new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_2",
cssSelectorAncestor: "#jp_container_2"
}, [
{
title:"1",
mp3:"url/file",
oga:"url/file"
},
{
title:"2",
mp3:"url/file",
oga:"url/file"
},
], {
swfPath: "js",
supplied: "oga, mp3",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true
});
Update:
I am now echoing my post_mime_types as '$alltracks' into the jquery script Like this:
<?php
$query_audio_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'application/ogg',
);
$audio_attachments = get_posts($query_audio_args);
foreach ( $audio_attachments as $audio_attachment ) {
$ogg = wp_get_attachment_url( $audio_attachment->ID );
$tracks[] = '{
title:"'.$audio_attachment->post_title.'",
oga:"'.$ogg.'",
}';
$alltracks = implode(',',$tracks);
}
?>
$(document).ready(function() {
new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_2",
cssSelectorAncestor: "#jp_container_2"
}, [
<?php echo $alltracks; ?>
], {
swfPath: "js",
supplied: "oga, mp3,aif",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true
});
});

Resources