INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is it possible to dynamically redirect URL using htaccess? Is there any way to dynamically redirect URLs. For example, I want to redirect any URL from ` to ` Where `NNNNN` could be any possible numbers. For example: ` should redirect to `
StackOverflow has already an answer for your question: < I guess that this should do the trick: RewriteRule ^(\d+)$ /?p=$1 [R=302,L]
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "htaccess" }
Woocommerce - Default product image by user role I would like that only the user role 'customer' see the product images and all the other roles see a default product image. I am searching to do this with no luck. Can someone help me please? I managed to do the same for the product prices and this is working correctly The code I added to functions.php is: function ace_hide_prices_guests( $price ) { if(current_user_can('customer')) { return $price; } return ''; } add_filter( 'woocommerce_get_price_html', 'ace_hide_prices_guests' ); Thanks
/** * Only allowing the customer and admin user role to view the product images * * @param $value * * @return bool */ function woocommerce_product_get_image_id_callback( $value ) { global $current_user; if ( in_array( 'customer', (array) $current_user->roles ) || in_array( 'administrator', (array) $current_user->roles ) ) { return $value; } else { return false; } } add_filter( 'woocommerce_product_get_image_id', 'woocommerce_product_get_image_id_callback', 10, 1 ); Copy the above code and paste it into you functions.php file of your child themes
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to use div class between the shortcode variable? i called wordpress function between the shorcodes as a input. <?php echo do_shortcode('[shortcode]'.$var.'[/shortcode]');?> how to add div class for the $var here? I tried few combination but it works for the full shortcode. i just want to use the div only for $var. I tried like, <?php echo '<div class="own">', do_shortcode( '[shortcode]'.$var.'[/shortcode]'), '</div>' ; ?> How to add div class only for $var here?
It's a bit difficult to understand or provide an accurate answer as we don't know what the shortcode is executing. Is it stripping html or any other parsing? If this is your own code, then you could add it in the function the shortcode is calling. If its not you could try a couple options: 1: (adding the div directly into the shortcode call) <?php echo do_shortcode( '[shortcode]<div>'.$var.'</div>[/shortcode]'), ; ?> 2: add it to the `$var` first: <?php $dvar = '<div class="own">'.$var.'</div>'; echo do_shortcode('[shortcode]'.$dvar.'[/shortcode]'); ?> Again, the ideal solution would be to see that function and then put the div directly in before the shortcode is executed.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "shortcode" }
Remove Jetpack infinite-wrap I'm trying to remove the infinite-wrap class jetpack adds to posts with infinite scroll turned on because I want to add infinitely loaded posts to a gridded layout. I found the article here that says to add the theme support stuff to the functions.php :< I ended up adding add_theme_support( 'infinite-scroll', array( 'wrapper' => false, ) ); The weird thing is this has no effect. I have jetpack installed as a plugin and turned on infinite scroll the the settings in the dashboard. Am I doing something wrong? This seems like it should be easy...
Since I was using the underscores.me theme, I had to look in the 'inc' folder for the jetpack.php file. There is where I had to change the options to get the desired effect.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, plugin jetpack, infinite scroll" }
I would like some help wth an SQL query to link posts with categories I am extracting data from my Wordpress database to analyse site structure. Works pretty good so far but I would like to include the posts main category in the table to enable further analysis. This is my current query: SELECT post_name, post_content FROM wp_posts WHERE post_type='post' AND post_status='publish' How can I enhance this query to include the main category in the result? I am pretty simple when it comes to SQL queries and would love to learn more.
You need to `JOIN` the term tables with the posts table, something like this: SELECT p.post_name, p.post_content, t.name FROM wp_posts p JOIN wp_term_relationships tr ON ( tr.object_id = p.ID ) JOIN wp_term_taxonomy tt ON ( tt.term_taxonomy_id = tr.term_taxonomy_id ) JOIN wp_terms t ON ( t.term_id = tt.term_id ) WHERE p.post_type='post' AND p.post_status='publish' AND tt.taxonomy = 'category' Let me know if you have any questions!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql" }
Adding body class to login page? I can't figure out for the life of me how to add a custom body class to the WordPress login page. I found this thread, which suggests using the `admin_body_class` along with this one to check if the current page is the login, and nothing seems to work. I have a multisite network going, and my ultimate aim is to add the `blog_id` number for each site to its corresponding login page as a body class- is this possible? This is one approach I've tried, to no avail: function login_body_class($classes) { global $blog_id; if ( $GLOBALS['pagenow'] === 'wp-login.php' ) { $append = ' ' . $blog_id . ' '; $classes .= $append; } return $classes; } add_filter('admin_body_class', 'login_body_class'); (Given that `admin_body_class` takes a string and not an array, I've added in spaces before/after the class name.) Thanks for any insight here!
I think you're on the right track with a filter. Have you tried `login_body_class` _as the filter?_ function add_blog_id_to_login_page( $classes ) { $blog_id = get_current_blog_id(); $classes[] = "blog-{$blog_id}"; return $classes; } add_filter( 'login_body_class', 'add_blog_id_to_login_page' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp admin, hooks, login, body class" }
how to build (custom) stats for post views, per month Does anyone know how I could code something to get the most viewed posts per month (without Jetpack), ideally without having to create a new DB table ? Maybe there is a smart way to achieve this only using post metas and/or transients. For the moment, i'm storing an array of stat entries as a post meta, containing a timestamp. Each time the meta is updated, I delete the timestamps < 1 month. It works, but i'm not sure that it is a good solution. Any ideas ? Thanks
I think I'd build that upon and already existing plugin that does the counting for me. I have made quite good experience with Post Views Counter as it also lets you use it in `WP_Query`. But WP-PostViews looks promising as well. Choose one. Next I'd query posts by view count from a WordPress cron event that runs monthly. And I'd simply save/add the results in an Options API option as array like `$data[INTEGER_YEAR][INTEGER_MONTH][INTEGER_POST_ID][INTEGER_VIEW_COUNT]`. And pull that off whenever I need it for displaying the high score in a widget or where ever.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "post meta, transient, statistics" }
How to remove the woocommerce_checkout_process action hook in woocommerce if particular project in cart I need to remove checkout page field validation if a particular product is in the cart. Plugin code : add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); function my_custom_checkout_field_process() { // Check if set, if its not set add an error. if ( ! $_POST['developer_name'] ) wc_add_notice( __( 'Please fill in your name.' ), 'error' ); } I need to remove this action hook `my_custom_checkout_field_process` only if the customer added the product_id (19) to the cart. Else there's no need to remove the `add_action`.
try this below code in your function.php file or in your plugin add_action("init", function () { // removing the woocommerce hook foreach( WC()->cart->get_cart() as $cart_item ){ $product_id = $cart_item['product_id']; if($product_id!='19') { remove_action('woocommerce_checkout_process', 'my_custom_checkout_field_process'); } } });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development, woocommerce offtopic" }
Wordpress Featured Image meta box not showing For some reason, the Featured Image box is not showing. I checked under the screen options and it is not showing. Since it is an MU site, I even checked under the main dashboard and still, I'm not seeing that option. I also checked for the setting under the settings and I don't still see the option. Here is what I have: WPBakery Page Builder as the main editor and my current version of Wordpress is 5.1.1 . Thank you, Kevin
You might be facing this problem because your theme does not support featured images. But you can easily add that support, so no worries :) To quote the WordPress Theme Handbook: > Themes must declare support for the Featured Image function before the Featured Image interface will appear on the Edit screen. Support is declared by putting the following in your theme’s `functions.php` file: `add_theme_support( 'post-thumbnails' );` So just add that line to `functions.php` (of your own theme or child theme), and you will be able to see the Featured Image option after you save and refresh the admin area page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, metabox" }
How do I activate a certain block template only when editing the front page? I've chosen a custom page(-post) to be my front page. Now I want to use a block template only on that page, when editing it in the Gutenberg editor. As I understand it I have to add it on "init" or close to it, before I know the post_ID so I can't do a `if ( get_option( 'page_on_front' ) === $post_ID )`. What are my options? **Edit:** I've tried this but since is_front_page() is returning 'false' it doesn't work: function home_block_template() { $post_type_object = get_post_type_object( 'post' ); if ( is_front_page() ) { $post_type_object->template = array( array( 'core/image', array() ), ); } } add_action( 'init', 'home_block_template' );
Setting `$post_type_object->template` seems to be done on 'init' (or close to it) while `is_front_page()` is set later, so I had to use `$_GET['post']` instead. I also changed `get_post_type_object( 'post' )` to 'page'. Like this: add_action( 'init', 'home_block_template' ); function home_block_template() { if ( ! is_admin() || ! isset( $_GET['post'] ) || get_option( 'page_on_front' ) !== $_GET['post'] ) { return false; } $post_type_object = get_post_type_object( 'page' ); $post_type_object->template = array( array( 'core/list' ), ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, frontpage" }
add_query_arg not work in admin I have code: class some{ public function run(){ add_filter('query_vars', array( $this, 'addPar')); $this->some_body(); } public function addPar($vars){ $vars[] = "my_par"; return $vars; } public function some_body(){ if(isset( get_query_var('my_par')) { $value = get_query_var('my_par'); echo $value; } echo '<li><a href="'.esc_url(add_query_arg(array('my_par' => '4'))).'">></a></li>'; } } And `get_query_var()` not work. **SOLUTION** In back-end this function not work probably. I use instead `$_GET`.
`some_body` needs to be run as an action on `pre_get_posts`. Here's an example of the entire process of adding new query vars. Pay extra attention to `myplugin_pre_get_posts`: function myplugin_pre_get_posts( $query ) { ... $city = get_query_var( 'city' ); ... } add_action( 'pre_get_posts', 'myplugin_pre_get_posts', 1 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, functions, query" }
Editing admin pages in WordPress I’m trying to find information on how to edit admin pages in WordPress. Custom pages can be overridden in the site template, but I still do not understand how to deal with the admin. > Note: In my case this is the WooCommerce order edit page, but you may provide the generic solution to the problem. The main thing is to make changes to the admin page.
There are no templates for the admin pages. You have two options to manipulate them, anyway: 1. Use filters to edit the pages (See the WordPress codex). 2. Change the page using CSS (also using a hook or use an existing plugin like Add Admin CSS). There are more plugins that help you changing the admin backend - a recommendation depends a bit on what _exactly_ you want to change.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, admin" }
Custom access given to Admin dashboard In my site I like to give admin dashboard access to Staff members,But in some custom ares should be denied.For example Like blue color area can be access but red color area should be denied. ![enter image description here]( How can I do ? Thanks in Advance.
As your question is too broad and you do not specify what they should be allowed to access the answer is also broad. you can modify the role system with the "user role editor" plugin. < It's for setting specific rights for user roles like for Admin, subscriber or even shop roles in woocommerce. If the right you explicitely need is not provided you need to add it programmatically. But for the first i would try that plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic, admin menu, dashboard" }
Embed Form In Header I'm using WordPress theme Twenty Ninteen and trying to make a travel blog with the help of travel affiliate API get from Travelpayouts. <script charset="utf-8" src="//www.travelpayouts.com/widgets/920a6b8c6fc20070013d2e04f690210d.js?v=1649" async></script> This is form code to display on pages/post, if I use on any post on page code working fine but I need to add this code in the header to display like. ![form image]( I try to use the plugin for header & footer to paste the code & display but via plugin code working in the footer but in header nothing display.
You need to edit `header.php` of your theme and insert the script there right after the site navigation. > I try to use the plugin for header & footer to paste the code & display but via plugin code working in the footer but in header nothing display. Plugins fail to insert this in header because these plugins use `wp-header` hook which output in `<head>` tag and not in the `<body>` tag, so the output is not visible. While those plugins which uses `wp_footer` hook outputs everything within `<body>` tag, so the output is visible.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom header" }
Coming soon page used instead of home page I am new in WordPress I have problem regarding coming soon page. I developed my hole one pager website and set my static page home also disable coming soon page (of hosting provider also) after that I done google indexing but when I search url my domain showing coming soon page I dont know where is this page set in wordpress Please help me to show my home page when i search my url.
It looks like your theme has some sort of maintenance mode - there is a CSS class on the `<body>` of `elementor-maintenance-mode` Have a look at the documentation here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "homepage" }
XMLHttpRequest of admin data to public I have a function that get the data from a admin page and display the result at frontpage. But only works when admin user is logged in. How can I display the result even if user is not logged in? Here the code in apoiadores.js xhr.open("GET", " xhr.addEventListener("load", carregarapoiadores); xhr.addEventListener("load", preco); xhr.send();` and here the code in functions.php function apoiadores () { wp_enqueue_script('apoiadores', get_template_directory_uri() . '/chsv/js/apoiadores.js', array('jquery'), '', true); } add_action('wp_enqueue_scripts', 'apoiadores'); function prazo () { wp_enqueue_script('prazo', get_template_directory_uri() . '/chsv/js/prazofinal.js', array('jquery'), '', true); } add_action('wp_enqueue_scripts', 'prazo');`
The short answer is "you can't do that." The WordPress admin content requires a user be logged in to view any of the content. If this were possible, anyone could get into the admin on your site. You will have to make this content available from the front-end by another method.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
Using custom field content as expression in IF statement I want to store some conditional logic in custom post types , and then use these in a plugin to generate new content based on the logic. Eg if a user submits a form with “body temperature”, a conditional logic will tell the user if she has a fever or not, and some extra text. There will be many such logic elements and I would like to maintain them from the front end. I was thinking about putting the above into two posts. One with condition field “temperature > 37” and text “you have a fever”. Then in a plugin loop through logic records, take the conditional field and use it as the expression in an if statement. How to make this work?
I asked the question in another group and here I got an answer that has turned out to be useful. BE AWARE! It must be dealt with with caution as the PHP eval() function can be a significant security risk. Find the answer here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, php, custom field" }
Headless Wordpress redirect front-page to login page Is there any way to redirect ` to ` with `.htaccess` ? I'm using WordPress only for the API.
At the top of your `.htaccess` file _before_ the WordPress front-controller try the following: RewriteRule ^$ /admin [R,L] This redirects ` to ` This is a temporary (302) redirect.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "redirect, htaccess" }
Featured Image not changing Here is what the situation with my featured image. When I try to change the featured on my site. It doesn't change at all. Here is how I currently try to change the featured image on my page: 1. I click on the Add Media button 2. Select the featured image option 3. Select the image 4. Then I click on the update page. For some reason, the image will not change. It is still the old featured image. Is there a reason why it is not changing on the front end. When I go to Facebook or other various social media site, it still shows the old image. I'm using Wordpress 5.1.1 and the featured image bug is happening on the pages. Not the post. The theme that I'm using is Dejure Thank you, Kevin Davis
Sorry you're having trouble with the featured image. Some details that will help the community solve the question: What theme are you using? Without knowing what theme you're using, one approach you might try is removing the featured image from the post/page, then click update. If the featured image is removed, you might then be able to choose another featured image. Another option would be to stop using the Media pop up window and updated the featured image from the Featured Image meta box on the Edit Post screen. **Edit to add the solution from the comments** If you tried the above and it didn't work, the next thing to do is switch themes, then attempt to change the featured image. If that works, then the issue is with the theme, and you might need a new copy of the theme. If that doesn't work, try deactivating all your plugins and then attempting to change it. There may be a plugin conflict as well.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, pages, customization" }
How can I pass a variable set by ACF to header.php? I have created a custom field with Advanced Custom Fields for my posts. My variable is set product_image, so I can print it with: <?php the_field('product_image'); ?> But I need to print it in my site-header section, within **header.php** , _only for single posts_. <?php if( is_single('post') ) { ?> <img src="<?php the_field('product_image'); ?>"> <?php } else { ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"> <img src="<?php echo esc_url( home_url( '/' ) ); ?>/logo.png"> </a> <?php } ?> And it doesn't work.
You can pass the post id as the 2nd argument on `the_field`. global $post; the_field('product_image', $post->ID); or the_field('product_image', get_the_ID());
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom field, advanced custom fields" }
My website is not responsive on mobile devices I'm building a Wordpress website at < I am not able to make it responsive, although all CSS and JS scripts are successfully loaded, as you may see in the Inspector. I guess it's something related to slicknav, although I'm not sure about it, here's the code of my main.js file to call slicknav responsive JS: $(function(){ $('#menu-primary-menu').slicknav({ prependTo: '.site-branding', label: '', allowParentLinks: true }); }); May you guys can check my wesbite with the Chrome Inspector and see if there's something wronng, the Console soesn't print any error so I don't really know what I'm doing worng, I'm anewbie :) Any help will be greatly appreciated!
Often times even if we have setup our media queries correctly, the site still isn't responsive to those queries. You need to set a viewport in your header.php to fix this. More often than not I find that this affects macs instead of PCs. but it's still a good idea to add this no matter the case. In your site `<head>` add this code: <meta name="viewport" content="width=device-width, initial-scale=1"> And it should fix the problem. This is telling the site to be aware of the device width that is viewing the site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "mobile, responsive" }
Why is Wordpress enqueuing admin relevant scripts (e.g., React, ReactDOM, Redux, hooks, TinyMCE etc) when not logged in? In attempting to boost the performance of my website, I've noticed that Wordpress is enqueuing a lot of the admin relevant scripts and stylesheets on the front end. I'm wondering how I can stop this from happening...I was thinking about dequeueing all of the offending, but then my server response time would be slightly slowed. Is there a tried and tested way of doing this?
If your bootstrap or other enqueued scripts have a dependency or name conflict, this could enqueue all these scripts. There are a large number of common scripts in WordPress core that are enqueued under common names. I always recommend prefixing your script names with something specific. wp_enqueue_script( 'theme-bootstrap', ' array( 'jquery' ), '4.3.1', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, wp enqueue script, wp enqueue style, wp register script" }
What is happening to make my Update/Publish button disabled? I'm really wondering... What is WP doing when it disables the Update/Publish button? It seems to happen every once in a while, and I could not say why in goes disabled sometimes for just a few minutes, but some other times it seems to be permanently disabled. So what triggers the Update/Publish button to be disabled (and what reenables it?)
Without seeing your specific situation, I cannot say whether this is what's causing your issues or not, but this is my best guess. WordPress has this cool thing called the Heartbeat API. It pings the server periodically while you're logged in and in the WordPress admin. It does a number of things to help improve the editing experience like auto-save, check if you're logged in, check if someone else is editing your page (or kicks you off), etc. If the heartbeat doesn't execute successfully (or a variety of other situations), it can cause things like the publish button to be disabled. This is actually a good thing since it prevents you from trying to publish without a connection to the server (and potentially losing your work).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "publish" }
SQL query, error I have sql query: $query= "SELECT * FROM files ORDER BY id DESC LIMIT $from, $site WHERE custom > 0"; but not work, i have notice: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax What i do wrong?
You have the `where` clause of the query in the wrong place. Your query should be written like this: `$query= "SELECT * FROM files WHERE custom > 0 ORDER BY id DESC LIMIT $from, $site";` As specified here < in the MySQL reference.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, query, sql" }
Adding additional roles on registration I'm trying to add an additional role for a user when they register if they register as a specific role. Here is my function: function add_secondary_role( $user_id ) { $current_user = wp_get_current_user(); if ( in_array( 'um_dueling-pianist', (array) $current_user->roles ) ) { $user = get_user_by('id', $user_id); $user->add_role('pianist'); } } It doesn't work. I have registered a test account with the role 'um_dueling-pianist' and it does not add the other role of 'pianist.' Those are both the meta values for the user roles and not the display name of the user roles. Any idea what's wrong with my function?
You check the role not for the created user, only the currently logged in user. Try this way: add_action( 'user_register', 'se333727_additional_roles' ); function se333727_additional_roles( $user_id ) { $new_user = get_user_by( 'ID', $user_id ); if ( in_array( 'um_dueling-pianist', (array)$new_user->roles ) ) { $new_user->add_role('pianist'); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, user roles, user registration" }
Remove links from meta widget I've had my wordpress page hosted in a free host. This host added some code in exchange of the free service, like two links to their free and paid services webpages into my `Meta` widget. For me it was ok at that time, but finally I moved my page to a VPS. I **exported** everything with `All-in-One WP Migration` widget, and **imported** it in the new host. So the problem is that these links from my previous free host have appeared again in my `Meta` widget in the new host, due to the import that I've performed. So basically, **how can I remove them**? **How can I edit the Meta widget**? I've tried to do it from the Desktop but I found no way to do it, so I guess it should be done directly modifying the file of the plugin... but I don't know which one it is.
There are 2 things you can do here. If you do not want to touch the source code, install any meta widget plugin editor (example - < and make required changes. If you can access your code, then look for default-widget.php file, find the lines where you have the unnecessary links, delete them and save the file. Please keep a backup copy of the file before you try this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets" }
Don't move sticky posts to the first page After I sticky post, it automatically moves post to the first page and I'd like it to stay at it's recent place. Don't want it to move. How can I do this? I just need sticky post option (i've got an option to sort posts in slider by sticky posts) but without any of its functionalities I'm using ToroPlay 3.1 theme
1: Don't change the core feature. If you really wanna do this then you need to find another solution for creating custom Category and add some styling for that category. 2: WordPress will add category classes on each post if your theme doesn't disabled it. Then you need to write CSS for that classes and it's gonna be resolved. 3: If you wanna use the theme sticky post styles. Then in your theme folder style.css, There have a .sticky classes out there and you need to change it or add your category css. Thanks.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sticky post" }
WP-CLI Process Killed I have around 1200 large images which I'd like to regenerate. I'm using the WP-CLI command `wp media regenerate`. After around 61 images are generated, the terminal shows the message `Killed`. ![enter image description here]( Why is this happening and how can I fix it?
Which version of WP-CLI are you using? What is `wp --version` returning you? Seems a little bit that you may be running out of memory as this is quite a large amount of images and there doesn't seem some proper batch processing implemented in version 1 of WP-CLI. At least, that's how I'd understand this issue WP-CLI issue Clear WP object cache periodically on media regenerate/import which I found in the WP-CLI v2.0.0 Release Notes. Is upgrading WP-CLI an option for you? If not you could also install it as a project-local dependency using Composer. Maybe you need to init a bare bone Composer project with `composer init` in your WordPress folder first. $ cd /path/to/wordpress $ composer require wp-cli/wp-cli-bundle:^2 $ vendor/bin/wp media regenerate
stackexchange-wordpress
{ "answer_score": 1, "question_score": 7, "tags": "wp cli" }
How to insert the first letter in uppercase short question, I have a variable concatenated with a get_the_title and get_the_category, and I need the get_the_category to show the first letter in capital letters. <?php echo get_the_title().' - '.get_post_type( get_the_ID() ) ; ?> Anyone have an idea? Thank-
I think this should do the job <?php echo ucfirst(get_the_title()) .' - '.get_post_type( get_the_ID() ) ;?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "php, functions, categories" }
Remove Admin Notice on page refresh I have a simple question about admin notices. I want to display a message like 'Record updated successfully', and when user refresh again same page, then this notice should not be there as no record is updated again. Just like settings Api, there is notice as 'Settings saved.' and when we refresh the page the notice is not there. I see in URI argument is there as I know here **settings-updated=true** is the key, and it disappear immediately and user can hardly notice it. But I don't know how it disappears after taking effect. I think I am missing very simple and basic trick. Any help highly appreciated
This is done by wp_admin_canonical_url: * It calls wp_removable_query_args to fetch a list of query string parameters to remove, which includes `settings-updated`. * It then writes some script into the page header to use `window.history.replaceState` to remove the query string from your browser's URL bar. <link id="wp-admin-canonical" rel="canonical" href=" <script> if ( window.history.replaceState ) { window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash ); } </script> If you want to add your own arguments to the list that gets removed then you can hook removable_query_args.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp list table, notices" }
Wordpress keeps redirecting me to online site I need to create a copy of a WordPress in a local environment. I have alread done some research and 1. Included the following line in wp-config.php (at it's start, also tried at the end) define('WP_SITEURL','< define('WP_HOME','< Note sure if these URLs should be different. 2. Changed `siteurl` and `home` to < in database in table [prefix]_options 3. I have also checked the .htaccess file and it contain nothing that refers to the online domain. but it keeps redirecting me to the online domain.
Clear all rewrite_rules in the wp_options table in your database then open your local website in an incognito browser or clear your browser cache.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "domain, site url" }
Displaying Woocommerce Product Category in Wordpress I'm trying to create a custom theme. I added theme compatibility with Woocommerce to my theme, and am trying to create a product loop. I want to filter my loop so it only displays post with the category "cap" I tried the following versions: $params = array('posts_per_page' => 5, 'post_type' => 'product', 'category_name' => 'cap'); $wc_query = new WP_Query($params); ?> and also tried displaying it by Category ID. Both show me no products. Am I doing something wrong? Using PHP 7.2 Some images showing cat setup: < < Any help is appreciated!
woocommerce categories are not a "category" they're the `product_cat` taxonomy. change your args like so: $params = array( 'posts_per_page' => 5, 'post_type' => 'product', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'cap' ) ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, loop, woocommerce offtopic" }
How to turn off email you receive when registered? My client wants to turn off the email you receive when register.
The function that generates the new user notification is `wp_new_user_notification()`. It is called by another (similarly named) function `wp_new_user_notifications()` which is triggered by the action hook `register_new_user` in the `register_new_user()` function. If you follow that (or even if you don't), all you need to do is remove the `wp_new_user_notifications()` filter from the `register_new_user` action: add_action( 'init', function() { remove_action( 'register_new_user', 'wp_send_new_user_notifications' ); }); As others have noted, if you remove this, then depending on how you have the site set up with user passwords, etc, you may have to consider how users will be able to initially access the site.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, php, functions, user registration" }
Plugin to display text before a post I am trying to display some text before publising post.When i add post i am getting error as ## Publishing failed my code is function adddata(){ echo "Welcome to my post!.........."; } add_action('new_to_publish', 'adddata'); It is not getting displayed
smraj, try to use a filter. Use this code snippet. Place this in our theme's functions.php file add_filter('the_content', 'adddata'); function adddata($content) { $pre_post_text = 'Welcome to my post!..........'; // only display this on single post pages if(is_single() && !is_home()) { $content = $pre_post_text.$content; } return $content; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, posts, plugin development" }
Upgrade from 5.0.4 to 5.1.1 causes $theme to be null When we upgrade from 5.0.4 to 5.1.1 the site stops loading. The error message is Fatal error: Uncaught Error: Call to a member function images_path() on null /wp-content/themes/mytheme/header.php on line 49 Line 49 is `<?php $theme->images_path(); ?>` above it in the same file is `global $theme;` $theme is created in functions.php as the instance of our custom theme. class MyTheme { private $theme_name = "MyTheme"; private $scripts_version = '0.90'; function __construct() { add_action('init', array($this, 'init_assets')); ...several of these ...more methods } } ...other stuff $theme = new MyTheme(); I don't know how to troubleshoot this issue. Everything worked great prior to the upgrade and no other changes were made to the site. Any help appreciated.
Since Changeset 44524, which has landed in WordPress 5.1, the variable `$theme` is now a global variable set by WordPress which also gets unset after the themes have been bootstrapped: // Load the functions for the active theme, for both parent and child theme if applicable. foreach ( wp_get_active_and_valid_themes() as $theme ) { if ( file_exists( $theme . '/functions.php' ) ) { include $theme . '/functions.php'; } } unset( $theme ); This means that any value set by your theme gets also unset. To fix the fatal error you now have to replace all variables named `$theme` with a prefixed version, for example `$my_theme`. Prefixing variables and functions in global scope is considered best practice to avoid such issues.
stackexchange-wordpress
{ "answer_score": 13, "question_score": 8, "tags": "theme development, upgrade" }
Changing Woocommerce language without changing the language in Dashboard admin Wordpress I want woocommerce to change the language to Vietnamese, but the wordpress admin page is still in English language? How to do that? Thank a million.
Make sure you have the language files and then in functions file add the following code. It will trigger in your frontend. //set Vietnamese locale add_filter( 'locale', function($locale) { if ( !is_admin() ){ $locale = "vi"; } return $locale; });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
How do i remove "Powered by WordPress" from AMP? how do I remove "Powered By Wordpress" from the AMP version of my website? It would be great if you suggest a CSS or Plugin for this. I use the basic AMP plugin.
> To remove “Powered by WordPress,” from the AMP plugin’s footer.php template file. Reference **This new file should reside at:** wp-content/themes/yourtheme/amp/footer.php **Footer.php** <footer class="amp-wp-footer"> <div> <h2><?php echo esc_html( $this->get( 'blog_name' ) ); ?></h2> <a href="#top" class="back-to-top"><?php _e( 'Back to top', 'amp' ); ?></a> </div> </footer> This will ensure that Remove Powered WordPress AMP Plugin will still remain after the plugin is updated next time.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, xampp" }
Remove Featured Image & All Media Uploaded to the Post I found a solution of removing featured image related to the post when delete the post from this article but, I want to remove all the uploaded media also with post removing. Delete all WP image gallery (included generated thumbnails) that are attached to a post. How can I do this?
You can try using the function `get_attached_media()` like this: add_action( 'before_delete_post', 'wps_remove_attachment_with_post', 10 ); function wps_remove_attachment_with_post( $post_id ) { /** @var WP_Post[] $images */ $images = get_attached_media( 'image', $post_id ); foreach ( $images as $image ) { wp_delete_attachment( $image->ID, true ); } } **Note that this will permanently delete all the image files related to this post. If those attachments are used somewhere else as well, those links will be broken.**
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, images, post thumbnails, media, trash" }
Why is my custom API endpoint not working? I tried to include this code in my plug-in php files as well as in `functions.php`. (In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.) It is a very basic method for now, I'm just trying to get a response with some content. In both cases, I get a 404 response. add_action( 'rest_api_init', function () { register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array( 'methods' => 'GET, POST', 'callback' => 'api_method', ) ); }); function api_method($data) { var_dump($data); return 'API method end.'; } And I tried to access URLs (in brower or with AJAX) * < * < * < * < I guess I'm missing something.
Maybe start with just `GET`. Your route looks weird as well. Try just: register_rest_route('my-project/v1', '/action/', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'api_method', ]); * * * And your callback is not returning a valid response. Let your callback look more like this: $data = [ 'foo' => 'bar' ]; $response = new WP_REST_Response($data, 200); // Set headers. $response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]); return $response; * * * Finally you must combine `wp-json`, the namespace `my-project/v1` and your route `action` to the URL you now can check for what you get:
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "rest api, endpoints" }
Are SVG image files safe to upload? Why WP defines them as a security risk? I'd like to upload a map of the USA in a SVG format however I am prevented from doing so because of a 'security risk'. Any ideas why this is? Is it safe to do so? Thanks
SVG files contain code in the XML markup language which is similar to HTML. Your browser or SVG editing software parses the XML markup language to display the output on the screen. However, this opens up your website to possible XML vulnerabilities. It can be used to gain unauthorized access to user data, trigger brute force attacks, or cross-site scripting attacks. Detailed article here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "security, svg" }
How to get the full URL of the current page and change domain of it? For example, the current url is: I want to display this url under the showing article and also change the domain to: Is there any way to do this? Thank you guys a lot!
If it’s a page or post, then you can get its url with `get_permalink()`. And to change the domain, you can do some simple string replacing with `str_replace`. So here’s the code: echo str_replace( 'OLD_DOMAIN', 'NEW DOMAIN', get_permalink() );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks" }
How to change header from full-width to box width I'm using a custom theme on my website. What I'd like to do is have the header to be boxed while having the main content staying as is. I've looked at several other threads, but I couldn't manage to make my way to the solution with the theme. here is my header CSS that makes its full width .full-width-content .wrap, .full-width-content .content-sidebar-wrap { margin: 0 auto; max-width: 100%; width: 100%;}
If you want to reduce the width of your header , you can do few different methods. If you use bootstrap, add class _container_ to your header, which will add left and right padding to the element. Or you can add your own css. With the given url, I found that your header's wrap class can be updated to get you a custom width. so here it is, .site-container header.site-header.fixed .wrap{width: 80%;} you can change the value as you wish
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "css" }
Force fill all fields when creating a new post How do I force all fields to create a new post? If a field (such as a category or title, etc.) is not filled, an error message will be issued Thanks for help
> I've been looking for a suitable solution for this as well. I came across this plugin which will make certain fields mandatory before a post can be published. Hope you may help with this. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Publishing post strips custom html element when user is not admin This phenomenon occurred after updating Wordpress from 4.9.10 to 5.1.1. I'm using the plugins TinyMCE Advanced, Classic Editor and Advanced Custom Fields PRO. The wordpress installation has the roles admin and testrole. I'm logged in as testrole and insert the custom html element `<p><new-page></new-page></p>` in a custom field of type WYSIWYG editor in a post and publish the post by clicking publish. `<p><new-page></new-page></p>` is replaced with `<p></p>`. When logged in as admin, the replacement does not happen. How can I prevent wordpress from replacing `<p><new-page></new-page></p>` with `<p></p>` when logged in as testrole?
Append the following code to wp-config.php define('CUSTOM_TAGS', true ); $allowedposttags = array(); $allowedtags = array(); $allowedentitynames = array(); Copy the values for $allowedposttags, $allowedtags and $allowedentitynames from web/wp-includes/kses.php and assign them to the variables $allowedposttags, $allowedtags and $allowedentitynames in wp-config.php . Add 'new-page' => array() as an element to the array which is assigned to $allowedposttags.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles" }
Adding pre-publish checks with Gutenberg Before publishing an unpublished article pre-publish checks are shown. How can I extend this programmatically, and disable the publish button if the checks are not passed? ![prepublish check](
This got me started. Set up the block with `create-guten-block` Gitub Update `block.js` to something like: import './style.scss'; import './editor.scss'; var PluginPrePublishPanel = wp.editPost.PluginPrePublishPanel; var registerPlugin = wp.plugins.registerPlugin; function Component() { wp.data.dispatch('core/editor').lockPostSaving() //do stuff //wp.data.dispatch('core/editor').unlockPostSaving() return wp.element.createElement( PluginPrePublishPanel, { className: 'my-plugin-publish-panel', title: 'Panel title', initialOpen: true, }, 'Panel content' ); } registerPlugin( 'my-plugin', { render: Component, });
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "plugin development, block editor" }
Call to undefined function get_userdata() in plugin After refactoring/restructuring files in my plug-in, I now get the error > Uncaught Error: Call to undefined function get_userdata() after code $current_user_id = get_current_user_id(); $current_user_meta = get_userdata($current_user_id); in `mydomain.local/wp-content/plugins/my-project/my-project.php` I also tried as it was before, in another .php file that was `required` by `my-project.php` These lines are and were appearing quite early in my plug-in code ... am I missing some dependency before running them?
Solution found: the reason was that the code including those lines were included in plug-in's main file and were wrapped in the shortcode launch anymore. I had to put things in another file,like for example function load_shortcode( $atts ){ require_once(getPluginPath().('my-project.start.php')); } add_shortcode( 'my-project', 'load_shortcode' ); and lines had to be in `my-project.start.php` * * * `getPluginPath()` is NOT a native WordPress function, don't look for it, the only thing to know here is that it generates a path string.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "php, functions, users" }
Add custom schema to post I'm building a car listing site which needs custom schema added to each vehicle. The schema doesn't comply with the standards sets, this is the example I've been sent: < I would like to find a way to generate the fields and output to JSON. I've used a custom field and added the data above which works well but isn't user friendly.
> I've used a custom field and added the data above which works well but isn't user friendly. Use **Custom Post Types** and **add Meta Boxes** to make it user friendly. Here's a basic example of adding a custom post type: function create_post_type() { register_post_type( 'car', array( 'labels' => array( 'name' => __( 'Cars' ), 'singular_name' => __( 'Car' ) ), 'public' => true, 'has_archive' => true, ) ); } add_action( 'init', 'create_post_type' ); **Suggestion** You can also include **Custom Taxonomies** for fields like `category`, `price_type`, `make`, `model`, `advert_type`, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "json" }
What is the propre way to include jQuery UI Datepicker's CSS in plugin? I was looking for a datepicker, I read in another question's answer that jQuery UI's DatePicker is included in WordPress. To make it work I needed to add in script inclusions wp_enqueue_script('jquery-ui-datepicker'); But now it's missing .css, I tried to add this in styles inclusions wp_enqueue_style('jquery-ui-datepicker'); but it didn't work. In the WordPress I'm working on, I found however thousands of references for datepicker. In the end I'm using this for now: wp_enqueue_style( 'jquery-ui-datepicker', plugin_dir_url(__DIR__) . 'jetpack/modules/contact-form/css/jquery-ui-datepicker.css' ); But I feel like there must be a more "WordPress-native" syntax which I'd like to know.
The syntax is fine. WordPress doesn't include CSS for the jQuery UI components, so you need to include it yourself. This is what Jetpack has done, and it's why you're able to load it from there. However this means that your plugin is dependent on Jetpack. Ideally you'd download the CSS (you can get it here) yourself and include it in your own plugin/theme, and enqueue it from there.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "jquery, css, datepicker" }
Why am I sometimes getting a 404 error when I try to update a page with Elementor? When updating a page with Elementor, we're occasionally receiving a 404 error. Most of the time we can update the page just fine, but when we try to add a `<script>` tag or a button with a custom font color it gives us a 404 Server Error. What could be causing the issue?
The exact cause of a 404 error can vary, but if you're receiving it when updating Elementor or making any other kind of call to `admin-ajax.php` and it only happens when performing very specific actions, then there's a good chance that it's security related. I've had this error happen several times across several completely different WordPress sites. It doesn't seem to be specifically related to Elementor, though in my experience it happens more frequently with Elementor. In every case that I've had so far, the cause was that the network request was being blocked by a security rule (false positive). One time it was due to WordFence, so I used their Learning Mode feature to whitelist the action. Another time it was triggered by Namecheap's mod_security rules, so I contacted their support and had them whitelist it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, page template, errors, security, 404 error" }
How to re-enable a filter after disabling with __return_false I can disable a filter as follows: add_filter( 'send_password_change_email', '__return_false' ); This may be a trivial question, but I can't find an answer for it... can I re-enable the filter with the following? add_filter( 'send_password_change_email', '__return_true' ); If not, how can I re-enable a filter?
When you add functions to the same handle without specifying the priority, they are executed in the order of addition. Every time you try to send an email, all the hooked functions will be called in the order in which they were added. To turn on email sending while a function runs, you can: * remove `__return_false` from filter at the beginning of the function and add again at the end, * add `__return_true` to filter (will be executed as second and override previous result) at the beginning of the function and remove it at the end. Example: function my_function() { add_filter( 'send_password_change_email', '__return_true' ); // // sending an email about password change enabled // remove_filter( 'send_password_change_email', '__return_true' ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "filters" }
Get product attribute for Simple product in WooCommerce I need to get product attributes from product in WooCommerce, type product Simple product, some product can be as dropdown, but much options as radio button. How I can do this? How it possible? With variations I have no problem, but for simple I can't get them.
Building on Loic's answer for an attribute of `pa_manufacturer`: if ( get_post_type( $post ) === 'product' && ! is_a($product, 'WC_Product') ) { $product = wc_get_product( get_the_id() ); // Get the WC_Product Object } $product_attributes = $product->get_attributes(); // Get the product attributes // Output $manufacturer_id = $product_attributes['pa_manufacturer']['options']['0']; // returns the ID of the term $manufacturer_name = get_term( $manufacturer_id )->name; // gets the term name of the term from the ID echo '<p class="manufacturer">'.$manufacturer_name.'</p>'; // display the actual term name
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, php, custom taxonomy, woocommerce offtopic" }
Display post count on archive page in reverse order I'm displaying some posts and I want each of them to display a post number. The first post being number 1, the most recent post being 10 (let's say there's 10 posts.) I'm currently using <?php echo $wp_query->current_post + 1?> Which works except the newest post is 1 and the oldest post is 10. How do I reverse this?
You can give a try to this within a loop <?php echo $wp_query->found_posts - $wp_query->current_post ; ?> `$wp_query->found_posts` gives the **total number of posts found matching the current query parameters**. So the if there are 20 posts, result for each post should look like this For 1st post it will display `20`, i.e. 20-0=20 For 2nd post it will display `19`, i.e. 20-1=19, ... ... ... For 12th post it will display `9`, i.e. 20-11=9, and For 20th post it will display `1`, i.e. 20-19=1,
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, archives, count" }
Imported Posts missing summary text on staging site I used WP Settings' native export (from production site) and import (to staging site on subdomain) for several months' posts. The imported posts are not showing a summary/excpert on the homepage feed. I've tried changed the Reading setting to Full Text and back to Summary, but it didn't have any effect. This can be seen at staging.slowgetter.com
Although there's little chance that something went wrong, first of all make sure that you content is actually there. Just edit a post from your dashboard and make sure it looks like it should, Now, it looks like you have different themes on you live and staging sites, so it most probably is an issue with your staging theme. It might have its own set of configuration options (check Appearance > Customize), or it might be a bug. It's probably best to read the theme's documentation or contact the theme's author.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, import, staging" }
Problem in redirect link in wordpress I created a login page in wordpress and redirected the page to another website . Now, after clicking the login icon from the menubar it redirects to another page. Thats fine. But I cant access the wp-admin page to edit the wordpress because whenever I go to wp-admin (www.energymaterials.org/wp-admin) , it again redirects to another page. I cant go to my admin page, of course the login in the menu bar redirects to the page (www.energymaterials.org -> select login in the menu bar->it will redirect to another site) which i redirected but i cant access my own admin page which is the most important page. How to sort out this issue ? Please help me.
Regarding to the comments. As there is no redirection page from WordPress itself, please check if you have some plugins enabled that create this page. deactivate them to test if you can access your wp-admin again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp redirect" }
How to create a specific role to manage users I have created a non-admin user role to manage users. I have given this role the following capabilities: Create User, Delete User, Edit User, List Users, list roles. A member with this role CAN create a new user. However when they list Users from the dashboard, they cannot edit any users. They do not get a edit button. I am using the "members" plugin to mange roles, although I see the same results when I set the capabilities programatically. I really don't want the user manager to be a full admin.
The following capabilities are needed to fully manage users: create_users edit_users promote_users delete_users remove_users list_users Remove role, you've created with Members plugin. Add the following code to `functions.php` of your active theme: add_role( 'users_manager', __( 'Users Manager' ), array( 'read' => true, 'list_users' => true, 'promote_users' => true, 'remove_users' => true, 'edit_users' => true, 'create_users' => true, 'delete_users' => true, ) ); Once 'users_manager' role is created, you can remove above code from `functions.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user roles, management" }
How to properly add and access a JavaScript file in Wordpress? I intend to use a JavaScript library on my WP website and have uploaded the JS file via FTP to the following directory belonging to the currently activated theme Salient: `/public_html/wp-content/themes/salient/js` Then, in order to load the JavaScript, I have added the following line in the "Header and Footer" settings (to be injected before the body closing tag): <script type="text/javascript" src=" When I am then loading a page and when inspecting it using the Chrome console, there's a 404 error for that JS file, although the file and the directory exist. As an alternative approach I also tried to add the script reference directly in HTML and even the page template, but with the same result. Why do I keep getting the 404 error? Thanks for your help.
You should enqueue your script using wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer); Where, `$handle` is the name for the script. `$src` defines where the script is located. `$deps` is an array that can handle any script that your new script depends on, such as `jQuery`. `$ver` lets you list a version number. `$in_footer` is a `boolean` parameter (`true`/`false`) that allows you to place your scripts in the footer of your HTML document rather then in the header, so that it does not delay the loading of the DOM tree. **Documentation** **Add this code to`functions.php` file of your theme.** function add_my_script() { wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/javascriptfile.js', array ( 'jquery' ), false, true ); } add_action( 'wp_enqueue_scripts', 'add_my_script' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, javascript, page template" }
admin-ajax.php slow website, how to fix I have a function in my wordpress that load a dynamic css. I checked that this admin-ajax.php call made the website slow (+5s) about. add_action( 'wp_enqueue_scripts', 'theme_custom_style_script', 12 ); function theme_custom_style_script() { wp_enqueue_style( 'dynamic-css', admin_url('admin-ajax.php').'?action=dynamic_css', ''); } add_action('wp_ajax_dynamic_css', 'dynamic_css'); function dynamic_css() { require( get_template_directory().'/css/custom.css.php' ); exit; } Can i save the output of this file in a folder each time i make an edit on admin , and load such a css link instead of load everytime via admin-ajax ? or call in different way to avoid this issue ? Thanks
If you want to save the generated css to a file, take a look at `file_get_contents()` and `file_put_contents()` native PHP functions. < You can also find some Q&A's on the topic both in SO and WPSE, e.g. < You can then enqueue the created css file inside wp_enqueue_scripts like any other css file. You might want to wrap the enqueue inside a `file_exists` conditional check to avoid potential errors. Another option could be that you enqueue the dynamic css in wp_enqueue_scripts, but wrapped in a suitable if statement.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "ajax" }
docker on windows 10 with VVV I've been using VVV on a Win 10 Pro machine for local dev. And it works great. But I want to try things like wpgraphql via docker. I've read about Docker Desktop for Windows vs. Docker Toolbox. We would prefer not to use the legacy solution ( Docker Tookbox ). Is it possible to use Docker Desktop for Windows on the same machine that is using VirtualBox ( VVV ) ? I'm not opposed to using Docker for all our local dev sites, but it would be nice to have the option to use either. Or at least be able to test Docker without hosing our VVV setup.
It is not possible to use Docker Desktop for Windows with Vagrants due to Docker's use of Hyper-V. Docker Toolbox can be used but it is a legacy version and getting localhost to work is a pain. Instead, we set up Mint on an old laptop and installed Docker CE and it works great.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "docker, vagrant" }
What version of React does Gutenberg use? The jump made in React 16 seem substantial enough from 15 in terms of how things are done, especially with the new hooks that Fiber provided, so what version does it use and is it considered bad practice / a no-no to use React 16 when a version of React 15 is provided to me?
WordPress 5.1.1 uses React 16.6.3. You can see this in the package.json file in the development version of WordPress on Trac: < This has already been updated in trunk to 16.8.4, so the next major version of WordPress will use at least that version.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "block editor" }
How to disable Woocommerce password recovery and use the default WordPress password reset page? On my website: < when I request for password reset, it is redirecting to Woocommerce's reset page: < but I want default WordPress password reset page: < How to do this? I tried disabling "Reset Password" in Woocommerce settings "Emails" page but it didn't work.
I found the solution in WP forum. Here it is: To remove the WooCommerce redirect for the “Lost Password” link, you’ll want to remove the “Lost Password” endpoint setting as found under `**WooCommerce > Settings > Advanced > Account endpoints**`. By simply leaving that blank, the user will be forced to use the default WordPress login password reset form
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "woocommerce offtopic, password" }
How to get a list of WordPress default database tables? Is there any solution to get a list of default database tables in WordPress? I have used `$wpdb->tables()` but even with `blog` argument, it returns a list that includes other tables too. (I have some plugins and they have created some more tables in database)
There is no programmatic way to get a list of default tables. WordPress does not store a list of them anywhere. The closest thing there is is `wp_get_db_schema()`. This function returns the raw SQL used to create the default tables, but as you can see from the source, it doesn't derive it from another source, it is where the default tables are originally defined. Maybe you could parse the SQL to figure it out, but I'm not sure why you'd need to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, wpdb" }
Woocommerce: sorting variable product How do I show variations sorted by quantity in stock? I can override or extend the WC_Product_Variable class, but this solution doesn't seem optimal. What other options are there?
You can use the `woocommerce_get_children` filter: function wpse_filter_variations( $variations, $product, $false ) { // Do you sorting here return $variations; } add_filter( 'woocommerce_get_children', 'wpse_filter_variations', 10, 3 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Overiding wp_sanitize_redirect for | character I am not really conversant with php and I have an issue with `wp_sanitize_redirect`. I have seen this excellent question and answer: wp_sanitize_redirect strips out @ signs (even from parameters) -- why? How do I override this method Wordpress so that I can pass the `|` as part of a URL and it not get stripped out? I am using the latest 5.x edition of Wordpress.
There was another solution. I looked here: < And it stated the encoded value for a `|` character was `%7C` so I was able to use that in my redirection URLs.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp redirect" }
Access post title from custom meta box on title change I have a custom meta box as part of my post editor. When the user changes the post title, I want to reflect this change in the content inside the meta box. I have seen plugins like Yoast do this but im not sure how. I have tried using a jQuery event to do this but even if i wait for document.ready, it doesnt bind itself to the element. jQuery(".editor-post-title__input").keyup(function(){ console.log(jQuery(".editor-post-title__input").val()); });
The event listener you have added will only attach to the available `.editor-post-title__input` elements, and won't attach to any dynamically added elements. You are better to move the listener to the body as follows: jQuery('body').on('keyup', '.editor-post-title__input', function(event){ console.log(jQuery(this).val()); }); Given the admin area is moving to use more React components, it's a good habit to get into.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, javascript, metabox, editor" }
How to get INSERT errors from $wpdb? I have these $wpdb->suppress_errors(false); $wpdb->show_errors (true); $wpdbp = $wpdb->prepare($preparedQuery->query, $preparedQuery->values); $result = $wpdb->get_var($wpdbp); I further thought of something like this (may be temporary) if($result === null) { $error = $wpdb->print_error(); var_dump($error); } I read in `get_var()` documentation: > Returns: Database query result (as string), or null on failure My problem here is that `$result` is always null when inserting, even if insert succeeds. How to actually know it there were errors or not? I expect there may be some other types of `get_` methods? Maybe I sould add something like "SELECT 1;" but even if that works I don't like it much.
To insert data you should use `query()` (documentation), `get_var()` method is for selecting data. If error is encountered, `query()` returns FALSE. > **query()** > > This function returns an integer value indicating the number of rows affected/selected for SELECT, INSERT, DELETE, UPDATE, etc. > > For CREATE, ALTER, TRUNCATE and DROP SQL statements, (which affect whole tables instead of specific rows) this function returns TRUE on success. If a MySQL error is encountered, the function will return FALSE. $result = $wpdb->query( 'insert query' ); if ( $result === FALSE ) { // display error }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "mysql, wpdb, sql" }
Re-zipping or extracting theme from wordpress site files I have all of my source file from my old WP site that I have from backups and a CPanel dump where I was using the Avada theme. I have all the theme files and whatnot, but is there a way I can extract or re-zip the theme from these files so that I can properly upload it on the new version of my site?
The easiest way to do this is to upload them using FTP. You can use a free program like Filezilla to upload your files to your server. You will need to know the host name (usually just your domain), user and password. If you don't know this info your hosting company will be able to assist you. Once connected, find the folder where WP is installed. This is typically inside of `/public_html/`. Your theme files are located in `/wp-content/themes/avada/`. You can upload your backup there. I would make sure you have current backups before doing anything.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes" }
Get all user meta_keys and then group users by matching values One of the plugins I am using generates user meta from our AD. One of the keys is the user's Manager. As many users will have the same manager, I want to be able to group all users. I was trying to find any way to do this, or adapt this post: getting all values for a custom field key (cross-post) but can't wrap my head around SQL database writing. Practically, I want to be able to loop each meta manager with all the users that have that `meta_value` with `get_users`
Eventually came to a solution in case anyone needs it: function mb_get_user_meta_values( $mb_user_meta_key ) { if( empty($mb_user_meta_key) ) return; $mb_get_users = get_users( array( 'meta_key' => $mb_user_meta_key ) ); $mb_user_meta_values = array(); foreach( $mb_get_users as $mb_user ) { $mb_user_meta_values[] = get_user_meta( $mb_user->ID, $mb_user_meta_key, true ); } $mb_user_meta_values = array_unique( $mb_user_meta_values ); return $mb_user_meta_values; } Then I can loop through the `get_users` with the `meta_value`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom field, user meta, users" }
WooCommerce registration password field not displaying For WooCommerce registration form we only have one email field and I want to add password fields for this. I have tried to find online help but there are few support pages only for repeat password field. On the other hand I need the first default password field and the repeat password field as well. How I can create these. Your help will be appreciated.
To enable default Password field I just had to check checkbox (When creating an account, automatically generate an account password) under WooComemrce > Settings > Accounts and Privacy. After this default password field started to display on registration page. To add repeat password field I used this hook add_action( 'woocommerce_register_form', 'wc_register_form_password_repeat' ); function wc_register_form_password_repeat() { ?> <p class="form-row form-row-wide"> <label for="reg_password2"><?php _e( 'Password Repeat', 'woocommerce' ); ?> <span class="required">*</span></label> <input type="password" class="input-text" name="password2" id="reg_password2" value="<?php if ( ! empty( $_POST['password2'] ) ) echo esc_attr( $_POST['password2'] ); ?>" /> </p> <?php } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, woocommerce offtopic, forms" }
To display the category of a specific custom post type I apologize for my English, but I am French. In my custom search page I display the results of my custom post type and everything is good. Only, I would like to display above the custom post type the category that is his. To display the post categories I do: $category = get_the_category (); echo "<p> Category:". $category[0]->cat_name. "</ p>"; But how to do for custom post type? Thank you for your help.
For a custom post type, use `get_the_terms()` instead: <?php $post_terms = get_the_terms( get_the_ID(), 'your-taxonomy' ); ?> <p> Category: <?php echo $post_terms[0]->name; ?></p> Much like the results from `get_the_category`, the returned value of `get_the_terms()` is an array of term objects for the taxonomy that you specify when calling the function. In the example code, that is "your-taxonomy". This sample code will only display the first term if multiple terms are assigned to a post. That is the 'zero position' in the array. Any subsequent terms would be returned in `$post_terms[1]`, `$post_terms[2]`, etc <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories" }
Set "editor" role to existing user Using the User ID of an existing user, how do I change the role to Editor? Here's what I tried: $wpdb->query("UPDATE wp_usermeta SET meta_value = 'a:1:{s:6:\"editor\";b:1;}' WHERE user_id = '$user_id' AND meta_key = 'wp_capabilities'"); Not sure what I am doing wrong?
Usermeta key that stores the user's role has a prefix in the name, the one set in the `wp-config.php` file. So `meta_key` will have the form `{prefix}_capabilities` and your query should look like global $wpdb; $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->usermeta} SET meta_value = 'a:1:{s:6:\"editor\";b:1;}' WHERE user_id = %d AND meta_key = '{$wpdb->prefix}capabilities'", $user_id ) ); You do not need to write SQL query. You can achieve the same by fetching the `WP_User` object with `get_userdata` function and set new role with the method set_role (or `remove_role` and `add_role` to change only one of the roles). $my_user_id = 12345; // user ID for changing role $my_user = get_userdata($my_user_id); if ( $my_user instanceof WP_User ) $my_user->set_role('editor');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, users, user roles" }
What's the difference between the capability remove_users and delete_users? In the list of capabilities, I found there's both `remove_users` and `delete_users`. It's not clear to me what `remove_users` is supposed to do, the Codex documentation just says it was introduced in version 3.0 (<
The difference is really no difference in regular (single install) WordPress. It's in a multisite install (network) where there is a difference. In multisite, only a Super Admin (who can manage everything on the network) has `delete_users` capability, while an "admin" (who would own/manage a single site) can `remove_users` from their site, but cannot delete them from the network. Hope that helps clarify.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 8, "tags": "users, capabilities, documentation" }
Reason to add a name of the theme like ('menu-1' => __( 'Primary', 'twentynineteen' ),) in PHP? Sorry for this novice question. I'd like to know why WordPress themes add their theme names many occasions in PHP files (e.g. where 'twentynineteen' is repeated below, this is from functions.php in twentynineteen theme). Looks like themes can function fine without those names included, though. register_nav_menus( array( 'menu-1' => __( 'Primary', 'twentynineteen' ), 'footer' => __( 'Footer Menu', 'twentynineteen' ), 'social' => __( 'Social Links Menu', 'twentynineteen' ), ) ); Is there any particular reason why theme names are included? Thank you in advance for your advice!
The name you see is the text domain of the theme. `__('some text', 'text-domain')` is a translation function, which makes it possible to translate the `some text` into different languages. There are also other translation functions that can be used in different situations. You can learn more about translations on the codex, I18n P.s. if the text domain is left out, the function uses default WP text domain and tries to find translations from that. For example simple strings, like yes and no, usually gets translated from the default translations.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, theme development, themes" }
Block any other domains from using my server Seems someone has set their domain to use my server. It's not a mirror, the database and everything works and updates with mine. He's basically stealing my content, and he's showing up on google instead of me. Is there a way to make it so my server will only respond to requests from my domain? I'm using Wordpress with Apache2. Block IP with .htaccess not works
Hope this will be helpful for others. This is how I stop stealer with javascript var x = location.hostname; if ( x != 'www.example.com'){ window.location.replace(" } Then use this javascriptobfuscator to encrypt the script and put on top of header file. Because of encryption domain name not replaceable (In my case stealer use nginx to change domain name) If anyone need server side solution if ($_SERVER['SERVER_NAME'] != "www.example.com"){ if ($_SERVER['SERVER_NAME'] != "example.com"){ echo "<script>window.location.replace(\" die(); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "security" }
problem with sql query I have a problem with quotes with query. My code: $this->table_name= 'table_name'; $how_much = $this->wpdb->get_var($this->wpdb->prepare("SELECT COUNT(*) FROM {$this->table_name}")); I have nothing notice or error and site break down. **EDIT** Probably `$wpdb->prepare` need arguments to work.
Your code should look something like this: $this->table_name= 'table_name'; $how_much = $this->wpdb->get_var("SELECT COUNT(*) FROM $this->table_name"); We don't need to use the prepare method, since this is not meant for table names, more here And also... as you what are trying to do is going not in a good direction... I don't what to criticize you or anything... But I really suggest you to ask someone who knows better what WordPress can do, about what you need to do, and maybe he will suggest a better approach. P.S: When you develop something, is good to enable the error/warnings/notices, and have a debugger, to know what's going on.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, query, sql" }
find out reason of "Updating failed" in Post-editor In some cases, if there is issue in code or whatever, and try to update the post in Gutenberg post-editor, you will get "Updating failed" error message: ![enter image description here]( Is there any way to debug/find out the reason (i.e. in console) what error happened there or what was the response from the erroneous page?
You could poke around in the Network tab. Filter the requests by XHR. You can view the headers and the Response from there. ![enter image description here]( I think I read somewhere that error reporting is something Gutenberg dev is planning on improving in the future.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, errors, block editor, post editor" }
Change image using only CSS I'm using the twenty fifteen theme. I have a logo set using the WP Customizer. I want to have the image change on mobile or tablet view. The breakpoint is anything smaller than 59.6875em. I'm using this code: @media only screen and (max-width: 59.6875em) { .custom-logo { content: url(" width: 300px; } } It works in Chrome but not Firefox. I've tried adding :before and :after and adding an `a` tag, as suggested on other answers, but none of that works. Can anyone suggest what's wrong, and how I can get this to work on Firefox? Here is the html: <div class="site-branding"> <a href=" class="custom-logo-link" rel="home" itemprop="url"><img src=" class="custom-logo" alt="Seed" itemprop="logo" srcset=" 248w, 150w" sizes="(max-width: 248px) 100vw, 248px" width="248" height="248"></a> </div>
Instead of trying to change the URL of the img tag, use your media query to hide the image and change the `:before` of your `<a>`. Like this... @media screen and (max-width: 59.6875em) { .site-branding img { display:none; } .site-branding a::before { content: url(" } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, theme customizer, theme twenty fifteen" }
correct validate inputs How correct validate data from user to save in database from inputs? I use this for textfields: $name = trim(sanitize_text_field($_POST['name'])); But if i add special signs like "&*({} Something like this ^&({}<>", then they add without a problem. I need add only "Something like this" without special signs.
Try `$name = trim( sanitize_user( $_POST['name'], true ) );` Be sure that the function does what you want! Read here
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "plugins, sql" }
How can I add arbitrary `data-` attributes to a block's `edit()` container? For example: **Before:** `<div id="block-fc502ca9-0d7b-440c-959c-3da152db0192" class="wp-block editor-block-list__block" data-type="wordcamp/schedule">` **After:** `<div id="block-fc502ca9-0d7b-440c-959c-3da152db0192" class="wp-block editor-block-list__block" data-type="wordcamp/schedule" data-foo="bar">`
You can define a `getEditWrapperProps` function when you register the block, and return an object that sets the props for the wrapper. The function will be passed the props for the block, in case those are needed. registerBlockType( 'wpse/example-get-edit-wrapper-props', { title : 'getEditWrapperProps() Example', // ... getEditWrapperProps( props ) { return { 'data-foo': 'bar', 'data-quix': props.quix || false, }; }, } ); That also lets you change any of other other props that get passed to the container, like `id`, `className`, `onClick`, `tabIndex`, etc. Obviously, you probably shouldn't mess with those unless you really know what you're doing, and understand the consequences. Declaration in Gutenberg source: 1, 2. Examples in Core blocks: 1, 2, 3
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "block editor" }
Issues when changing == to === What am I missing... when using === in the code, the front end doesn't show an element at all until I disable and then re-enable an option in the WP Customizer. For example, I have a logo that can be disabled. After installing the theme and viewing the site through the Customizer, the logo shows fine. But when viewing it on the front end, the logo isn't shown at all until I disable the logo and then re-enable again in the Customizer. Here's the code: <?php if( get_theme_mod('hide_logo') === '') { ?> LOGO CODE <?php } ?> == works fine, though I'm making a little theme for sale, and the marketplace requires strict equality checks. Thanks.
The `get_theme_mod()` function could return an explicit `false`. The `===` operator looks for exact matches, so in the case of `hide_logo` not being set the function would return `false` and false is not an exact match to an empty string `''`. The `==` operator is a bit more forgiving in that sense which is why you don't have an issue there. You could supply a default value as the second parameter which will be returned if a value is not set or does not exist: if( '' === get_theme_mod( 'hide_logo', '' ) ) {}
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php" }
Best practices/popular methods for distributing a program with a plugin? Are there any best practice guidelines regarding how a plugin should distribute a third-party program with it's own installation? If there are no guidelines, then what are the most popular methods? For example, our plugin requires the installation of a third-party (GPL compatible) program. To ease installation, the third-party program would be included with our plugin and it will offer to run a version of the program that is compatible with their hosting environment that is included in our plugins assets directory (or other directory?). Updates to the third-party program would be handled by updating it along with our own plugins updates ([our version].[third-party-version]).
their rules specifically say > Externally loading code from documented services is permitted. however all the related examples are about javascript or wordpress plugins. > Management services that interact with and push software down to a site are permitted, provided the service handles the interaction on it’s own domain and not within the WordPress dashboard. which doesn't apply since I'm not providing a remote service but a local service. (unless an http download counts as a "management service") I emailed `[email protected]` and got an official response. > You cannot include the binary, nor can you one-click to install.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, third party applications" }
Error establishing a database connection; After importing DB & Theme I'm doing some work on a client's wordpress so to not touch the live I imported what I thought I needed from their FTP into my xampp to reproduce their environment. Their website is hosted on bluehost, for reference. I Exported/imported their phpmyadmin database, as well as copying over the parent theme and the child theme from FTP. I copied over the wp-config.php for database credentials. It seems like i'd have covered all the bases but it's giving me that error still. What else could I be missing to get this working? DB_HOST is also already set to localhost Googling this error didn't yield much for my scenario Are there more things I should import over from their FTP to emulate 1:1 their environment? Thanks
The database password is not stored in the database itself, so importing the database via phpmyadmin will not also import the password. You need to manually edit your local copy of `wp-config.php`, and enter your local username and password for MySQL ( or any other database you are using ). Usually the default username for local development installations is `root`, and the password is blank, so you can try these. Otherwise, you can check xampp's website to see what the default password, or if you have already set your own password during installation, you can use that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "database, import" }
Add table controls with wp_editor minimal editor configuration ('teeny') I want to add the table controls for wp_editor(tinymce) initiated with teeny=>true. Here is what I have done so far (without success): <?php $tinymce_options = array('plugins' => "table", 'theme_advanced_buttons2' => "tablecontrols"); $editor_config= array('teeny'=>true, 'textarea_rows'=>5, 'editor_class'=>'csec_text', 'textarea_name'=>'csec_text', 'wpautop'=>false, 'tinymce'=>$tinymce_options); wp_editor($content, $id, $editor_config); ?> Can anyone suggest anything reagrding this? Thanks in advance. I'm using: > Wordpress 5.1.1 + TinyMCE advanced 5.1.0 Current output (with requirement): ![enter image description here](
Finally got it running with few pieces of extra buttons too :): <?php $tinymce_options = array('plugins' => "table,lists,link,textcolor,hr", 'toolbar1'=>"fontsizeselect,forecolor,backcolor,bold,italic,underline,strikethrough,alignleft,aligncenter,alignright,alignjustify",'toolbar2'=>"blockquote,hr,table,bullist,numlist,undo,redo,link,unlink"); $editor_config= array('teeny'=>true, 'textarea_rows'=>5, 'editor_class'=>'csec_text', 'textarea_name'=>'csec_text', 'wpautop'=>false, 'tinymce'=>$tinymce_options); wp_editor($content, $id, $editor_config); ?> Check: wp_editor in add_meta_boxes does not show gallery for better option working in accordance with Wordpress.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "tinymce, editor, wp editor, table" }
My plugin wants to update another plugin I am having issues when I view my installed plugin page, it's telling me there is a new version available. If I click the view version or view details links, it shows a completely different plugin that someone else put on wordpress.org. I've tried changing the plugin name and uri, and everything should be unique so not sure why this is happening. Has anyone had this happen or know how to fix it? Thanks in advance
WordPress retrieves the plug-in name from the comment block header in the main plug-in file (using the function `get_plugin_data` defined in `/wp-admin/includes/plugin.php`). The thing is, it doesn't look for updates every time you visit the page - it schedules a cron job that fires every few hours to ease load on the servers running the repository. So after it finds an update for a plug-in, it will cache that find. My recommendation: 1. Deactivate and delete your plug-in from the site. 2. Re-name the plug-in in the code / rename the plugin folder. 3. Re-add your re-named plug-in to your site This should circumvent any caching done by the update system. Copied Resource Here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, customization" }
Set a condition based on WooCommerce checkout city field while placing order How to make condition on WooCommerce checkout field like when user select city "Indore" then on place order email goes to `[email protected]` and when he select "Bhopal" city then email goes to `[email protected]`.
**Updated** The following code will add an additional recipient based on customer billing/shipping city, to new order admin notification: add_filter( 'woocommerce_email_recipient_new_order', 'different_email_recipients', 10, 2 ); function different_email_recipients( $recipient, $order ) { if ( ! is_a( $order, 'WC_Order' ) ) return $recipient; $city = $order->get_shipping_city(); $city = empty( $city ) ? $order->get_billing_city() : $city; // Conditionaly send additional email based on customer city if ( 'Indore' == $city ) { $recipient .= ',[email protected]'; } elseif ( 'bhopal' == $city ) { $recipient .= ',[email protected]'; } return $recipient; } Code goes in function.php file of your active child theme (or active theme). Tested and works.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, woocommerce offtopic, email" }
why is my paypal button not clicable i'm getting crazy with a problem that is probably a stupid thing. Yesterday, i make some little design change on a site, to get the paypal button displayed on a second column of an area. But since it is displayed this way, when i click on "acheter" ( buy now ) nothings happen. I have tryied to generate a brand new button thru paypal, thinking i have probably deleted essential element, but same problem. Button can be seen here : (bottom of the page) < if i take of all my html custom and leave just the paypal form, it works well again :o Here is a capture of the form to help you identify it on the website ![capture](
Your html is broken. Check your quotes at <div class="paiement-honoraires-right>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, paypal" }
ACF - Query relationship without ID i have different CPT ( hotel, market, city, etc… ) My relationship field is used to link CPT to cities (CITY). Now in a page ( hotel page ) i want to link “other hotels in same city”. how can i make my query ? I know how to do a query by ID with the ID of actual page, but what i need is : $city = get_field(‘contact_city’); $query = display all hotels with contact_city as $city But i didn’t find any solution.
If only 1 value in relation field : $city_id = $bnb_ville[0]->ID; if it could be more than 1 value : $city_id = []; foreach ($var as $post) { $city_id[] = $post->ID; } $bnb_ville is the variable for get_field() !
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom post types, custom field, advanced custom fields" }
my images are not showing when i upload them, they apear as placeholders the image has a the correct format. the image url is correct but some how the image is not showing this error happened after website was migrated Please help ![preview of error](
I suggest the following things: 1. Please install the Regenerate Thumbnails plugin and regenerate your thumbnails and check it again. 2. Also check the WordPress Media files type for your WordPress and any other image related (Image Type) plugins installed. 3. WordPress used GD image Library in your Server. Contact your hosting module and check that module is installed and enabled on your server.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "migration" }
Show products as posts on archive page Usually products on shop pages show up with a single featured image title price and add to cart button like this < , and do not follow the themes original styles and settings What i want to do is to show these as how a post in shown in any given theme like this < i have tried numerous codes to override templates, changed themes with and without woocommerce support and customizing archive-products.php with loops from posts.php of the theme which works to an extent but somehow functionality breaks the only thing that worked was switching post type of products to post but i loose a lot of data that way. i have tried making post manually but it was very time consuming as i am importing a lot of products through plugins which automatically import as products. themes i am working with bimber and chipmunk i am an absolute beginner and learning as i go. Thank you,
i was able to overcome this problem although not every efficiently, used elementor skin extension to create a template for loop, then used that loop in elementor template builder for archive. While this does solve the problem i believe it is not efficient as it did slow down my website and cpu usage may be increased. if anyone has a better solution without using any plugins please let me know.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, archive template" }
Change background image page header overlay for each category this is my site: < and I'm trying to change the background image page header overlay for each category. I have been looking at many forums but I didn't get with the correct answer. For example: on this page < it should show a different background image page header overlay than this one: < If anybody could help me with this I will be very grateful.
This is probably the easiest method. If you inspect the `<body>` tag by pressing `F12` in your browser you will see it has a different class for each category. You can use this to target your header element for each specific category. For example, this will change the image for category 6. body.category-6 .page-header { background-image: url( ) !important; } Note: You can upload images via the file uploader and then just replace the correct path for the background-image URL. CSS changes can be added to Appearance > Customize > Additional CSS
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, images, custom background" }
Query certain amount of posts from multiple dates I was wondering whether it's possible to use _one_ query to get the last couple of posts from several years. I'm currently using a `foreach` loop to run several queries and then merge the post data. My single query looks like this: $amount = 2; $year = 2018; $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => $amount, 'date_query' => array( array( 'year' => $year ) ) ); $query = new WP_Query($args); For performance reasons, I'm assuming it's better to use one query that achieves the same – if that's even possible. An example of what I'm trying to achieve is get the last two posts from each of the last three years: * two posts from 2016 * two posts from 2017 * two posts from 2018
You're just about there. Each `date_query` array represents a separate condition to filter by. By default, these are combined using `AND` which limits the scope further. In your case, you want to change the relation to `OR` and then add the different years as their own separate conditions in the array. $args = array( 'date_query' => array( 'relation' => 'OR', array( 'year' => '2018', ), array( 'year' => '2015', ), ), ); The resulting mysql statement looks like this: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_date DESC LIMIT 0, 10 The important bit is `( YEAR( wp_posts.post_date ) = 2018 OR YEAR( wp_posts.post_date ) = 2015 )`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "wp query" }
Wordpress Menu Navigation links not working Navigation Menu links not working, but the bootstrap CSS is working. Can anyone help me in getting the links working? Thank you![enter image description here]( <ul class="navbar-nav mr-auto"> <?php wp_nav_menu(array( 'theme_location' => 'primary', 'before' => '<class="nav-item active">', 'menu_class' =>'navbar-nav mr-auto', 'link_before' =>'<a class="nav-link" href="#">', 'link_after' =>'<span class="sr-only">(current)</span></a>', 'container' => false, 'items_wrap' => '%3$s' )); ?> </ul>
Here are a couple things I noticed. You don't want to include the `<a>` inside of `link_before` or `link_after`, you will get 2 links if you do that. You also don't need the `<ul>`. Instead I think you want something like this... <?php wp_nav_menu(array( 'theme_location' => 'primary', 'before' => '<class="nav-item active">', 'menu_class' =>'navbar-nav mr-auto', 'link_before' =>'<span class="nav-link">', 'link_after' =>'</span>', 'container' => false, 'items_wrap' => '%3$s' )); ?> You should read more about wp_nav_menu.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, themes, navigation" }
Retrieving custom field as shortcode I have added a custom field to my site called "dansk_url", to which a link to the version in Danish (different domain) will be entered. I would like to be able to output this as a shortcode to add anywhere within the post, and it should appear as a link (anchor text will always be "Dansk" and whichever url has been entered in the custom field for that post. Is this possible? I prefer a non-plugin solution.
Put this in `functions.php` of your theme. add_shortcode( 'dansk_url', 'dansk_url' ); function dansk_url() { $output=''; $the_url= get_post_meta( get_the_ID(), 'dansk_url', true ); if ( $the_url) $output .= '<a href="' . esc_url( $the_url) . '">Dansk</a>'; return $output; } and use shortcode `[dansk_url]` in the post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom field, shortcode, post meta" }
Exclude certain template from wp_list_pages I'm trying to do something similar to the question in Exclude pages with certain template from wp_list_pages, but the `$exclude` variable doesn't seem to be returning the `_wp_page_template` value to then filter out the relevant pages with the template `guidance-note-template.php` from the list. Any tips, greatly appreciated. <?php global $post; $exclude = []; foreach(get_pages(['meta_key' => '_wp_page_template', 'meta_value' => 'guidance-note-template.php']) as $page) { $exclude[] = $page->post_id; } $children = get_pages( array( 'child_of' => $post->ID ) ); $hasChild = (count( $children ) > 0 ); $page_id = ($hasChild) ? $post->ID : wp_get_post_parent_id( $post->ID ); wp_list_pages( array( 'title_li' => '', 'child_of' => $page_id, 'exclude' => implode(",", $exclude), )); ?>
For children pages to show, the `'hierarchical' => 0` option must also be set in your get_pages() function. I copied your code and initially had the same results (it returned no pages). Adding in the hierarchical setting set to 0 made it return the 2 pages I had set to that template, which could then be excluded. It then output all the other children except for those 2, as I think you wanted. Credit for solution: Older Stack Overflow answer
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, wp list pages" }
Retrieving post excerpt as a shortcode How do I register a shortcode to add the **manual** post excerpt anywhere within the same post? Does this shortcode already exist in WP? Thanks!
Just add this to your child theme's `functions.php` file: add_shortcode( 'output_post_excerpt', 'get_the_excerpt' ); Then use `[output_post_excerpt]`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "shortcode, excerpt" }
404 error on published page with specific permalink I am experiencing a strange error with my Wordpress install. I've got a dozen of pages, %postname% permalink structure, everything works fine. For one of the published pages, I reverted it to draft mode, edited for a couple of days, then published it again. Now, when I try to access its permalink, I get a 404 error. If I change the slug by 1 symbol, it works. But the initial slug does not. Any idea how to fix it? Thanks! Can share the website if necessary. Edit: I did all the "fixes" that I found by Googling: refresh .htaccess, disable all plug-ins to see if it's a plugin issue, disable caching, update permalink structure... Nothing worked.
OK so I've spent a couple of more hours working on this and was examining my database through phpmyadmin. In the table wp_terms I noticed that I had terms identical to my page's slug. Turns out I had a tag named like this. I deleted the tag, and voila - no more 404 error. Hope this may help somebody.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, 404 error, slug, single" }
How to code custom special page I'm looking for how to code custom "special" page as use many plugins. An idea is that I have in theme links to the custom special page. Then admin can chose which of his pages is the one "special" page. The functionality I'm looking for is similar as functionality of for example "Shop page" in woocommerce. ![enter image description here]( ![enter image description here]( I appreciate any help or a documentation link.
Because you asked "How to Code", here is my guide to get you started. 1. Create a menu page in the administration area using add_menu_page 2. Create the form using html **select** form-element 3. Populate the form-element with all **pages**. To get all pages you can use get_posts() 4. Save the form using admin_post) action 5. Save the selected-item of the form using update_option() 6. To get the saved option you can use get_option() 7. To add that **— Special Text** in the page list, you need to filter the title. If the page's ID is equal to the saved_setting, then append that text. I'm not sure which hook to use, I think it is manage_pages_columns I hope it helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, pages, code" }
What will happen to the additional CSS when the theme is updated? I have a premium theme installed and I need to add some custom CSS to add some new styles. So what will happen if I add the CSS to the additional css section in the customize? Will I lose them when the theme is updated? Should I install a plugin or create a simple one for this? I tried to search about that, But didn't find an answer.
Nothing. The Additional CSS section of the customiser will be unaffected by updating the theme. The reason you may have seen warnings regarding updating themes and losing customisations is because when themes are updated, all of its files are replaced with fresh copies. So the reason you lose changes is because if you modified the themes files then they have been overwritten with copies that don’t have your changes. None of this is relevant to the Customiser, because it doesn’t modify theme files.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "customization, css, theme customizer" }
WP_Query author parameter not working As per doumentation Author Parameters #Author Parameters 1. author (int) – use author id. 2. author_name (string) – use ‘user_nicename‘ – NOT name. 3. author__in (array) – use author id (available since version 3.7). 4. author__not_in (array) – use author id (available since version 3.7). Can they all work together? If I keep author__not_in, first 3 does not work? author__not_in is an empty array
First, the `author` parameter is parsed and appended to the `author__in` and `author__not_in` query parameters. Then `author__in` or `author__not_in` array is processed. These can be arrays created from `author` parameter or arrays passed as query parameteres `author__in` / `author__not_in` **or created from a mergion** `author` parameter with `author__in` / `author__not_in` parameters. Parameters `author__in` and `author__not_in` are mutually exclusive, so you can use only one of them. If both are given, then `author__not_in` will be used. Finally, the `author_name` parameter is processed and added to the`where` clause. Although theoretically it can be used with any of the other parameters, the effect will be the same as if only `author_name` was used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, author" }
How to remove multiple blocks of Gutenberg at the same time? Currently, I have to remove one block per time. How to remove multiple blocks of Gutenberg at the same time?
You can click and drag mouse out of a block, to select multiple ones - but it's not very comfortable option, IMHO (especially when there are large blocks). Another way is to click one block, then press shift (and hold it) and and click another block - all blocks between them will get selected.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "block editor" }
user activation email doesn't work I have a question about the Gravity forms Plugin ... I'm going to create a registration form And for that, I used the description of the link below. < But the problem is that no email is sent to the registered user, so that they can complete the signup submission link. I do not understand where the problem is?
i found answer If you also encountered this problem, you can use "wp smtp config" plugins <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "user registration, plugin gravity forms" }