Using Wordpress Theme Mod Better - php

I am adding some Custom Controls to the Wordpress Customizer and using those controls to style a slider. I was wondering if there was a better way to implement this than how I've already done. I don't really understand the if statements here, but I know that it works. Any help is much appreciated!
function apache_c_slider_css() {
?>
<style type='text/css'>
<?php
$slider_height = get_theme_mod( 'slider_height', '500' );
if ( ! empty( $slider_height ) ) {
?>
#slider,
.slides,
.slide {
height: <?php echo $slider_height; ?>px;
}
<?php
}
$slider_max_height = get_theme_mod( 'slider_max_height', '100' );
if ( ! empty( $slider_max_height ) ) {
?>
#slider,
.slides,
.slide {
max-height: <?php echo $slider_max_height; ?>vh;
}
<?php
}
?>
</style>
<?php
}

Truthfully, you don't even need the if statement, because you're passing a default value to get_theme_mod(), so it shouldn't ever be empty. Generally speaking, if you don't have a default value, or there's even a chance of an empty value, you'll want to check that condition - but you shouldn't need to here. If you want to, you could combine them into a single if statement like so:
if ( !empty( $slider_height ) || !empty( $slider_max_height ) ){
// Code
}
The pipes || indicate PHP's Logical "OR" Operator, so if either isn't empty, it will proceed. That said, this is probably how I'd modify your current code:
function apache_c_slider_css(){
$slider_height = get_theme_mod( 'slider_height', '500' );
$slider_max_height = get_theme_mod( 'slider_max_height', '100' );
echo '<style type=\'text/css\'>
#slider,
.slides,
.slide {
height: '. $slider_height .'px;
max-height: '. $slider_max_height .'vh;
}
</style>';
}
The declarations will return the theme mod that's set, or 500 pixels and 100 viewport height % by default.
And lastly you can output the whole thing at once.
With that said, "baking in" scripts and styles generally isn't the best way to go about adding CSS and JS in WordPress, especially if you're working on a theme. This kind of CSS is a textbook example of code that should be added with the wp_add_inline_style() function to extend your theme's main styles.

Related

php function to change css

I'm trying to add a piece of code to change css on a page. I added the code to functions.php in WordPress. However, it does not seem to work. Since I'm quite new to this there might be something quite basic wrong with the code... Any idea why it might not be working?
// This code is added to functions.php
// intro is the class name of the element I'm trying to change
add_action( 'intro', function () {
if ( is_user_logged_in() ) {
?>
<style>
display: none!important;
</style>
<?php
};
exit;
});
I got it to work by removing exit; and targeting an element:
add_action( 'wp_head', function () {
if ( is_user_logged_in() ) {
?>
<style>
.intro{
display: none!important;
}
</style>
<?php
};
});
I think what you are trying to do is change the content of the css class which I do not think you can do. Instead a solution would be to assign a css class with the propertied that you want applied to the element e.g.
<div class="<?php if ( is_user_logged_in() ) { echo 'intro';} ?>">
// Whatever you have here will get the css style applied
// if user is logged in
</div>
And inn The CSS you have the following
.intro{
display: none!important;
}
You can create multiple files for different styles e.g. another class
.outro{
display:initial;
}
And you can add it in the code as
<div class="<?php if ( is_user_logged_in() ) { echo 'intro';} else{ echo 'outro';} ?>">
// Whatever you have here will get the css style applied
// if user is logged in and if logged out then outro class will be applied
</div>

How to disable product image thumbnails for woocommerce gallery?

I work on slider for woocommerce product gallery and I don't use/need the generated thumbnails, because I use "dots" for navigation and I want to hide/unload the generated thumbnails by woocommerce gallery.
Firstly, I put this in my theme functions.php file :
remove_theme_support( 'wc-product-gallery-slider' );
And actually, I just put "display:none" in my css file and I make this for the product-thumbnails.php :
// Note: `wc_get_gallery_image_html` was added in WC 3.3.2 and did not exist prior. This check protects against theme overrides being used on older versions of WC.
if ( ! function_exists( 'wc_get_gallery_image_html' ) ) {
return;
}
global $post, $product;
$attachment_ids = $product->get_gallery_image_ids();
if ( $attachment_ids && $product->get_image_id() ) { ?>
<div class="slider product-responsive-thumbnail" id="product_thumbnail_<?php echo esc_attr( $post->ID ); ?>">
<?php foreach ( $attachment_ids as $attachment_id ) { ?>
<div class="thumbnail-wrapper">
<?php echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', wc_get_gallery_image_html( $attachment_id ), $attachment_id ); // phpcs:disable WordPress.XSS.EscapeOutput.OutputNotEscaped ?>
</div>
<?php
} ?>
</div>
<?php
}
?>
I would like to disable the generation of thumbnails and its display completely to optimize the loading of my page!
I know that I can totally delete the contents of the file "produtc-thumbnails.php" but it is a bit raw method and I would like to know if this is possible with another less raw method
As #7uc1f3r suggested to me,
First simple solution. Mask in the woocommerce-general.css file like this:
.woocommerce div.product div.images .flex-control-thumbs {
overflow: hidden;
zoom: 1;
margin: 0;
padding:0;
display:none; /* this hide the thumbnails */
}
Second solution, put "false" in the product-thumbnails.php
if ( ! function_exists( 'wc_get_gallery_image_html' ) ) {
return;
}
global $post, $product;
$attachment_ids = false; // This disable the thumbnails
And voilà, now it's up to you to choose the method you want to keep.

