How do we get admin current screen by post id instead of screen id? - wordpress

I need to add css on one single admin page which has post=183 .. Here id is 183.. The below code will work for all the pages but in my case I just want this to have effect in single page. So the best thing will have to be through page/post_id.
function this_screen() {
$current_screen = get_current_screen();
if(( $current_screen ->id === "page") ) {
wp_enqueue_style(
'gp_fp',
get_template_directory_uri() . '/admin/css/block.css');
}
}
Appreciate help.

I would check that:
Current page is admin (so it won't affect the front-end)
Current page is post ID = 183
$post_id = 183;
if (is_admin() && get_post_status($post_id) === false) {
// do something
}
Reference: https://tommcfarlin.com/wordpress-post-exists-by-id/

Related

Hide plugin from admin bar & plugin list

I am trying to hide the following item from the following sections:
Admin bar: ID = wp-admin-bar-nitropack-top-menu
Plugin list: data-slug="nitropack"
I have tried these methods, but can not get it to work. Maybe i have the wrong IDs/Slugs?
Methods: https://divi.space/wordpress-and-divi-code-snippets/hide-any-plugin-from-the-wordpress-dashboard/
Would really appreciate some help, since a customer should not be able to change the settings within this plugin!
Best regards,
Isac
The css way
<style>
a[data-slug="nitropack"] { //hides all a href's with that data slug
display:none;
}
</style>
normally if its an wp admin menu you would do something like this:
//remove admin page item
function edit_admin_menus() {
remove_menu_page("index.php"); //Dashboard
remove_menu_page("itsec"); // wp-admin.php?page=itsec use this "itsec"
}
add_action("admin_menu", "edit_admin_menus");
or you need to remove admin bar item
//remove tool bar item
function remove_toolbar_node($wp_admin_bar) {
// replace 'updraft_admin_node' with your node id "nitropack" something
$wp_admin_bar->remove_node("avia");
$wp_admin_bar->remove_node("updates");
$wp_admin_bar->remove_menu("wp-logo");
$wp_admin_bar->remove_menu("themes");
$wp_admin_bar->remove_menu("widgets");
$wp_admin_bar->remove_menu("dashboard");
//$wp_admin_bar->remove_node("updraft_admin_node");
}
add_action("admin_bar_menu", "remove_toolbar_node", 999);
FYI, since you need to block access to the plugin you'll need to add a redirect based on member role. The customer may know the actual url and can still access the page.
//Admin or Editor role check, if else send to alt url
function block_pages_for_user() {
$blocked_pages = is_page('slug');
$url = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if( !current_user_can('administrator') && !current_user_can('editor') && !current_user_can('subscriber') && $blocked_pages ) {
wp_redirect( 'http://www.example.dev/your-page/', 301 );
exit;
}
}
add_action( 'wp', 'block_pages_for_user', 8 );

Override wordpress routing / url rewriting?

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
}

Wordpress. How to use shortcode with if else statement?

I have following code but it's displaying shortcode in text rather than showing results of shortcode.
$curr_user_id = get_current_user_id();
// the value is 0 if the user isn't logged-in
if ( $curr_user_id != 0 ) {
// we know now the user is logged-in, so we can use his/her ID to get the user meta
$um_value = get_user_meta( $curr_user_id, 'user_phone', true );
// now we check if the value is correct
if ( ! empty( $um_value ) && $um_value == 'French' ) {
// if so we can output something
echo '[ld_course_list course_category_name="french" col=4 progress_bar=true]';
} else {
// else the code, eg.
echo '[ld_course_list course_category_name="english" col=4 progress_bar=true]';
}
}
Above code will result in text below rather than showing results of the shortcode
[ld_course_list course_category_name="english" col=4
progress_bar=true]
How do I change my code so it actually runs shortcode?
Thank you.
Following code worked. Only problem is do_shortcode is breaking stylesheet. Anyone know why or how to fix it?
<?
$curr_user_id = get_current_user_id();
// the value is 0 if the user isn't logged-in
if ( $curr_user_id != 0 ) {
// we know now the user is logged-in, so we can use his/her ID to get the user meta
$um_value = get_user_meta( $curr_user_id, 'user_phone', true );
// now we check if the value is correct
if ( ! empty( $um_value ) && $um_value == 'French' ) {
// if so we can output something
echo do_shortcode('[ld_course_list course_category_name="french" col=4 progress_bar=true]');
} else {
// else the code, eg.
echo do_shortcode('[ld_course_list course_category_name="english" col="4" progress_bar="true"]');
}
}
?>
You are using it in wrong way, the method you are trying is used inside wordpress pages, posts etc.
To use inside plugin, theme or any other .php file, use WordPress function called do_shortcode() that lets you add shortcodes directly in your themes and plugins.
Add it like this:
echo do_shortcode("[ld_course_list course_category_name="english" col=4 progress_bar=true]");

How do you show media posted by a certain user ? Wordpress

How do you show media posted by a certain user in Wordpress?
Say I have the loop...
and im using get_the_author_meta() to retrieve user inf
Now I want to show all the images a certain user has uploaded.
Have no idea where to begin.
Just want to show a list of images that one user has uploaded.
A very common code to allow users to see ONLY their own attachments in the upload page is :
add_action('pre_get_posts','users_attachments');
function users_attachments( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, 'WP_User') )
return;
if( 'upload.php' != $pagenow )
return;
if( !current_user_can('delete_pages') )
$wp_query_obj->set('author', $current_user->id );
return;
}
So based on this, and removing the conditionals you do not need - you could try :
add_action('pre_get_posts','users_attachments');
function users_attachments( $wp_query_obj ) {
$wp_query_obj->set('author', '30' ); // ID of user , or any other meta..
return;
}
or Filter the Query for example :
function user_files_only( $wp_query ) {
global $current_user;
$wp_query->set( 'author', '30' ); // ID of user , or any other meta..
}
add_filter('parse_query', 'user_files_only' );
Both examples actually alter the main query in some way , so you might want to remove the action after applying it . Not sure how this will work on the loop.
You could use the pre_get_posts Filter and to filter the query..
Give a tag as user x for a certain user who posts his media in different categories, now it is easy if anyone press that tag then all the media uploaded by a particular user gets displayed one by one.(i mean that you must use tags for all the posts of the user-x by giving the same tag for all his uploaded media )

add custom class to wordpress nav menu item based on specific condition

I want to add current-menu-item class to the li if it is a single page.
I am trying to do this by using wp_nav_menu_objects hook with a custom function but don't know how to get the particular menu item and set a condition to assign the class to it.
Here is the code.
add_filter('wp_nav_menu_objects' , 'my_menu_class');
function my_menu_class($menu) {
//if it is a single post page of a particular post type (in this case 'property')
if( is_single() && is_post_type_archive( 'property' ) ) {
//get all the menu items
foreach($menu as $key => $item) {
// check if the menu item is "Commercial Property"
if($item == "Commercial Property") {
//assign the class to that menu item
$menu[$key]->classes[] = 'current-menu-item';
}
}
}
return $menu;
}
This code is just to represent the logic. Please suggest if what I need can be achieved with this method or there is a better approach to it.
Thanks.
In my WP theme, I wanted to remove all wordpess menu classes, add my own and on specific condition ( for example if the menu has an active class ) to add another class. Here s my code
function add_custom_classes($classes){
$newClasses[] = "navigation__item";
if( in_array('current_page_item', $classes) ){
array_push($newClasses, "navigation__item-active");
}
return $newClasses;
}
add_filter('nav_menu_css_class', 'add_custom_classes', 100, 1);
add_filter('nav_menu_item_id', 'add_custom_classes', 100, 1);
add_filter('page_css_class', 'add_custom_classes', 100, 1);
You can add your own conditions
is_single is actually looking for a single post. You need is_page
Wordpress already provides the class if it is a single page
current-post-ancestor
on any post detail page you can inspect the menu you will find that class so in other way you can utilize current-post-ancestor class for what you need to do
Hope it makes sense
I have solved it using the HTTP_REFERER to set conditions in the same function.
Don't feel it is the best way to achieve this but it sorts me out.
Here is the code if anyone else needs a reference.
function nav_menu_class($menu) {
//To dynamically get the directory path from the URL irrespective of the local or web server.
$ref = $_SERVER['HTTP_REFERER']; // prev page url.
$split_ref = pathinfo($ref); // splitting the url to seperate the directory (http://dev.calyxagency.com/horizoncapital/site-new/) from the file path.
$dir_path .= $split_ref[ "dirname" ]; // extracting the host + directory from the full path
$class = 'current-menu-item'; // class to be assigned.
foreach($menu as $key => $item) {
if( $menu[$key]-> ID == 101 ) { // check if the menu item matches this ID
if( $ref == $dir_path.'/properties-to-let/' || $ref == $dir_path.'/properties-for-sale/' || $ref == $dir_path.'/commercial-property/' ) {
$menu[$key]->classes[] = $class;
}
} elseif( $menu[$key]-> ID == 15 ) { // check if the menu item matches this ID
if( $ref == $dir_path.'/business-for-sale/' ) { // check if the single page has come from this page for assigning current class to only this menu item
$menu[$key]->classes[] = $class;
}
} elseif( $menu[$key]-> ID == 18 ) { // check if the menu item matches this ID
if( $ref == $dir_path.'/news/' ) { // check if the single page has come from this page for assigning current class to only this menu item
$menu[$key]->classes[] = $class;
}
}
}
return $menu;
}
add_filter('wp_nav_menu_objects' , 'nav_menu_class');

Resources