in WP 4.2 opening Add New Post page and without editing any fields, clicking on "Publish" button page is submitted and reopened, but no any of fields are marked with red background color as required.
How to make it? Seems, that is original behauvior of this page.
I want it to work like editor of categories, when in similar situation field name is marked with red background color as required.
Also I added several fields to New Post page using register_post_type function and I aslo want to marked with red background color as required. Which is the best way for this?
Thanks!
You can call your jquery validation by your self using below code,
Add this code in theme's functions.php and custom.js in your theme js folder
add_action( 'admin_print_scripts-post-new.php', 'custom_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'custom_admin_script', 11 );
function custom_admin_script() {
global $post_type;
// Post type = "post" or "page" you can load script wheater it is post or page , if page then change 'post' to 'page' in below condition
if( 'post' == $post_type )
wp_enqueue_script( 'custom-admin-script', get_stylesheet_directory_uri() . '/js/custom.js' );
}
custom.js
jQuery(document).ready(function ($) {
if ($("#post").length > 0) {
var frm = true;
$("#publish").click(function () {
var title = $("#title").val();
var excerpt = $("#excerpt").val();
// your custom field variable goes here
if (jQuery.trim(title) == "" || jQuery.trim(excerpt) == "") {
frm = false;
}
if (frm == false) {
$("#publish").prop('disabled', true);
} else {
$("#publish").prop('disabled', false);
}
});
}
});
Related
I would like to serve different content based on the URL.
I started with a custom page setup via a custom template but I am open to something else.
The main goal is to have one PHP page that can serve different contents programmatically based on the URL.
For example:
https://some-url.com/my-plugin/ -> run my page
https://some-url.com/my-plugin/foo/ -> run my page
https://some-url.com/my-plugin/foo2/abc/ -> run my page
etc...
I have been looking at add_rewrite_rule, add_rewrite_tag, flush_rewrite_rules and WP_Rewrite API but I am getting confused about which one I should use?
I found an example here but I could not make it work, I get 404s, any idea why?:
/*
Plugin Name: Products Plugin
Plugin URI: http://clivern.com/
Description: Register URL rules for our products
Version: 1.0
Author: Clivern
Author URI: http://clivern.com
License: MIT
*/
function products_plugin_activate() {
products_plugin_rules();
flush_rewrite_rules();
}
function products_plugin_deactivate() {
flush_rewrite_rules();
}
function products_plugin_rules() {
add_rewrite_rule('products/?([^/]*)', 'index.php?pagename=products&product_id=$matches[1]', 'top');
}
function products_plugin_query_vars($vars) {
$vars[] = 'product_id';
return $vars;
}
function products_plugin_display() {
$products_page = get_query_var('pagename');
$product_id = get_query_var('product_id');
if ('products' == $products_page && '' == $product_id):
//show all products
exit;
elseif ('products' == $products_page && '' != $product_id):
//show product page
exit;
endif;
}
//register activation function
register_activation_hook(__FILE__, 'products_plugin_activate');
//register deactivation function
register_deactivation_hook(__FILE__, 'products_plugin_deactivate');
//add rewrite rules in case another plugin flushes rules
add_action('init', 'products_plugin_rules');
//add plugin query vars (product_id) to wordpress
add_filter('query_vars', 'products_plugin_query_vars');
//register plugin custom pages display
add_filter('template_redirect', 'products_plugin_display');
First of all, make sure your pretty permalinks are enabled, in this case the option "Plain" in Settings - Permalinks should be unselected:
Select one of these options to enable pretty permalinks
You can check whether pretty permalinks are enabled in the code like so:
function is_enabled_pretty_permalinks() {
return !empty( get_option( 'permalink_structure' ) );
}
if ( is_enabled_pretty_permalinks() ) {
echo 'Pretty permalinks enabled';
}
Next add a new rewrite rule:
function add_my_rewrite_rule() {
$page_slug = 'products'; // slug of the page you want to be shown to
$param = 'do'; // param name you want to handle on the page
add_rewrite_rule('my-plugin/?([^/]*)', 'index.php?pagename=' . $page_slug . '&' . $param . '=$matches[1]', 'top');
}
add_action('init', 'add_my_rewrite_rule');
Add your parameter to query vars so you will be able to handle it on the page:
function add_my_query_vars($vars) {
$vars[] = 'do'; // param name you want to handle on the page
return $vars;
}
add_filter('query_vars', 'add_my_query_vars');
Then you can access your query var do in the page template or in a shortcode, for example:
function my_plugin_shortcode_handler( $atts ){
$do = get_query_var( 'do' );
if ( $do === 'this' ) {
return 'do this';
} else {
return 'do that';
}
}
add_shortcode( 'myshortcode', 'my_plugin_shortcode_handler' );
Then place the shortcode to the content via Gutenberg.
Check out the links:
https://some-url.com/my-plugin/this/ - outputs "do this"
https://some-url.com/my-plugin/that/ - outputs "do that".
This can be solved by using query params. Like you mentioned you have set up custom page via a custom template. You can read the URL and check for the parameters and based on that you can send data from the PHP template page.
e.g,
function cleanTheInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
if (isset($_GET['page_url'])) {
$theUrl = cleanTheInput($_GET['page_url']);
}
if($theUrl == 266)){
// data for https://some-url.com/?page_url=266
}
if($theUrl == 366)){
// data for https://some-url.com/?page_url=366
}
I am developing a plugin for wordpress and I want to add the button to the header of gutenberg editor just like the one added by Elementor plugin "Edit with Elementor"
Can anyone guide me what should i do to achieve this... Thanks in Advance
I've checked Guternberg source code on header toolbar and unfortunately right now there's only not a beautiful solution possible. You can have 'custom' buttons but they are only done through calling registerPlugin with PluginSidebar component which creates sidebar and button appears on right side for pinned\starred sidebars (like Yoast SEO does).
Elementor does it this way: it subscribes to wp.data store changes and whenever something happens it injects it's button if it's not yet injected. Just because React rerenders DOM it may eventually wipe button out, so subscribing to changes is important so if it wipes out custom button js code just reinjects it.
Below is simplified ES5 code to inject a custom link\button or really any custom HTML into it (just as Elementor does).
// custom-link-in-toolbar.js
// wrapped into IIFE - to leave global space clean.
( function( window, wp ){
// just to keep it cleaner - we refer to our link by id for speed of lookup on DOM.
var link_id = 'Your_Super_Custom_Link';
// prepare our custom link's html.
var link_html = '<a id="' + link_id + '" class="components-button" href="#" >Custom Link</a>';
// check if gutenberg's editor root element is present.
var editorEl = document.getElementById( 'editor' );
if( !editorEl ){ // do nothing if there's no gutenberg root element on page.
return;
}
var unsubscribe = wp.data.subscribe( function () {
setTimeout( function () {
if ( !document.getElementById( link_id ) ) {
var toolbalEl = editorEl.querySelector( '.edit-post-header__toolbar' );
if( toolbalEl instanceof HTMLElement ){
toolbalEl.insertAdjacentHTML( 'beforeend', link_html );
}
}
}, 1 )
} );
// unsubscribe is a function - it's not used right now
// but in case you'll need to stop this link from being reappeared at any point you can just call unsubscribe();
} )( window, wp )
So create a js file in your theme or plugin and then link it this way:
add_action( 'enqueue_block_editor_assets', 'custom_link_injection_to_gutenberg_toolbar' );
function custom_link_injection_to_gutenberg_toolbar(){
// Here you can also check several conditions,
// for example if you want to add this link only on CPT you can
$screen= get_current_screen();
// and then
if ( 'cpt-name' === $screen->post_type ){
wp_enqueue_script( 'custom-link-in-toolbar', get_template_directory_uri() . '/assets/js/custom-link-in-toolbar.js', array(), '1.0', true );
}
}
Again this solution isn't perfect because we just inject our custom HTML into DOM which is managed by Gutenberg(React) but at this point it seems like the only way to achieve it, may be in future we'll have something like filters or hooks which will allow us to inject our custom components being rendered in toolbar but not yet.
Still Elementor does it this way. you can check it's code at
https://github.com/elementor/elementor/blob/master/assets/dev/js/admin/gutenberg.js
Now there is a slot for the Main dashboard button you can use that one
import { registerPlugin } from '#wordpress/plugins';
import {
__experimentalFullscreenModeClose as FullscreenModeClose,
__experimentalMainDashboardButton as MainDashboardButton,
} from '#wordpress/edit-post';
import { close,image } from '#wordpress/icons';
const MainDashboardButtonIconTest = () => (
<MainDashboardButton>
<FullscreenModeClose icon={ close } href="http://wordpress.org" />
<Button variant="primary" icon={image}>
My Button
</Button>
</MainDashboardButton>
);
registerPlugin( 'main-dashboard-button-icon-test', {
render: MainDashboardButtonIconTest,
} );
ref: https://developer.wordpress.org/block-editor/reference-guides/slotfills/main-dashboard-button/
In Gutenberg Editor, I try to modify the categories panel (the one on the right where I choose the categories my post will be placed into).
One should not be able to add a post to a category if that category has child-categories. As the categories are static, it'll be ok to use the category-id.
My idea was to use the enqueue_block_editor_assets and add some javascript to disable the checkbox via the ID of the element.
This does not work, the element could not be found :-(
This is my unfunctional code so far:
functions.php:
function gutenberg_enqueue()
{
wp_enqueue_script(
'gutenberg-additions-script',
get_stylesheet_directory_uri().'/gutenberg-additions.js',
array(), true, true
);
}
add_action('enqueue_block_editor_assets', 'gutenberg_enqueue', 999);
(I use get_stylesheet_directory_uri(), because I am in a child theme)
gutenberg-additions.js:
window.onload = function () {
var cat1 = document.getElementById('editor-post-taxonomies-hierarchical-term-1');
if (cat1 != null) {
cat1.disabled = true;
}
Welcome to Stackoverflow. There is an example about that in the gutenberg github directory. It is written in the old es5 syntax, but should easily be transferrable to esnext. It uses the editor.PostTaxonomyType filter to edit the taxonomies component.
var el = wp.element.createElement;
function customizeProductTypeSelector( OriginalComponent ) {
return function( props ) {
if ( props.slug === 'product-type' ) {
return el(
'div',
{},
'Product Type Selector'
);
} else {
return el(
OriginalComponent,
props
);
}
}
};
wp.hooks.addFilter(
'editor.PostTaxonomyType',
'my-custom-plugin',
customizeProductTypeSelector
);
If you need more information, also read the comments on this github issue.
i am creating plugin for my project. i want to create one page when plugin gets activate and same way i want to delete that page when plugin gets deactivate... i am able to create page but i am facing problem while deleting page...
my code is
global $page_id;
register_activation_hook(__FILE__,'createPage');
register_deactivation_hook(__FILE__, 'dropPage');
function createPage()
{
global $page_id;
$page['post_type'] = 'page';
$page['post_content'] = 'hello this page created by plugin';
$page['post_status'] = 'publish';
$page['post_title'] = 'dpage';
$page_id = wp_insert_post ($page);
}
function dropPage()
{
global $page_id;
wp_delete_page($page_id);
}
it's not deleting page... if i give wp_delete_post('116') then it's working fine... i have assigning page id in global variable then also i am not able to retrieve it..
can any one suggest me how to do it?
Thanks in advance
the global $page_id you're adding will only contain the page ID when you're activating the plugin. To store the page ID, use the Options API.
register_activation_hook(__FILE__,'createPage');
register_deactivation_hook(__FILE__, 'dropPage');
function createPage()
{
$page['post_type'] = 'page';
$page['post_content'] = 'hello this page created by plugin';
$page['post_status'] = 'publish';
$page['post_title'] = 'dpage';
$page_id = wp_insert_post ($page);
update_option('the_page_id_i_created', $page_id );
}
function dropPage()
{
if( get_option('the_page_id_i_created') ){
wp_delete_page( get_option('the_page_id_i_created') );
}
}
I have a "Products" custom post type. Normally, this custom post type have an "Add New" button. I want to add another button call "Update from Provider".
Currently, I have modify the Wordpress code (in "wordpress\wp-admin\includes\class-wp-list-table.php") to add that button. In this case, when I update Wordpress, my modified code will be deleted. Therefore, I need to move that button to my plug-in code.
In this case, please help me how to move that button to my plug-in code.
Well, if you opened the core file you saw that there's no action in it where we can hook.
Only a couple of filters. We can use the following:
add_filter( 'views_edit-movies', 'so_13813805_add_button_to_views' );
function so_13813805_add_button_to_views( $views )
{
$views['my-button'] = '<button id="update-from-provider" type="button" title="Update from Provider" style="margin:5px">Update from Provider</button>';
return $views;
}
It produces this:
To put it in an approximate position from where you'd like, use the following:
add_action( 'admin_head-edit.php', 'so_13813805_move_custom_button' );
function so_13813805_move_custom_button( )
{
global $current_screen;
// Not our post type, exit earlier
if( 'movies' != $current_screen->post_type )
return;
?>
<script type="text/javascript">
jQuery(document).ready( function($)
{
$('#update-from-provider').prependTo('span.displaying-num');
});
</script>
<?php
}
Which results in this: