I'm creating a custom block inside a plugin. It's a drop down selector of categories for posts. I'm simply trying to update the query of a query loop block on the same page. However I'm not sure how to access the query of the query loop block.
I've tried the above however getting the blockId of the block doesn't seem to be possible on the front end. Does anyone know how i can reference the query loop block from a front end js file?
plugin.php
function tapacode_selector_ajax_callback() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'wp-tapacode-nonce' ) ) {
die ( 'Busted!' );
}
$category = intval( $_POST['category']);
$query_args = array(
'cat' => $category
);
$query = new WP_Query( $query_args );
wp_send_json( $query->posts );
wp_die();
}
add_action( 'wp_ajax_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_ajax_nopriv_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'ajax-selector-script', plugins_url( '/selector.js', __FILE__ ), array( 'wp-blocks', 'wp-editor', 'wp-element', 'jquery' ), '1.0', true );
wp_enqueue_script( 'ajax-selector-script' );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-selector-script', 'ajax_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wp-tapacode-nonce' )
) );
}
another plugin.php file
<p <?php echo get_block_wrapper_attributes(); ?>>
<?php wp_dropdown_categories(); ?>
</p>
selector.js
document.addEventListener('DOMContentLoaded', setupCategorySelector, false);
function setupCategorySelector() {
document.getElementById('cat').onchange = function () {
// if value is category id
if (this.value !== '-1') {
if (typeof wp !== 'undefined' && wp.data) {
const blockId = document.querySelector('.wp-block-tapacode-category-selector').getAttribute('data-block-id');
const queryBlock = wp.data.select('core/block-editor').getBlock(blockId);
queryBlock.setAttributes({ categories: this.value });
queryBlock.update();
}
Related
I'm developing an elementor widget as a plugin. The font view js working fine but the backend (Elementor edit page) js are not working. I'm using hooks (admin_enqueue-scripts, wp_enqueue_scripts, elementor/editor/before_enqueue_scripts, elementor/elements/categories_registered, elementor/widgets/widgets_registered, elementor/editor/after_enqueue_scripts, elementor/frontend/init). Which is perfect the js loading for elementor font page. Now, My js effects are not working on Elementor edit page. How can I solve the problem?
The enqueue code:- `public function bwdic_admin_editor_scripts() {
add_filter( 'script_loader_tag', [ $this, 'bwdic_admin_editor_scripts_as_a_module' ], 10, 2 );
}
public function bwdic_admin_editor_scripts_as_a_module( $tag, $handle ) {
if ( 'bwdic_the_compare_editor' === $handle ) {
$tag = str_replace( '<script', '<script type="module"', $tag );
}
return $tag;
}
private function include_widgets_files() {
require_once( __DIR__ . '/widgets/bwdic-compare.php' );
}
public function bwdic_register_widgets() {
// Its is now safe to include Widgets files
$this->include_widgets_files();
// Register Widgets
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Widgets\BWDMEcompare() );
}
private function add_page_settings_controls() {
require_once( __DIR__ . '/page-settings/image-compare-manager.php' );
new Page_Settings();
}
// Register Category
function bwdic_add_elementor_widget_categories( $elements_manager ) {
$elements_manager->add_category(
'bwd-image-compare-category',
[
'title' => esc_html__( 'BWD Image Compare', 'bwd-image-compare' ),
'icon' => 'eicon-person',
]
);
}
public function bwdic_all_assets_for_the_public(){
wp_enqueue_script( 'bwdic_compare_the_main_js', plugin_dir_url( __FILE__ ) . 'assets/public/js/custom.js', array('jquery'), '1.0', true );
$all_css_js_file = array(
'bwdic_compare_main_css' => array('bwdic_path_define'=>BWDIC_ASFSK_ASSETS_PUBLIC_DIR_FILE . '/css/style.css'),
);
foreach($all_css_js_file as $handle => $fileinfo){
wp_enqueue_style( $handle, $fileinfo['bwdic_path_define'], null, '1.0', 'all');
}
}
public function bwdic_all_assets_for_elementor_editor_admin(){
wp_enqueue_script( 'bwdic_compare_the_main_js_admin', plugin_dir_url( __FILE__ ) . 'assets/public/js/custom.js', array('jquery'), '1.0', true );
$all_css_js_file = array(
'bwdic_compare_admin_icon_css' => array('bwdic_path_admin_define'=>BWDIC_ASFSK_ASSETS_ADMIN_DIR_FILE . '/icon.css'),
);
foreach($all_css_js_file as $handle => $fileinfo){
wp_enqueue_style( $handle, $fileinfo['bwdic_path_admin_define'], null, '1.0', 'all');
}
}
public function __construct() {
// For public assets
add_action('wp_enqueue_scripts', [$this, 'bwdic_all_assets_for_the_public']);
// For Elementor Editor
add_action('elementor/editor/before_enqueue_scripts', [$this, 'bwdic_all_assets_for_elementor_editor_admin']);
// Register Category
add_action( 'elementor/elements/categories_registered', [ $this, 'bwdic_add_elementor_widget_categories' ] );
// Register widgets
add_action( 'elementor/widgets/widgets_registered', [ $this, 'bwdic_register_widgets' ] );
// Register editor scripts
add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'bwdic_admin_editor_scripts' ] );
$this->add_page_settings_controls();
}`
I have tried both wp_localize_script and wp_add_inline_script : it doesn't work the way I expect.
I have this in my plugin's PHP file (it is enqueued with wp_enqueue_scripts somewhere else but I don't need to write the code here right ?) :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false
);
wp_enqueue_script(
'custom-profile-script'
);
wp_localize_script(
'custom-profile-plugin',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_add_inline_script( 'custom-profile-plugin', 'const PHPVAR = ' . json_encode( array(
'plugin_url' => "url"
) ), 'before' );
And then, in my js file :
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(PHPVAR.plugin_url);
});
The first console log (related to wp_localize_script) is an object that contains "ajax_url" and "ajax_nonce" with the right values, but "plugin_url" doesn't appear and is UNDEFINED when I call it using wp_ajax.plugin_url.
The second console log (related to wp_add_inline_script) tells me that PHPVAR is not defined...
What I don't understand is why the first two values are passed correctly using localize script, but not the third one and, furthermore, why wp_add_inline_script doesn't work.
The script needs to be registered in the footer for the PHP value to be passed, like this :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
true // register script in the footer
);
Instead of :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false // default value of the wp_register_script function that registers script in header
);
You need to add wp_enqueue_script after wp_localize_script and also you add wrong handle to wp_localize_script check the below code.
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
true
);
wp_localize_script(
'custom-profile-script',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_enqueue_script(
'custom-profile-script'
);
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(wp_ajax.plugin_url);
});
I have a problem to solve for coders and AJAX lovers.
I have examples of code javascript, jquery, and php.
function find_page_number( element ) {
element.find('span').remove();
return parseInt( element.html() );
}
$(document).on( 'click', '#PaginationExample a', function( event ) {
event.preventDefault();
page = find_page_number( $(this).clone() );
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
beforeSend: function() {
$('#showcase').find( 'article' ).remove();
$('#showcase nav').remove();
$(document).scrollTop();
$('#showcase').append( '<div class="page-content" id="loader">Loading New Posts...</div>' );
},
success: function(html ) {
$('#showcase').empty();
$('#showcase').append(html );
},
})
})
})(jQuery);
functions.php
add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination' );
add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination' );
function ajax_pagination() {
$query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );
$query_vars['paged'] = $_POST['page'];
$posts = new WP_Query( $query_vars );
$GLOBALS['wp_query'] = $posts;
add_filter( 'editor_max_image_size', 'my_image_size_override' );
if( ! $posts->have_posts() ) {
get_template_part( 'content', 'none' );
}
else {
while ( $posts->have_posts() ) {
$posts->the_post();
get_template_part( 'content', get_post_format() );
}
}
remove_filter( 'editor_max_image_size', 'my_image_size_override' );
the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'webisawesome' ),
'next_text' => __( 'Next page', 'webisawesome' ),
'before_page_number' => '<ul id="PaginationExample">' . __( 'Page', 'webisawesome' ) . ' </ul>',
) );
wp_die();
}
function my_image_size_override() {
return array( 825, 510 );
}
function add_myjavascript(){
wp_enqueue_script( 'ajax-pagination', get_template_directory_uri(). '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true );
global $wp_query;
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'query_vars' => json_encode( $wp_query->query )
));
}
add_action( 'init', 'add_myjavascript' );
html part
<nav> <ul id='PaginationExample' style=" display:flex;
justify-content:center;">
<li><?php previous_posts_link('« Back ') ?></li>||
<li><?php next_posts_link('Forward »') ?></li>
</ul></nav>
So who can answer why it returns to 0 after clicking pages? Does anybody know what can be wrong and what is missing to make the code to work properly and page posts? My website is https://www.webisawesome.com/category/services WordPress based:) Let me know if you need more information about it. Thanks to all!
The weird problem I am facing is that the hl_admin_script wont load in footer. But it load work when I change the $in_footer to false
/*
Load Admin Scripts only on custom-post-type post type.
*/
function hl_enqueue_admin() {
global $post;
$screen = get_current_screen();
if ($screen->post_type !== 'custom-post-type') {
return;
}
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-widget');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('jquery-ui-accordion');
wp_enqueue_style( 'hl_jquery-ui', plugins_url( 'css/hl-jquery-ui.css', __FILE__ ) , array(), '1.0.0', false );
wp_enqueue_script( 'hl_admin_script', plugins_url( '/js/hl_admin_script.js', __FILE__ ) , array('jquery','jquery-ui-core', 'jquery-ui-sortable','jquery-ui-accordion'), '2.0.0', true );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'hl_admin_script', 'ajax_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'post_id' => $post->ID,
));
}
add_action( 'admin_enqueue_scripts', 'hl_enqueue_admin' ,1000 ,0 );
I have this simple wordpress menu that I want to load in div element.
<?php
$menuParameters = array(
'theme_location' => 'sidebar-menu',
'container' => false,
'echo' => false,
'items_wrap' => '%3$s',
'depth' => 0,
);
echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );
?>
I'm using modernizr and jQuery load() to load the php file into the div element when a certain media query is detected.
jQuery(document).ready(function($){
if(Modernizr.mq('only all and (max-width:600px)')) {
$('#content-wrapper').removeClass('col-4-5');
$("#trending-Container").load( 'wordpress/wp-content/themes/test_theme/navbar-mobile.php' );
}
});
This works if just use some html or if just echo some string but when I use a wordpress function like above or something like the_title() I get a 500 internal server error.
Any ideas?
I suppose you should no directly access any file in your theme for security reasons.
Register your function in funcitons.php in your theme and then call that function_name as refereed over here enter link description here
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
and register your action in functions.php
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) return; // Only applies to dashboard panel
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));
// in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
// Same handler function...
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die();
}