Output Custom CSS Settings in PHP

I'm trying to output some CSS i the head of my page with custom settings from my theme customizer. The code below works great when there is a value but the problem is when there is no value, it still outputs everything else. I would only like it to appear if there are custom settings.
<style>
body {background-color: <?php echo $background_color; ?>;}
</style>
I think it needs some kind of conditional statement?
You can wrap conditionals around the declaration if necessary... For example:
<style>
body {
<?php if(!empty($background_color)) : ?>
background-color: <?php echo $background_color; ?>;
<?php endif; ?>
}
</style>
If background-color will always be present, and you're looking to allow the background color to be overridden, you could do something like this:
<style>
body {
background-color: <?php echo !empty($background_color) ? $background_color : '#fff'; ?>;
}
</style>
In this example, the background color will default to #fff. This method is known as the ternary operator.
You'll want to only render something out to the browser IF there's a background-color available.
This approach only renders out the inline script IF there's a background-color. This technique avoids an empty CSS declaration in the DOM.
<?php if ( $background_color ) : ?>
<script>
body {
background-color: <?php esc_html_e( $background_color ); ?>;
}
</script>
<?php endif; ?>
A Full Solution
Another way to handle it is to use wp_add_inline_style() and let WordPress handle it.
add_action( 'wp_enqueue_scripts', 'build_and_enqueue_dynamic_css' );
/**
* Build and enqueue dynamic inline head CSS.
*
* #since 1.0.0
*
* #return void
*/
function build_and_enqueue_dynamic_css() {
// do the business logic to get the styles
$background_color = ''; //you need to write this code.
// Now check if you have a background color. If no, bail out.
if ( ! $background_color ) {
return;
}
$css =
"body {
background-color: {$background_color};
}";
wp_add_inline_style( 'your_theme_name_inline_css', $css );
}
I think this is more like what I'm looking for, but now I need a default color for background_color, before there's one input.
<?php self::generate_css( 'body', 'background-color', 'background_color' ); ?>
I ended up using get_theme_mod, which allows for a default setting. Since there's always going to be at least a default setting, there's no need for conditional statements to omit style, body, background-image, etc.
<style type="text/css">
body { background-image: url("<?php echo get_theme_mod( 'background_image' , get_template_directory_uri() . '/images/default.jpg' ); ?>"); }
</style>
You could do something like:
<style>
body {
<?php echo (!empty($background_color)) ? "background-color: " . $background_color.";" : "";
?>
}
</style>

Redirecting logged out users from specific pages

I have a wordpress website, its using buddypress and bbpress. I need to hide/redirect all the buddypress and bbpress pages from people who are not logged in. So if someone lands on the members page, profile page or any forum topic it needs to redirect them to the signup page.
I tried maybe 5 plugins, all of them caused issues like 404 errors, not working or just white pages.
The url structure is like this:
www.example.com/members
www.example.com/members/luke
www.example.com/forums
www.example.com/forums/forum/general-chat
Does anyone know how I can do this without a plugin?
you have to modify from within a child theme the profile-loop.php file
your-child-theme/members/single/profile/profile-loop.php
On the first line of the file, add
<?php if ( is_user_logged_in() ) : ?>
At the end of the file, insert between the last endif and the last do_action this:
<?php else : ?>
<?php echo “<div style=’width: 600px;height:25px; padding: 4px; border: 3px solid #ff0000; text-align: center; font-style:bold; font-size: 1.3em;’> You must be logged in to view a member profile</div>”; ?>
<?php endif; ?>
Change the div inline style to whatever you need accordingly to your theme. The example fits with bp-default.
If you can not do that, then try this plugin,
plugin
Try this but make sure to change the url to what you want
add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' );
function redirect_non_logged_users_to_specific_page() {
if ( !is_user_logged_in() && is_page('add page slug or i.d here') && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
wp_redirect( 'http://www.example.dev/page/' );
exit;
}
Try this in your theme/functions.php or in bp-custom.php:
function lukedi_private_check() {
if ( ! is_admin() && ! is_user_logged_in() ) {
if ( is_front_page() || is_home() || bp_is_register_page() || bp_is_activation_page() )
return;
$redirect_url = trailingslashit( site_url() ); // change this to whatever you need
// member page
if ( bp_is_user() )
bp_core_redirect( $redirect_url );
// bbPress
if( is_bbpress() )
bp_core_redirect( $redirect_url );
// members loop
$bp_current_component = bp_current_component();
if ( false != $bp_current_component ) {
if ( 'members' == $bp_current_component )
bp_core_redirect( $redirect_url );
}
}
}
add_action( 'bp_ready', 'lukedi_private_check' );

Check if current user is administrator in wordpress

I am developing a plugin for wordpress, I want to find if current user is administrator or not, unfortunately I could not use the current_user_can() as it gives me error, so am using the global $current_user. But I could not get inside the if part even for admin user.. How to fix this?
global $current_user;
if ($current_user->role[0]=='administrator'){
function hide_post_page_options() {
//global $post;
// Set the display css property to none for add category and add tag functions
$hide_post_options = "<style type=\"text/css\"> .jaxtag { display: none; } #category-adder { display: none; } </style>";
print($hide_post_options);
}
add_action( 'admin_head', 'hide_post_page_options' );
}
Try something like the following:
if ( current_user_can( 'manage_options' ) ) {
/* A user with admin privileges */
} else {
/* A user without admin privileges */
}
Read more about the current_user_can function here.
Get the user and check if it has the role adminstrator, like so:
function is_site_admin(){
return in_array('administrator', wp_get_current_user()->roles);
}
if (is_site_admin()) {
echo 'Woot Woot';
} else {
echo 'So sad, I have no rights';
}
This works for me:
global $current_user;
if( !empty($current_user->roles) ){
foreach ($current_user->roles as $key => $value) {
if( $value == 'administrator' ){
Do Something
}
}
}
If it's not a multi-site set-up, you can use this to detect an administrator. If it's multi-site, this will only return true for a super admin.
$user_ID = get_current_user_id();
if($user_ID && is_super_admin( $user_id )) {
Do Something
}
I know it is an old question but I would like to make this page more useful by addressing the actual issue. The actual issue here is that OP hasn't been able to use current_user_can( 'manage_options' ) in his plugin. Using the function raises the usual undefined function... PHP error. This happens because the plugin gets initialized before WP core completes loading. Fix is very simple. Loading the plugin at appropriate time is the key.
Assuming the admin plugin code resides inside a class MyPlugin, the class initialization should be hooked to init. Following is one way of doing it.
/**
* Plugin Class
*/
class MyPlugin{
public function __construct(){
/* all hooks and initialization stuff here */
/* only hook if user has appropriate permissions */
if(current_user_can('manage_options')){
add_action( 'admin_head', array($this, 'hide_post_page_options'));
}
}
function hide_post_page_options() {
// Set the display css property to none for add category and add tag functions
$hide_post_options = "
<style type=\"text/css\">
.jaxtag { display: none; }
#category-adder { display: none; }
</style>";
print($hide_post_options);
}
}
add_action('admin_init', function(){
$myplugin = new MyPlugin();
});
This is a way of making sure that wordpress core is available to the plugin function.
You can find admin_init documentation here.
P.S. You should look into using PHP HEREDOC. It is a very simple way of writing multi-line strings. Your style block can be re-written as follows
$hide_post_options = <<<HTML
<style type="text/css">
.jaxtag { display: none; }
#category-adder { display: none; }
</style>
HTML;
I hope it helps somebody.
Thanks.
Too late for an answer for this question, but I think it might be useful anyway if someone ends up here like me.
I needed a quick solution to this problem - check if the current user is admin or not.
From the WP codex I got a simple solution which is to use..
if(is_super_admin($user_id)) {
// do stuff for the admin user...
}
According to WP-Codex this function returns True if the currently logged in user is network (super) admin. This function returns True even if the network mode is disabled but the current user is admin.
<?php
if( current_user_can( 'administrator' ) ){} // only if administrator
if( current_user_can( 'editor' ) ){} // only if editor
if( current_user_can( 'author' ) ){} // only if author
if( current_user_can( 'contributor' ) ){} // only if contributor
if( current_user_can( 'subscriber' ) ){} // only if subscriber
?>
More info here: How To Check If User Is Administrator Or Editor In WordPress
use this code, I hope this solve your problem
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
echo trim($user_role);
$user=wp_get_current_user();
if(in_array("administrator", $user->roles)){
//user role is admin
}

Categories