INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Serving WordPress in it's own directory on localhost on WAMP I have followed Giving WordPress it's own directory for directions on how to accomplish this on www.mysite.com (once it goes live) but I'm looking for localhost directions to serve my site to localhost directly with WordPress in a SubFolder (I don't think you change .htaccess for localhost). My WordPress installation is at /sitefolder/arc/... How can I browse to localhost and see my site as opposed to the way it is now, having to navigate to localhost/sitefolder/arc? I am guessing its something in the DocumentRoot? I am using WAMP. Thanks!
You have two alternatives: 1. Change the DocumentRoot directive in the WAMP httpd.conf file (use CTRL+F to find it). That way you will change the whole root folder of your server, be aware of that! 2. Create a virtual host that will bind a domain to a particular subfolder in your document root (similar to subdomains logic). Here some article that might help: < I personally prefer the second option, is better than modify the entire document root. With a virtual host you choose if you want to use the root or a subdirectory. Be happy!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "localhost, apache" }
Best way to use a large array in function I need to define an array which has more than 15000 values in the wordpress functions file: $validpin = array(110019,111222,112233); I have written only 3 values to explain but the actual array will have more than 15000 values. How should I go about doing, as writing 15000 values is making the functions file very large?
If it's just a list of numbers, I'd suggest just saving them in a text file, with a number on each line. 110019 111222 112233 Then when you need the file, read its contents with PHP, and use `preg_split()` to turn it into an array: $file_path = plugin_dir_path( 'postcodes.txt', __FILE__ ); // Or wherever you've placed it. $file_contents = file_get_contents( $file_path ); $postcodes = preg_split( "/\r\n|\n|\r/", $file_contents ); if ( in_array( $postcode, $postcodes ) ) { } That `preg_split()` method for splitting text based on newlines is taken from here.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions" }
Update post meta date always store 1970-01-07 I want to update the post meta "job_expires" to the current "job_expires" meta data + 1 week but with this code always store 1970-01-07 as date. $lejar_datum = get_post_meta($job_id , '_job_expires', true); $date = date('Y-m-d',strtotime('+1 week',$lejar_datum)); update_post_meta( $job_id, '_job_expires', $date); How can I store the current "job_expires" date + 1 week?
With debugging enabled, you should have gotten the following message: > Notice: A non well formed numeric value encountered This is because `strtotime()` expects an integer as its second argument. You could use it like so $date = date('Y-m-d', strtotime('+1 week', strtotime($lejar_datum))); or if you want to use the more modern approach with `DateTime` $dt = DateTime::createFromFormat('Y-m-d', $lejar_datum)->modify('+1 week'); update_post_meta($job_id, '_job_expires', $dt->format('Y-m-d'));
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta, date" }
Wordpress REST API and User meta data I created two custom REST API endpoint to create/update a user metadata a get its value. I use update_user_meta() and get_user_meta(). Both work properly, in the API where I use get_user_meta() I have the value, but when I use the native REST API of Wordpress /users/me?context=edit In meta object I have an empty array. ![enter image description here](
There's a lot of stuff saved as user meta that has no business being sent over the REST API, therefore the default endpoints do not include every piece of arbitrary meta automatically. If you want a piece of meta to appear in the REST API responses you need to register it with `register_meta()`, with `show_in_rest` set to `true`: register_meta( 'user', 'your_meta_key_here', [ 'show_in_rest' => true ] );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 0, "tags": "user meta, rest api" }
Cloning a website via wget Is it possible to somehow upload files downloaded via “wget -r” onto a server to replicate the actual website, If so how?
Technically, a WGET can be used to download a site's page(s) to your local machine. Then, you could theoretically upload those files to your own web server, and the results will look like the original site. But only as the site existed when you WGET'd the individual pages. WordPress stores all site content in a database, and then 'builds' the page using templates and other processes to display the actual content. If the content changes in the database, then your WGET'd files will not be the same as the actual site. And then there is the whole issue of copyright infringement, and content ownership, which is not something you mentioned. So, although technically possible to 'snapshot' a site (the "Wayback Mahine" does that, for instance), it will not be a 'true' clone of the site.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "clone site" }
create new users in db starting at what ID? I have to create several hundred users using mysql. How do I know which user IDs to give them? I don't want to duplicate already-in-use IDs, so is there a way to check which IDs are safe to use for new users?
You don’t give them IDs. The user ID column in the database is an ‘auto increment’ column, meaning that the value is automatically created whenever a row is added. So just add your users without an ID and the database will create one for you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, mysql, id" }
how to increase connection time actually I'm using this script To increase the connection time // Reste connecté à WordPress durant 1 an add_filter( 'auth_cookie_expiration', 'keep_me_logged_in' ); function keep_me_logged_in( $expirein ) { return 31556926; // 1 an en secondes } it works for some users but not for all, some users are often disconnected. Where does the problem come from ? how to be sure to increase the session timeout
Maybe your hook called too early. And after yours, this connection time changes elsewhere. Try to increase priority like that: add_filter( 'auth_cookie_expiration', 'keep_me_logged_in', 99, 3); function keep_me_logged_in( $expiration, $user_id, $remember ) {/*your code*/}
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, cookies" }
why get_the_post_thumbnail( the_ID()) echos extra post id I have the following snippet which adds post thumbnails to products on archive page if matches a given product category, which will output the image but echos the the post id as well. How do I suppress to not show post id? add_action( 'woocommerce_after_shop_loop_item_title', function () { if(is_product_category('t-shirts')) { $thumb = get_the_post_thumbnail( the_ID()); if(is_string($thumb) ) { echo '<div class="imagewrapper">' . $thumb; } } }, 9 ); add_action( 'woocommerce_after_shop_loop_item_title', function () { if(is_product_category('t-shirts')) { $thumb = get_the_post_thumbnail( the_ID()); if(is_string($thumb) ) { echo '</div>'; } } }, 11 );
I believe because: > **the_ID()** : Display the ID of the current item in the WordPress Loop. and > **get_the_ID()** : Retrieve the ID of the current item in the WordPress Loop. So `the_ID()` _displays_ the post ID. Try to use `get_the_ID()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, woocommerce offtopic, post thumbnails, archives" }
Using the Parcel build tool with Wordpress I've been looking into build tools lately, specifically stuff that allows PostCSS, and would therefore enable to create a build process that among other things would automatically autoprefix, minify and concatenate my Wordpress site. It seems that one of the more current tools for this purpose is Parcel, which also boasts a zero-configuration file approach and therefore has the advantage of being the easiest to get started with. However, Parcel seems to require an index.html file as an "entry file" to get started with it, and I'm unsure how this would work with Wordpress' index.php. Has anyone had success getting Parcel working with a local Wordpress installation, and if so, how would it be done? If not, do you use any other build tools as part of your development workflow, and why/why not?
Parcel is intended to be used to build apps from the ground up. That's why they recommend starting with a index.js or index.html file. You might be able to use Parcel's packaging for a theme or plugin, but you would lose the built-in server and live reloading ("hot module replacement") among other things. There may be more that wouldn't work. I don't think Parcel is a good fit for WordPress development. Read more.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "local installation, xampp" }
I want to redirect the url to the previous page I have created a table in which i have delete link something like and i have added a code to delete the post if ($action == 'batch-delete') { require_once (plugin_dir_path( __FILE__ ).'views/single_batch_delete.php'); } code in the required file is if (isset($_GET['action']) == 'batch-delete') { global $wpdb; $delete_batch = $wpdb->delete( 'batch_number', array( 'id'=>$_GET['post_id'] ) ); wp_redirect( $_SERVER['PHP_SELF'].'?page="batch-op-settings"', 302, 'Deleted' ); } the data row is deleted but it is not redirecting to the all batches code all data i have used wp_redirect function i have also used header() function but it shows this error > Warning: Cannot modify header information - headers already sent I want to know is there any better way to handle this issue or any solution with the current code .
Add below code in functions.php and check it works or not. add_action('admin_init', 'app_output_buffer'); function app_output_buffer() { ob_start(); } let me know if it is working or not.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, wp list table" }
Show subcategory name selected in specific category woocoommerce Hi basically I have categori ID number (134) that has 2 child of that (red and blue). I selected the blue one. I want to display only the selected one (blue). But at the moment the show all subcategories (red and blue). Please help me here my code $args = array( 'hierarchical' => 1, 'show_option_none' => '', 'hide_empty' => 0, 'parent' => 134, 'taxonomy' => 'product_cat' ); $subcats = get_categories($args); echo '<ul class="wooc_sclist">'; foreach ($subcats as $sc) { $link = get_term_link( $sc->slug, $sc->taxonomy ); echo '<li><a href="'. $link .'">'.$sc->name.'</a></li>'; } echo '</ul>'; Here for single product page.
To display only assigned category you need to change **hide_empty** to true. Please see the modified code: $args = array( 'hierarchical' => 1, 'show_option_none' => '', 'hide_empty' => true, 'parent' => 134, 'taxonomy' => 'product_cat' ); $subcats = get_categories($args); echo '<ul class="wooc_sclist">'; foreach ($subcats as $sc) { $link = get_term_link( $sc->slug, $sc->taxonomy ); echo '<li><a href="'. $link .'">'.$sc->name.'</a></li>'; } echo '</ul>'; Please see the updated code: $cats_list = get_the_terms ( get_the_ID() , 'product_cat' ); echo '<ul class="wooc_sclist">'; foreach ($cats_list as $cats) { $link = get_term_link( $cats->slug, $cats->taxonomy ); echo '<li><a href="'. $link .'">'.$cats->name.'</a></li>'; } echo '</ul>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, javascript, html, categories" }
Get list of shortcodes from content I need a list of every shortcode inside the content. Is there any way to list them? This is what I need: $str = '[term value="Value" id="600"][term value="Term" id="609"]'; So every shortcode should be inside the `$str`. I found a code snippet to check if there is a shortcode. But how can I display them all? $content = 'This is some text, (perhaps pulled via $post->post_content). It has a [gallery] shortcode.'; if( has_shortcode( $content, 'gallery' ) ) { // The content has a [gallery] short code, so this check returned true. }
Here's one way: You can look at has_shortcode() and find the parsing there: preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER ); using the get_shortcode_regex() function for the regex pattern. For non empty matches, you can then loop through them and collect the full shortcode matches with: $shortcodes = []; foreach( $matches as $shortcode ) { $shortcodes[] = $shortcode[0]; } Finally you format the output to your needs, e.g.: echo join( '', $shortcodes ); PS: It can be handy to wrap this into your custom function.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "php, shortcode" }
How to Add a Link to the Drop-Down User Menu in the Admin Bar? I need to add a link to the drop-down user menu in the admin bar. Is there a hook or function for this? ![WP admin bar user drop-down menu](
You want to use $wp_admin_bar->add_node( $args ). Below is a tested working example. function wpse_add_toolbar_edit($wp_admin_bar) { $wp_admin_bar->add_node( array( 'id' => 'mylink', 'title' => 'My New Link', 'href' => 'mailto:[email protected]', 'parent' => 'user-actions' ) ); } add_action('admin_bar_menu', 'wpse_add_toolbar_edit', 999); Note: The `parent` param adds the link to an existing ID. If you need to find the correct ID to add your new link to you can `var_dump($wp_admin_bar);` and look through the output for the correct ID.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, admin menu, admin bar" }
How to import Reusable Blocks programatically? How to import Reusable Blocks programatically? I would supply 20 or 30 .json files with Reusable Blocks and the theme admin would be able to use them in their posts or pages. How could I import them programatically on theme activation?
The easiest solution so far seems to be creating the Reusable Blocks as custom post types: wp_insert_post([ 'post_content' => '<!-- wp:shortcode --> [slider] <!-- /wp:shortcode -->', 'post_title' => 'My Slider', 'post_type' => 'wp_block', 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'guid' => sprintf( '%s/wp_block/%s', site_url(), sanitize_title('my-slider') ) ]); This way, I can create a library of blocks, loop and import them all. Probably, as @kero mentioned, the core JSON import works the same internally.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor" }
Wordpress AJAX PHP(html) file that is within Wordpress Loop I have a Wordpress AJAX call that is working in as much as it is able to get raw data from a PHP file. The AJAX is using the admin-ajax.php file. However, the PHP file I need to get is within the loop of the page. Where it is being placed is where it works if it was just included on the page. To summarize: if the PHP file being AJAXed has in it: <?php echo 'this is the file!' ?> …everything works fine. But if it has: <?php the_title(); ?> …it returns blank. Thank you for taking the time to read this!
There is no such thing as an AJAX call that's inside the loop. The server has no idea what page or where on that page an ajax call is coming from unless you explicitly send it that data as a part of the ajax call. You're going to need to send some data to the php function so it can recreate the correct query (or the current post if that's all you need.) i.e. You send a post ID in the ajax, the php function it calls then does `$post_id = $_POST[post_id];` (please add your own sanitization and validation here.) Then instead of calling `the_title()` you would call `get_the_title($post_id)`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, ajax" }
Taxonomy page template changing when using query variables I'm hoping someone can help me fill in the gaps in my understanding of page templates and query vars: I've registered a custom taxonomy 'stream', and have set up a page template for that taxonomy, taxonomy-stream.php. The page template lists an archive of posts that are using the respective taxonomy term. Everything there works fine. I'm trying to add a filter to the sidebar to allow the user to narrow down the taxonomy archive of posts based on Categories. I am finding that if I add a query var to the URL (?category_name=text, for example) that the page template switches from my taxonomy-stream.php template to archive.php. My goal, however, is for the ?category_name=test query var to limit the results of the taxonomy archive. The query var itself seems to be changing the page template to archive.php instead of keeping it on the taxonomy-stream.php template. What am I missing here?
The problem is that `category_name` is a reserved keyword for the built-in categories for posts. Almost anything `category_*` is reserved. You can find a list of reserved keywords at the following url: < This includes, but is not limited to: * cat * category * category__and * category__in * category__not_in * category_name * term * terms Behind the scenes it sees that you're using the `category_name` reserved keyword. It knows categories are a taxonomy of posts and switches to the `archive.php` template. If the `archive.php` template did not exist it would default to `index.php` and try to load posts looking for anything in the `test` category (taxonomy).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "custom taxonomy, page template, query variable" }
Category tags with comma's I have in my code the following variable to call the title of the categories. <?php $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category'); foreach ($categories as $category) { $cats .= $category->name . ', '; echo rtrim($cats, ', '); } ?> The problem is that in the last post of the loop I duplicated the categories and printed them all. ![enter image description here]( in fact it is printed by post from less to more. If I use the following code fragment, I print it well but without commas foreach ($categories as $category) { echo '<span>'.$category->name .'</span>'; } If someone would be so kind to guide me I would be very grateful, this brings me
In this line: $cats .= $category->name . ', '; You append a name of category to variable called $cats. But you never reset this variable. So every post appends its categories to the same variable. So here’s how to fix this: <?php $categories = get_the_terms($custom_args->ID, 'veranstaltungen-category'); $cats = ''; // set empty string as value foreach ($categories as $category) { $cats .= $category->name . ', '; echo rtrim($cats, ', '); } ?> Of course you can also add commas to your second code: foreach ($categories as $i => $category) { if ( $i ) echo ', '; echo '<span>'.$category->name .'</span>'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, loop" }
Best way of deletion of old posts I have a few sites that I wish to slim down. The sites have been active for a long time and there is really old post data that is no longer relevant. I wish to delete those (older then 3 years) and there meta data, their attached media, revisions and including W3 cache files. Also a database cleanup can help a bit. **Which method is best?** 1\. Plugin 'Bulk delete' with pro addon delete 'delete attachment' 2\. wp-cli post delete 3\. WP api function
I will use the wp-cli version: wp post delete --force $(wp post list --post_type=post --format=ids --year=2008 --posts_per_page=10000) I added the --force so that it will delete the post and not just put them in the trash.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, customization" }
How to insert a short code into Contact Form 7 in Wordpress that will call a function once the submit button is pressed How (or where) do I insert a short code that will call a function (written in a plugin called 'code snippets') when the submit button is pressed. I am trying to get the submit button to send data to an external database instead of sending mail. I have the actual function written already but no matter where I place the short code nothing happens when the submit button is pressed. The external database lives on the same IP address as the wp database. I have been struggling with this short code for a bit of time now so thought I would pose the question.
You can achieve it by changing the action of the particular form and then use the function to store the data in the database into a new file. add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url'); function wpcf7_custom_form_action_url($url) { global $post; $id_to_change = 1; if($post->ID === $id_to_change) return 'wheretopost.asp'; else return $url; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
Add shortcode with open close function I have a website with a lot of [mybutton]click here[/mybutton] or [mybutton]click there[/mybutton] in editor. I need to add a function to create a href from this shortcodes. Closing of shortcode is a problem for me. How can i do it?
To change the functionality of a shortcode you must first `remove_shortcode( 'shortcode_name' );` where shortcode name is the name of the shortcode. Add the shortcode back with your NEW function. A simple example to follow what you might be needing: remove_shortcode( 'mybutton' ); add_shortcode( 'mybutton', 'my_shortcode_function' ); my_shortcode_function( $atts, $content = "" ) { return '<a href=" . $content . '</a>'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode" }
get_the_id, get_the_permalink, and get_the_title all with one DB call we are trying to optimize a heavy traffic WP site, and am looking for a way to get the data for these three WP functions with only one query, in order to reduce queries & load on DB server: $wpid=get_the_ID(); $title=get_the_title($different_post_id); $perma=get_the_permalink($different_post_id); Is this possible? EDIT-- adjusted above example code to correctly indicate that in this case, we're grabbing the title and permalink for a different post_id -vs- the one that's returned by get_the_ID();
These functions do not even call the database each time they are run. It just pulls them off the current post object that was returned by the database query that retrieved the posts. There's nothing to optimise here. `get_the_ID()` and `get_the_title()` literally just return `$post->ID` and `$post->post_title`. `get_permalink()` is a little bit more complicated, because it needs to do logic to figure out what the URL should be, based on permalink settings etc., but it doesn't require additional database calls. WordPress is not _so_ poorly optimised that you need to do anything about these functions. If it's how the documentation tells you how to do it, and it's how the default themes work, then it's _fine_. If you're concerned about the speed of your site, then install Query Monitor and at least check what queries are _actually_ being made before deciding on a target.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "performance, optimization" }
Error Handling when building Wordpress themes I'm very new to the developing world and have been, with the help of Youtube, been learning to design Wordpress themes with HTML, CSS and PHP. I am using MAMP to locally host my wordpress site. When I make an error, like forgetting to close my PHP tag, and I refresh my site, all I see is "the site is experiencing technical difficulties" and I'm not sure where I can check my syntax or other errors. Any suggestions?
When developing it's a good idea to enable debugging, as described in this article in the developer handbook. Essentially in wp-config.php you want to define the `WP_DEBUG` as `true`. define( 'WP_DEBUG', true ); This will cause WordPress to output more errors and warnings to the screen, which can help finding issues. You can also log these to `wp-content/debug.log` by setting `WP_DEBUG_LOG` to `true`: define( 'WP_DEBUG_LOG', true ); In 5.2+ you might also want to disable the 'fatal error handler', which is responsible for the screen that's displaying the "the site is experiencing technical difficulties" message. define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true ); Just keep in mind that none of these should be turned on in a live environment.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
wordpress themes and plugin customization Wordpress has been the best for me. Now I have been working with wordpress plugin and themes using various wordpress hook and filter for my site. Currently I need to 1.) change the successful message that is display by default when a user successfully registered 2.) I need to change the various error message during users registrations or login. Eg email is not available, password is empty etc. 3.) I need to hide wordpresslost password link on both signup and register page 4.) I need to edit and style wordpress login form, registration form, login and signup submit button. **I already know how to change wordpress image logo** Please what hooks or filter function do I have to call to achieve this. I cannot properly find it in wordpress codex. Any single solution provided will be awesome. Thanks
Have you started here: < ? All the hooks and filters....and more.. Or here: < ? Hooks and stuff for plugins. Or here (for login forms) < ?
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins" }
How can I view wordpress site hosted locally in my home LAN network from the Internet (outside LAN network)? I have my wordpress multisite setup in LAN network. I also setup dynamic DNS (eg. www.mysite.com) which is directed to my router's public IP (eg. 10.10.10.10). My router will port forward any request to my server's IP (eg. 192.168.0.100). When I tried to view the wordpress site from another device in my LAN network by typing in my server's IP in the browser, the site showed up nicely. But when I tried to view the site from a device outside of my LAN network by typing in the dynamic DNS name or my router's public IP, the browser showed that there was an error. Sometimes it show timed out error and sometimes it show that a network change has been detected. The site URL and wordpress URL was set to (< for this example. Is there any way I could configure so that the site could be viewed from outside the LAN network? Any solution is much appreciated.
You need to set up port forwarding on your router. So when you go to your public-facing IP address (say it's 204.122.30.5, use a "what's my IP" site, or check your router's info page), you'll want to set up incoming port xxxx to forward to your local server (in your case 192.168.0.100). Once you get it set up, if you go to < (your public-facing address plus the port number you set up for port forwarding), you should be able to get to your local site from the outside. For the 'xxxx' number, choose a four-digit value that is random. Be aware that there are some security risks involved in allowing outside access to your home network. There are things you can do to mitigate those risks. Lots of googles/bings/ducks can help you out with that and port forwarding. Your router's manufacturer's support pages will also help with setting up port forwarding.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "localhost, hosting" }
Changing navigation strip color with CSS I own a website, Digital Phablet, i want to know how can i change thr color of Blue strip to Red? I have attached the picture too as well as you can check it on my website by typing the name on google. Please give CSS to change it. !enter image description here
In file named style.css on line 1235 .mobile-navbar { height: 44px; background-color: red; } and on line 3824 .header-bottom { position: relative; height: 50px; background-color: red; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
http: not showing in wordpress permalink setting http: not showing in wordpress permalink setting any body can advice to fix this ![enter image description here](
Go into the wp-options table. Change the URL of your site in two places to < . Or go into the Admin, Settings, General, and fix the URL there. (The setting on that screen reads the value from the wp-options table.) Make sure there are no URL settings in the wp-config.php file. Any setting in wp-config.php for the URL will override the settings in wp-options, and you will not be able to change the setting on the Settings, General page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks" }
Woocommerce Moving Review Below add to cart breaks button Trying to add the reviews on a site below the add to cart button in woocommerce. Both these snippets of code do it: add_action('woocommerce_after_add_to_cart_button', create_function( '$args', 'call_user_func(\'comments_template\');'), 14); function woocommerce_template_product_reviews() { woocommerce_get_template( 'single-product-reviews.php' ); } add_action( 'woocommerce_after_add_to_cart_button', 'comments_template', 50 ); The add to cart will now not work unless you complete a review. Is there a way to do this with hooks? Or will I need to use jQuery to clone and move the review code to where I want it.
`woocommerce_after_add_to_cart_button` is inside the `<form>` element for adding items to the cart, but the reviews form is its own form, and you can't have one form inside another form. You need to pick a hook that's not inside a `<form>` element. `woocommerce_after_add_to_cart_form` seems to be the closest that's still outside a form.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, jquery, hooks" }
Enable errors PHP Wordpress 5.2 Since Wordpress 5.2 can not display errors on the site. The constants " _WP_DEBUG_ " et " _WP_DEBUG_DISPLAY_ " doesn't work. The following message is always displayed : "The site is experiencing technical difficulties. Please check your site admin email inbox for instructions." Have you solution?
You can disable this behaviour by setting `WP_DISABLE_FATAL_ERROR_HANDLER` to `true`: define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true ); This will stop the "The site is experiencing technical difficulties" message from appearing, so errors will appear as they did prior to this feature being added.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "php, errors" }
How to get category lists by name or slug Currently I am able to get all categories but I want only few categories to display based on name or slug for example. $categories = get_categories('accessibility','wcag', 'abc'); is this possible ?
If you are looking for specific term objects from the term slugs, from a specific taxonomy, I think new WP_Term_Query() is your best bet: $term_args = array( 'taxonomy' => 'category', 'name' => array( 'accessibility','wcag', 'abc' ) 'hide_empty' => false, 'fields' => 'all', 'count' => true, ); $term_query = new WP_Term_Query($term_args); foreach($term_query->terms as $term){ echo '<pre>'; print_r($term); // You'll see the term object here, which is what I think you are after echo '</pre>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, categories" }
How can I say if a URL is a post, page, or taxonomy archive? I'm studying for SEO purposes how a few WordPress sites (that aren't mine) are organized, link structure architecture and so on. Therefore I need to know if a specific URL of a website is a post, page, or a taxonomy archive. Can I do that using Chrome Inspect tool? How? If no, so any other way to get this information? Thanks for all help!
WordPress sites usually use `body_class()`, which adds CSS classes to the `<body>` tag. If you inspect the body element itself, most sites will show you something like `<body class="page-template page-template-tpl-events page-template-tpl-events-php page page-id-1168 page-parent page-child parent-pageid-378">` You can tell from these classes that this is a Page, using a Page Template, it is a Parent, and it is also a Child. You'll see similar classes that tell you when you're on a Post, Archive, etc.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, directory, google chrome" }
Auto approve new users if their username is included in a predefined list I need to have users' registration in my website as Subscribers. Each user will provide a username. I need to have a list that contains a company's usernames and then I need to automatically approve any new user that his/her id is included in that list. Is there an easy way to that support this procedure?
You might put this code in `functions.php` : $GLOBALS['allowed_users']= ['mikejordan', 'jamesbrown', ...]; add_action('user_register','my_function'); function my_function($user_id){ // get user data $user_info = get_userdata($user_id); if ( in_array($user_info->login, $GLOBALS['allowed_users'] ) ) { $res = $wpdb->query($wpdb->prepare("SELECT activation_key from {$wpdb->signups} WHERE user_login = %s)", $user_info->login)); if (!empty($res)) { wpmu_activate_signup( $res->activation_key ); } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user registration" }
How to use query string in URL to display content on the wordpress page My wordpress page URL is like this https:www.com/thanks-page/?origin_name=Sydney&origin_iata=SYD&destination_name=Ahmedabad&destination_iata=AMD I need to display SYD and AMD in to the page content like this.. Flights from SYD to AMD... How can I display those two Param query sting in to the actual wordpress page. Thanks in advance.
Simple, you can use $_GET method. if(isset($_GET["origin_iata"]) && !empty($_GET["origin_iata"]) && isset($_GET["destination_iata"]) && !empty($_GET["destination_iata"])) { echo "Flights from ".$_GET["origin_iata"]." to ".$_GET["destination_iata"]."..."; }
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "urls, parameter, query string" }
How to stop my themes CSS changing the Wordpress interface/? I'm currently busy exploring Wordpress theme development. I've made a theme and uploaded it to my Wordpress development site. In a css file of me, I've declared some styles for the h1, h2, h3 etc. The thing is that some of those styles are being applied to header in my Wordpress interface. This is of course not how it should be. Has anyone an idea on how to fix this? Other Wordpress themes that I used never had this weird thing. ![Image as an example](
This can happen if the function for enqueueing stylesheets, `wp_enqueue_style()` is run inside functions.php outside of a hooked function, like this: <?php wp_enqueue_style( 'my-style', get_stylesheet_uri() ); functions.php is loaded on the front-end and back-end when your theme is active, so this will load the stylesheet in both places. To only load a stylesheet on the front-end you need to run this function inside another function that is hooked to the `wp_enqueue_scripts` hook: <?php function wpse_341512_enqueue_styles() { wp_enqueue_style( 'my-style', get_stylesheet_uri() ); } add_action( 'wp_enqueue_scripts', 'wpse_341512_enqueue_styles' ); By doing this, `wp_enqueue_style()` is only run when `wpse_341512_enqueue_styles()` is run, and using `add_action()` like this queues up that function to only run on the front-end.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "css, admin css" }
JavaScript Change focus to password field login page being reset I have a special situation where I want users on the standard WordPress login page enter a password. I'm filling in the username with a line of javascript: document.getElementById('user_login').value = 'username'; By default the focus starts on the username field. I want to have the focus start on the password field... document.getElementById('user_pass').focus(); but this isn't working. It looks like it might be focusing on the password field for a moment and then going back to the username field. Any idea why this might be happening and how to fix it? (I don't want to just hide the username field, I need actual admins to be able to login as usual. This special autofilled username only gets role access to one little part of the site. And I don't want to use a password protected page for other reasons.)
This sounds like a timing issue, there is probably already some JS running after your script is ran. Try wrapping your JS in $(window).load(), this will run the function after other page assets have loaded and should fix the timing issue. For example... $(window).load(function() { document.getElementById('user_pass').focus(); }); Here is some info about the difference between $(document).ready() vs $(window).load().
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, javascript, wp login form" }
ACF under category name in shop page I'm using display categories only for shop page setup in woocommerce. I added custom field (textfield) for product categories in Advanced custom fields. I would like to display this text under category title on shop page (not on category page). in content-product_cat.php after do_action( 'woocommerce_shop_loop_subcategory_title', $category ); I added: $term_id = get_queried_object()->term_id; $post_id = 'product_cat_'.$term_id; $custom_field = get_field('krotki_opis_kategorii', $post_id); // My Advanced Custom Field Variable echo $custom_field; But it's not working.
If i understand you correctly here you want to display some text under each of the category titles on your shop page. Instead of editing the template i would suggest using a hook. To do this you should move your code into **functions.php**. **The complete code would look something like this:** add_action('woocommerce_after_subcategory_title', 'wpse_add_custom_text_under_category_title', 10); function wpse_add_custom_text_under_category_title($category) { $term_id = 'product_cat_'.$category->term_id; the_field('krotki_opis_kategorii', $term_id); } The reason why your code is not working is because when you run **get_queried_object_id** on the shop page it will return the id of the page and not the category. When you use the hook, the **$category** object will be passed in through the hook like in the code above. Hope this was what you were looking for. I did not test this code but it should work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic, advanced custom fields" }
Will current_theme_supports return TRUE with a nonstandard add_theme_support? Will `current_theme_supports()` return TRUE with a nonstandard `add_theme_support()` string? If I do this in my theme: add_theme_support( 'my_funky_new_thing' ); Can someone else writing a plugin do this? if( current_theme_supports( 'my_funky_new_thing' ) ){ // ... }
Yes. You can take advantage of this to enable or disable features in your plugin if a theme does or does not declare support for a feature. WooCommmerce is an example of a plugin that does this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, add theme support" }
Shortcode to show current post category with link I want to display the current post category with link using shortcode **[post_category]**. The current code I got below shows the current category as text. I want it to be a link to the category. Thanks. function category_name_shortcode(){ global $post; $post_id = $post->ID; $catName = ""; foreach((get_the_category($post_id)) as $category){ $catName .= $category->name . " ,"; } return $catName; } add_shortcode('post_category','category_name_shortcode');
One way of doing it would be to modify your current code and add the links in there: function category_name_shortcode() { global $post; $post_id = $post->ID; $catName = ""; foreach((get_the_category($post_id)) as $category){ $catName .= '<a href="' . get_term_link($category) . '">' . $category->name . '</a>, '; } return $catName; } add_shortcode( 'post_category', 'category_name_shortcode' ); But there’s an easier way, because WP already has a way to obtain the list of categories with links (`get_the_category_list`): function category_name_shortcode() { return get_the_category_list( ', ' ); } add_shortcode( 'post_category', 'category_name_shortcode' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "shortcode, post meta" }
Move dashicons.min.css to Footer Hey there WordPress community, Google page speed is moaning about dashicons.min.css being on our site. However, we need it for the Mega menu. I wanted to know if it's possible to move it to the footer. I have tried this code already: add_action( 'wp_print_styles', 'my_deregister_styles' ); function my_deregister_styles() { wp_deregister_style( 'dashicons' ); wp_enqueue_style( 'dashicons', array(), false, true ); } I have also tried a few other samples, however, nothing seems to work here. Any ideas? Thanks
Please try below code : add_action( 'wp_print_styles', 'my_deregister_styles' ); function my_deregister_styles() { wp_deregister_style( 'dashicons' ); } Replace your css path "PATH_OF_CSS" : add_action( 'wp_footer', 'register_wp_footer', 11 ); function register_wp_footer() { wp_enqueue_style( 'dashicons', 'PATH_OF_CSS' ,array(), false, true ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp enqueue style" }
infinite loop in wp_query using simple query This code goes into an infinite loop! What am i doing wrong? There is only one post called “hello there”. The only way to stop it is use `break;` in while. Any help appreciated $gotop="hello there"; $args = array( 's' => $gotop, 'post_type' => 'post' ); $wp_query = new WP_Query($args); if ( $wp_query->have_posts() ) : ?> <?php while ( $wp_query->have_posts() ) { $wp_query->the_post(); } else: echo "nothing found."; endif; ?>
I'm not certain why it would cause an infinite loop, but make sure not to use `$wp_query` as the variable name for your custom query. It's a reserved global variable for the main query. Use a different name for the variable. I'd also suggest using `wp_reset_postdata()` after the loop: $my_query = new WP_Query( $args ); if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) { $my_query->the_post(); } else: echo "nothing found."; endif; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query" }
Why I can't change the permalink of a WP page? I wonder if you can help me, please? I have the following problem with a permalink. I have tried to change the permalink for the following link from < to < by going into page on the Dashboard and editing it there. Each time that I save it, WP changes it back to what-are-impact-goals-2. I can change it to other things (eg impact-goals) but not to what-are-impact-goals. I searched for help and one recommendation is to empty trash. I have no pages in trash. Other is to check Media. Again, no similar link. < takes me to my homepage. I presume that WP has what-are-impact-goals recorded somewhere. Any ideas?
May be the main reason of this issue is that the WordPress finds that this URLs already assign to any post which exists in database. so You have to check permalinks of the every pages/post or attachments are not using that permalink. It could be in publish, drafts or trash as well. or you can find in wp_posts table in database from phpmyadmin. you can search using : wp_posts > search tab > "post_name" operator LIKE%..% value "what-are-impact-goals" or you can fire SQL query in SQL tab: SELECT * FROM `wp_posts` WHERE `post_name` LIKE '%what-are-impact-goals%' Check there is permalink already exists or not. then after you can take action.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks" }
Where i must put hooks in overridable functions? Where i must put hooks in overridable functions for better child themes? Inside if statement or outside? if( !function_exists( ovveridable_function() ) { function overridable_function() { echo 'Test'; } add_action( 'init', 'overridable_function' ); } **OR** if( !function_exists( ovveridable_function() ) { function overridable_function() { echo 'Test'; } } add_action( 'init', 'overridable_function' );
Neither. Hooked functions don’t need to be pluggable because child themes can already unhook and replace them with `remove_action()`. The main functions that you’d want to make pluggable are functions that are used in templates i.e. template tags, and those functions aren’t usually hooked, so the placement of `add_action()` isn’t relevant. Even then you probably only need to make them pluggable if they’re used in multiple templates, because otherwise the child theme could just replace the template file.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, child theme" }
How to clean up the theme for production? Is there some automated way to generate a dist/production version of the theme without all of the hidden .git, IDE directories and the config files, node_modules? WARNING: .babelrc .git .gitignore .idea .sass-cache .bin .npmignore .github .travis.yml .coveralls.yml .eslintrc .gitattributes .jshintrc .verb.md Hidden Files or Folders found. REQUIRED: Please remove any extraneous directories like .git or .svn from the ZIP file before uploading it.
You can use gulp zip to do that. Take a look here < This will let you zip up your theme with a terminal command and you can ignore whichever folders you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, customization, production" }
edit.php all post not working i am using publish press plugin to create a custom post status i changed the all post status into public, using this register_post_status( $status->slug, [ 'label' => $status->name, 'public' => true, 'exclude_from_search' => true, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, '_builtin' => false, 'label_count' => _n_noop("{$status->name} <span class='count'>(%s)</span>", "{$status->name} <span class='count'>(%s)</span>"), ] ); all post shown at front end but edit.php all post page not working it not showing the all the post which is relevant to custom post type and it also affected the woocommerce
finally found the solution when i enter all the custom post status to **public** it declare the post_type to default post as global so applied filter to change the global post_type based what type request get in URL function publishPress_allPost_pre_get_posts( &$wp_query ) { if ( is_admin() && array_key_exists( 'post_type', $_GET ) ) { $wp_query->set( 'post_type', $_GET['post_type'] ); add_filter( 'the_posts', 'publishPress_allPost_the_posts', 10, 2 ); } } function publishPress_allPost_the_posts( $posts, &$wp_query ) { $wp_query->set( 'post_type', $GLOBALS['post_type'] ); return $posts; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, woocommerce offtopic, post status" }
How to add a panel/box/widget/are/screen to the right side of edit post/page confusion I have been reading through the WP plugin docs to try and figure out how to display information on the right side of a post or page when an admin is creating or editing a post or page. I don't seem to be able to find this anywhere or I got something wrong, right now I am just confused. I read about Dashboard widgets and tried it, but they only displayed the widget on the dashboard not when editing a post/page. Then I thought it could be done with metabox, but that seems to only add a custom field to the settings bar. I need to use html/php/jquery so I guess that will not work either. I just want a panel to the right that is visible when a user/admin edits a page/post. In the panel I need to use html/php/jquery. What is the correct way to do this?
If you're using classic editor, then add_meta_box() will do the trick. Just make sure you set the context as "side". With Gutenberg I think you'll need a Panel component. I'm not too familiar with Gutenberg so I can't comment more on this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, javascript, admin ui" }
how can i add more than one custom taxonomy? I want to add more than one taxonomy. i tried `get_terms( 'CUSTOM_TAXONOMY','CUSTOM_TAXONOMY-2', array` but second tax not work $i = 1; // get the terms you need $terms = get_terms( 'CUSTOM_TAXONOMY', array('orderby' => 'count', 'order' => 'DESC', 'hide_empty' => 0 ) );
i fixed $terms = get_terms([ 'taxonomy' => array('bank','dovlet_qurumu'), 'hide_empty' => false, ]); her
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy" }
How do I get information about a page, such as featured image, except, and title? Assuming that I learn how to do this, how do I pull information about the user's selected page and display them? Obviously, I start with $mytheme_f_page[1] = get_theme_mod( 'mytheme_featured_page_1', '' ); What do I do to pull the information about this page? As there will be three, can I get all three at once or do I need to do it one at a time? I'm going to need the thumbnail, the title, and the excerpt.
When you save a selected page in the Customiser you're just saving the post ID of the page, which means you can just pass that value to any function that accepts a post ID as a parameter: $mytheme_f_page[1] = get_theme_mod( 'mytheme_featured_page_1' ); echo get_the_title( $mytheme_f_page[1] ); echo get_the_excerpt( $mytheme_f_page[1] ); echo get_the_post_thumbnail( $mytheme_f_page[1] ); The first time you use any one of these the full post (page) is cached internally, so you don't need to worry about getting them one at a time or all at once, or anything like that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "theme development, pages" }
How do I get WordPress to create resizes of a supplied default image in a theme? In case my recent questions have not made it abundantly clear, I am trying my hand at theme creation. Among the many other things that I am still figuring out are image sizes. Specifically `add_image_size(...)`. I know I can use it to tell WordPress the sizes to make default images and so forth. Can I do that with an asset in my theme? In my theme, I have an assets folder which contains a 1200x1200 image for use as a default in a range of cases. One part of my theme calls for images 140x140. Now, I could push that huge file into the `src` for an image but it would be kinder on page load times if I resized it. The do it myself hack would be to open GIMP and make one image for every size I can possibly imagine wanting. Given I'm changing things all the time, I would rather let WordPress do that for me. Can I do that? If so how?
Images sizes are only relevant for uploads in the media library. If you have assets in your theme then you need to include whichever sizes are needed for how they're used in the theme. Since end users can't choose your theme's bundled images to place wherever they want, you don't need every possible size. You'll only need the sizes that you use.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "media, images" }
How to configure two SMTP Server for wordpress What I need is : I need to send transactional e-mails from two SMTP configurations. All WooCommerce side of e-mails should send from [email protected]. Example: order summary, delivery status. All WordPress user side of e-mails should send from [email protected]. Example: Forget password e-mail, account creation e-mail. Note: All methods are working. I just want to send different e-mails from their respective purpose.
Disclaimer: this is clumsy, someone might have a better suggestion. But here's one idea: 1. Leave WordPress configured with your [email protected] settings. 2. Set up Woo with the [email protected] address (WooCommerce -> Settings -> Emails -> From Address). 3. Hook woocommerce_mail_callback with your own function that temporarily hooks phpmailer_init to change the SMTP configuration before calling wp_mail. Or perhaps you can skip step 3 if your SMTP server can be configured to allow an alternate "from" address for authenticated users. And just a heads up: WooCommerce supplies its own forgot password and new account emails, so you'd need to decide whether you want to return those to their WordPress defaults, or just change them as well in step 3.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, woocommerce offtopic, smtp" }
How to get all CPT names into WP_Query 'post_type' parameter? hello I want to display post based on his ID. This post could be a default 'post', 'page' or other registered custom post type. In query I sould specify all CPT names which I want to use, for eg. 'post_type' => array('post', 'page', 'my_cpt') My question is how can I set 'post_types' automatically for all registered post types, without manually specify them? I'm striving for something like that: $post_types = ALL-POST-TYPES-NAMES; $the_query = new WP_Query( array( 'post_type' => $post_types, 'p' => ID, ) ); Thanks!
You can get a list of post types with the `get_post_types()` function: $post_types = get_post_types(); In your case you'll want to set the second `$output` parameter to `names` (since that's what you need to pass to the `post_type` argument), and you'll probably want to set the `$args` in the first argument so that only public post types are returned, otherwise you could end up with weird stuff like menu items and revisions: $post_types = get_post_types( [ 'public' => true ], 'names' ); However, it looks like you're just looking for a specific post based on the ID. If that's the case, then you don't need post types or a query at all. Just pass the ID to `get_post()`: $post = get_post( $id );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post type" }
Change "Shipping" text to "Delivery" everywhere I appears in woocommerce I only offer local delivery in my woocommerce store. but there are several pages that refer my delivery method as shipping. Ship to, shipping type, shipping address, free shipping, shipping date, shipping time. is it possible to change or override every instance the word "Shipping" appears and change it to "Delivery" or "Deliver"
You can use custom **functions.php** file inside your theme folder. If a file named functions.php already exist, then you can use the following formulae. You can also create a functions.php file by yourself in the theme root folder if it does not exist. <?php /* Functions.php file Description: Site specific codes and functions */ function fix_woocommerce_strings( $translated, $text, $domain ) { // STRING 1 $translated = str_ireplace( 'Shipping', 'Delivery', $translated ); return $translated; } add_filter( 'gettext', 'fix_woocommerce_strings', 999, 3 ); //EOF ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "woocommerce offtopic" }
Calling a function from functions.php in custom page/ blog post Is it possible to call a function from functions.php in custom page or blog post? I put simple function in functions.php: function testTest() { echo "Test"; } And called it from the page: <?php testTest();?> But it doesn't work. Do I need to make a plugin to use simple function like that inside one chosen custom page? Thanks for your answer, Mary
You could use add_shortcode if you want to use it within the editor. function footag_func() { return "Test"; } add_shortcode( 'footag', 'footag_func' ); And then use [footag] in your editor. Or Use code like this in functions.php and add a conditional tag add_action( 'loop_start', 'your_function' ); function your_function() { if ( is_singular('post') ) { echo 'Test'; } } or Create a function in functions.php function your_function() { return 'Test'; } And then use this in your template echo your_function();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugin development, functions, pages, page template" }
rename navigation menu label in wordpress theme by code Hello there i have a navigation menu in my wordpress theme. The navigation menu has two items. One has the label “home” and the other “categories”. I need to rename the label “home” to something else and the “categories” label name as well. How is this possible on the fly?
Maybe try filtering just the menu items you want when they get printed back on the front end. You can do that in functions.php Here you can filter the HTML list content for navigation menus. < After some talk, give this a try and then call your `lo()` where you need it: function lo() { add_filter( 'wp_nav_menu_items', 'dynamic_label_change', 10, 2 ); function dynamic_label_change( $items,$args) { if($args->theme_location == 'primary'){ $items = str_replace("Categories", "new_string", $items); $items = str_replace("Latest Offers", "another_new_string", $items); } return $items; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Woocommerce product search result layout page I have made a 'archive-product-custom.php' file who is called in 'taxonomy-product-cat.php'. I do this to easily change the layout of product when a user is looking on a specific category page (in the archive-product-custom i changed the wc_get_template_part to my "content-product-custom" file) This is the only one and easiest method i found for doing what i want without broke the entire theme (content-product template is used everywhere.. related, cart, up-sells, cross-sells) Is it possible to change the layout of the search result with the same above techniques? Or maybe you have a better solution for me? All i want is a custom product layout on each category page and search result without changing the cross-sells, up-sells and related product layout
Usually there is a comment at the start of each WC template file, which basically says: `This template can be overridden by copying it to yourtheme/woocommerce/wc-template-name.php.`. This is the correct and recommended way to override WooCommerce templates. I think you should look into having a child theme for when there is a theme that already have those templates overridden, or even if it doesn't. See < for reference. What I said above is applicable for the `search.php` as well. Of course it will depend very much on your theme setup. If you provide more details on where and what you're trying to achieve, then I can be more specific.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom taxonomy, woocommerce offtopic" }
Why is my multisite installation not showing all the available sites? Please check out the image below, there are four sites listed on the right side but only three of them appear on the drop down menu on the left. The site that is missing is not the main website. ![enter image description here](
This is because you're only a member of 3 sites. As a super admin you have the ability to view the full site list via the network admin, but that doesn't mean you're a part of every site. The admin bar menu only lists the sites you're a member of, not the full list, that's how it's intended to work. Otherwise users would see sites listed that they have no access to. For example, on my own site, there's a subsite I created for a friend. It does not appear in the admin bar menu either. If I look at the users page, I am not listed. The only reason I have access is because I am a super admin. As a result it's listed in the network admin, and I can access the site as if I were an administrator. Despite my super admin access, until I add myself to the site I won't have a role on it, and it won't show in the admin menu.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "multisite, admin" }
What is difference between 'Page Cache' and 'Object Cache' in WordPress? I am optimizing my WordPress website. I am using 2 WordPress plugins right now. First one is 'Autoptimize' for optimizing CSS, JS, and HTML. And another one is 'WP Super Cache' for caching pages. While reading about WordPress optimization, I came across another term called 'Object Caching'. But I still can't figure out the difference between 'Page Cache' and 'Object Cache'. Can someone help me understand this? Is 'Object Cache' needed even if I am using 'Page Cache'?
Page cache is the entire rendered html output for a page. It's useful for serving static content like a WordPress post. Object cache is often the resource-heavy pieces that make up a page. For example, When you use `WP_Query` each result would be stored in object cache. This prevents WordPress from hitting the database every time `WP_Query` is used. For example, if you use ajax for pagination, the next page of results would be stored in object cache and not in page cache.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "cache, plugin w3 total cache, plugin wp supercache" }
adding the_custom_logo(); to header i want to show logo on navbar section.the logo appears but i cant control it with css. <?php wp_head(); ?> <nav class="navbar navbar-expand-md navbar-light sticky-top" style="background-color:rgb(3, 0, 180);" role="navigation"> <div class="container" > <!-- Brand and toggle get grouped for better mobile display --> <a class="navbar-brand" href="#" > <img src="<?php the_custom_logo(); ?>" height="42" width="42"> </a> i typed notes on screen picture: ![enter image description here]( <
The biggest issue you're running into is putting `the_custom_logo()` inside of an `<img>` tag. The function already outputs a full image tag, plus a link to the homepage wrapped around it. So, replace this <a class="navbar-brand" href="#" > <img src="<?php the_custom_logo(); ?>" height="42" width="42"> </a> with this <?php the_custom_logo(); ?> to get rid of the first and third arrow in your screenshot.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css" }
How to reference a function from a class in a different file which is also namespaced? For example I am inside a file1.php with a namespaced class, like so: <?php namespace FrameWork\CPT; class CPT{ ..... public function register_custom_post_type() { $args = array( 'register_meta_box_cb' => //PROBLEM: How to reference from a different file which also contains a namespaced class register_post_type('plugin-cpt', $args); } How do I access a public function from a namespaced class from file2.php? <?php namespace FrameWork\Helper; class Metabox{ ..... public function register_metaboxes() { // I want to reference this function }
Firstly, to do this the `register_metaboxes()` method needs to be static: public static function register_metaboxes() { } Then, for the callback you pass an array with the full class name including the namespace: $args = array( 'register_meta_box_cb' => [ 'FrameWork\Helper\Metabox', 'register_metaboxes' ], ); If, for whatever reason, `register_metaboxes()` isn't static (i.e. you're using `$this`) then passing the class name isn't enough, you need to pass an instance of the class: namespace FrameWork\CPT; class CPT { public function register_custom_post_type() { $meta_box_helper = new FrameWork\Helper\Metabox(); $args = [ 'register_meta_box_cb' => [ $meta_box_helper, 'register_metaboxes' ], ]; register_post_type( 'plugin-cpt', $args ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "namespace" }
Access to apache logs from plugin how can I access to php logs using plugin ? I would like in my plugin to show logs, in case there will be some error user can easily check log and send me it.
If you have Try and cache block and loggin error manually than you can try this : $mylogfilepath = plugin_dir_path(__FILE__).'debug.log'; $errormessage = 'SOME ERROR'.PHP_EOL; error_log($errormessage, 3, $mylogfilepath); Place debug.log file directly inside your plugin. and it will log error to that file. third attribute in error_log set path of file in which log should be recored.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development" }
Editing fields required in the WooCommerce / WordPress registration form I can't seem to find the template file or find the setting within WooCommerce to amend the fields requested in the registration form for a WordPress site. I did not set up the form to begin with and have been brought in on this project. Does anyone know where this form is saved and how I can go about removing the 'Organisation' field? It is a required field making this more than just hide it with CSS jobby. I'm here to answer any questions / fetch any helpful information about my set up. Thanks, Jason.
I found these were custom fields set up within the functions.php file. Thanks, Jason.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, templates, forms" }
Multiple WordPress sites on one hosting I want to start building multiple `WordPress` blog sites(different niche), on one cloud hosting. Every blog will have his own unique domain, but all of them will be on the same hosting. Is this platform can affect the websites SEO ranking on `Google`? What are the alternatives if I don't want to have a specific host for each website?
You can have each site with a separate database (individual copies of WP), or one database with multiple sites (WP Multisite). If you go Multisite, each sub-site can have its own domain assigned to it. Multisite has common themeing and plugins, although you can have a different theme for each sub-site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "multisite, seo" }
How to disable automated E-Mail on PHP error/exception? Since WordPress 5.2 there is an automated E-Mail on PHP exceptions. In some smaller projects I just upload the files for new extensions while developing - whenever an error occurs then, the site admin is getting an email. This is usually one of my freelance customers and they unecessarily panic then. Therefore I would like to turn of this email notifications (without changing the admin email). Is there some kind of action/filter, config option (e.g. define) to disable this behaviour? Some true/false option would be the best? Then I can disable this just for the times I develop.
There was some discussion on it a few weeks ago you can find here: < According to that and looking through the core, you can accomplish that with one of two methods: define('RECOVERY_MODE_EMAIL', '[email protected]'); OR add_filter( 'recovery_mode_email', 'recovery_email_update', 10, 2 ); function recovery_email_update( $email, $url ) { $email['to'] = '[email protected]'; return $email; } Hope that helps!!
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "email, customization, fatal error, errors" }
Turn off redirect to canonical domain (or host website on any hostname) I want to have various development (say `dev.example.com`) and staging environments of a WordPress multisite (`example.com`). For this it would be great if WordPress wouldn't redirect to what it considers the canonical domain name. I'm running into trouble with this in my `wp-config.php`: define('DOMAIN_CURRENT_SITE', gethostname()); It redirects to `example.com` or gives me database errors. This is after `wp search-replace example.com dev.example.com`. Is it possible to turn off this redirection? If so, how?
In addition to modification of `wp-config` you might need to check `.htaccess` too, if there are any pointers to subfolder. After that, you might need to replace the values in DB tables `wp_site` and `wp_blogs`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, multisite, redirect" }
How to get post image root URL? By using below code, I got Image url like `" but I need root path of that image from `"var/www/html/....` " $FeaturedImage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'homepage-column1' ); Is there any way to get root path of the post thumbnail?
The `get_attached_file()` function returns the path to a file based on the attachment ID: $FeaturedImage = get_attached_file( get_post_thumbnail_id() ); Getting the path to a specific size is more complicated. WordPress stores the filename for resized versions of the images in as attachment metadata, that can be retrieved with `wp_get_attachment_metadata()`. Once you have the filename of the resized version, you just need to replace the original filename in the path with the resized version's filename: $image_id = get_post_thumbnail_id(); $image_meta = wp_get_attachment_metadata( $image_id ); $image_path = get_attached_file( $image_id ); if ( isset( $image_meta['sizes']['homepage-column1']['file'] ) ) { $image_path = str_replace( $image_meta['file'], $image_meta['sizes']['homepage-column1']['file'], $image_path ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, permalinks, paths" }
How do I make sure the gutenberg block CSS is not disrupted by generic styles? I am working with a pre-existing theme. On the site in question, the style sets rules for P tags. These rules are applied in preference to the class styles for P tags used in certain blocks. (With the result that covers, for example, look quite silly). How can I fix this?
Many of the default blocks add a class `wp-block-[name]` to the block's root element on save. You could use these to increase your class specificity. For your example of covers, `.wp-block-cover .has-huge-font-size` or `.wp-block-cover p.has-huge-font-size` depending on how much specificity you need.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, css" }
How do I extract just the post ID of the first item in whatever WP_Query returns? How do I extract just the post ID of the first item in whatever WP_Query returns? All the examples, answers, and documentation that I have seen dives off into doing things with loops. That's nice, but I just want the first ID. Nothing else. As the plugin will only ever generate a custom post type when there is none, the user should only have one. I need to get the ID of that post. How do I find a post ID? Is there an easier way to find out if the user has a post available? This is as far as I have gotten: $query = new WP_Query( array( 'author' => $current_user, 'post_type' => 'my_custom_post_type', // etc. ) ); $author_posts = new WP_Query( $query ); if( $author_posts->have_posts() ) { // They have at least one. Grovey, now what? } unset($author_posts);
If you only need the ID of a single post of a custom post type, to see if it exists, I'd suggest just using `get_posts()` with `fields` set to `ids`: $post_ids = get_posts( [ 'numberposts' => 1, 'author' => $current_user, 'post_type' => 'my_custom_post_type', 'fields' => 'ids', ] ); if ( isset( $post_ids[0] ) ) { $post_id = $post_ids[0]; } However, if you have a post type where every user gets 1 post, I'd suggest storing the ID of their post as user meta. Then you don't need to bother with this sort of query: $post_id = get_user_meta( $current_user, 'the_post_type', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp query" }
How to move my website to wordpress? I am in need to move a website from okaycms to wordpress, but I can't seem to find efficient way to do that. Can someone please tell me how to do that. I guess there is always option to rebuild everything in wordpress, but that wouldn't be so great of a choice. Thanks in advance.
There is no 'easy' way to 'move' or 'convert' a static site to WordPress. That's because WP is database-oriented, with content in the database. The themes/plugins/WP-engine take care of creating/building pages from the database content. So, if you have a static site (HTML or HTML/PHP), you are going to need to find a theme that makes the site look how you want it to, then manually create pages with your page content.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "migration" }
Suspicious google tag manager I'm trying to integrate some analytics into my site and whilst debugging why mine wasn't working, I found this line being put in the head of my document: `<script async="" src=" Now... It's weird because I've disabled any plugins I had doing google analytics. Additionally, when I look up that account ID, I find references to some company called KyinWebSEO that I've never heard of or done any kind of business with (that exact tag is on the source of their site). Two main questions here: * Did I get some kind of virus in one of the plugins I've downloaded? I have plugins related to analytics deactivated so unless one of the other plugins I have is doing that, not sure where it is coming form * Any advice on finding what is injecting it other than disabling all plugins? Google the following to see sitewiki links: `google tag manager "UA-75655200-4"`
When I disable `Content Visibility for Divi Builder` then the tag goes away. Seems suspicious... maybe they got hacked or maybe they are bad cookies. Will try to move this to the proper reporting channels. AoD Technologies LLC is the developer. **Edit: wanted to temper this with a third possibility of tracking the usage of their plugin** **Edit 2: the developer replied< I found a bug but the tracking code is theirs for tracking usage of the plugin. False alarm**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, html, google analytics, virus" }
Category pages redirecting to tab on Posts page grid I have a Posts page (< which has a tab/button for each Category. I would like my Category pages to open this tab instead of loading the default Category page. Is there a way to do this so that the Category title and meta description (via Yoast) which I will set will show in Google, but the tab of the Posts page load instead of just the Category page? I have Categories in two hierarchies; single level ones, and ones which are a sub-category below the main Category of "Country". Examples: < this should load < < this should load < Would a simple 301 or 302 redirect cause the Google entry title/meta/url to show the redirected page info and pass rank to the Posts/Locations page? I have tried to read around the subject and not sure. Any help would be appreciated :)
For now I have done this via category.php `/* Redirect Category to Post Grid tab */ <?php $cat = get_queried_object(); wp_redirect( site_url('/locations/').'?tx_category='.$cat->slug ); exit();`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, redirect, seo" }
Pagination for Category does not work I am trying to implement pagination for category items listing archive.php page. But this does not work. Below is the code that I am using. **Custom Query** : $cat = single_cat_title("", false); $cat_ID = get_cat_ID ($cat); $args = array( 'posts_per_page' => '2', 'post_type' => 'mathematics', 'cat' => $cat_ID, 'paged' => get_query_var('paged',1) ); $posts = new WP_Query($args); **Pagination code** : echo paginate_links(array( 'base' => '%_%', 'format' => '?paged=%#%', 'total' => $posts->max_num_pages, )); When the page is loaded, it displays the pagination links but when I click on next it gives 404 error. main page link: < when next is clicked : < I have already tried updating permalinks
I added below code in functions.php and it is working fine now. function custom_query( $query ){ if(is_category()){ $query->set( 'post_type', array( 'math' ) ); $query->set( 'posts_per_page', '2' ); } } add_action('pre_get_posts', 'custom_query'); Thank you all for your suggestions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, categories, pagination" }
Multisite - disallow list of blognames during subsite creation I need to prevent users from using particular blognames URL during site creation subdirectory multisite. More or less need to reserve multiple names for future use. Since there is a function that looks for existing names I imagine its possible. Appreciate the help.
Look in `Network Admin > Settings > Banned Names`. It is just one line so if you have very many, better type them up in notepad first. **The help text under it says:** > Users are not allowed to register these sites. Separate names by spaces. Just type in all the names you want to reserve for later. Banned Names should be about fifth or sixth down on the main settings page. Just above "Limited Email Registrations".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite" }
WordPress SVN UTF-8 issue I tried to commit the changes to the “Filenames to latin” plugin and got the SVN error. The error message: > Error: Commit failed (details follow): Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: [Error output could not be translated from the native locale to UTF-8.] Error: This error was generated by a custom hook script on the Subversion server. Error: Please contact your server administrator for help with resolving this issue. The latest code for the plugin I had issues with is in the GIT repo. Does anyone know how can I solve this issue? Thank you in advance.
Finally solved the issue. The problem was with the missing comma in the key-value array. It took me some time to found it. The error message was misleading: "Error output could not be translated from the native locale to UTF-8." WordPress SVN repository is doing code analyse before using pre-commit hook. I hope this will be useful for someone else too.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, svn, wordpress.org" }
How to run nested xargs commands? I am trying to loop through all sites on a multisite network, and for each site, delete all _subscriber_ users. I have tried this WP-CLI command: `wp site list --field=url | xargs -n 1 -I ^ wp user list --url=^ --role=subscriber --field=ID | xargs -n 2 -I % ^ wp user delete % --url=^ --reassign=4` I can't find a way to pass the `^` value to the second xargs command. Anyone?
xargs is unnecessary, something similar to this will do the job without any piping or `xargs`: sites=$(wp site list --field=url) for site in $sites do users=$(wp user list --url="$site" --role=subscriber) for user in $users do wp user delete $user --url="$site" --reassign=4 end end
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "multisite, wp cli" }
PHP error on local server install I'm trying to install an existing Wordpress website on my local server (Mamp). When I open the site in my browser it's all white. If I activate WP_DEBUG I've got this PHP error : _Warning: Unexpected character in input: '' (ASCII=15) state=0 in /Applications/MAMP/htdocs/www/gla/wp-includes/formatting.php on line 5318_ _Parse error: syntax error, unexpected 'T' (T_STRING), expecting ')' in /Applications/MAMP/htdocs/www/gla/wp-includes/formatting.php on line 5318_ I've been installing and using Wordpress many times but it's the first time I see so. Is it a problem of PHP version? Thanks for the help!
Problem resolved. Just needed a fresh install from Wordpress and it works like a charm.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, errors, installation" }
JSON-LD: creating an AggregateOffer from many shortcode I've created a shortcode which outputs product schema in JSON-LD format. 1 schortcode = 1 product = 1 product schema output 2 schortcode = 2 product = 2 product schema output The problem is that then I've realized that **all** the products in an article should create a single JSON-LD (see the image). 2 schortcode = 2 product = **1** product schema output This means that **the schema output should be outputted only by the last shortcode of this kind**. # The question Shortcodes output in wordpress are usually independent one from the others, they are "stateless" (the output depends only on the input parameters). But can I force them to a different behaviour? I've thought of using global variables inside the shortcode handler and output the aggregated JSON **only after the last shortcode has been called** ). **Is this a good solution?** ![enter image description here](
If you have full control over the system, it would be best to get all of the data by some other means. If you must concatenate the shortcodes, you can parse the content to get the shortcodes with get_shortcode_regex(). You can save all the matches, and their attributes, and remove them from the content. Then, you can either move them all to the end (or where ever you want them) or process them to get whatever data you need. On the other hand, you could just use microdata schema markup in your html instead of the JSON-LD format. For an example, see Example 1 here and click the microdata tab. Hope this helps
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "json" }
Is there possible way to modify custom post type? I use a third party plugin and plugin has created a custom post type called "creations". Bu there is no archive page, there is no single page, there is no admin menu page... But data are saving on database correctly. Is there a possible way to the active admin menu, archive page & single page? Other all behaviours of custom post type should be there like( Eg: if `exclude_from_search` is true, this shouldn't change)
You can change `register_post_type()` arguments before the new type is created. To do this, use the `register_post_type_args` filter. add_filter( 'register_post_type_args', 'se342540_change_post_type_args', 10, 2 ); function se342540_change_post_type_args( $args, $post_name ) { if ( $post_name != 'cpt_slug' ) return $args; $args['has_archive'] = true; // // other arguments return $args; }
stackexchange-wordpress
{ "answer_score": 11, "question_score": 2, "tags": "custom post types" }
When does save_post hook fire on post save/update In my plugin I want to update sitemap every time **page** or **post** is created/modified. To achieve this I use `save_post` hook: add_action( 'save_post', 'update_sitemap', 10, 3); Upon creating/saving/updating/deleting any **page** my callback method `update_sitemap` is fired but when i create/save/update/delete any **post** it doesn't seem to fire callback `update_sitemap` immediately. I tested this for custom post types and it works immediately like for pages. When I add 2 new regular posts, callback method is called once. Only after any further modification callback for 2nd post is fired. Is this expected behaviour for `save_post` hook?
`save_post` is fired at the end of `wp_insert_post()` which is the core function that's run whenever a post is inserted or updated (`wp_update_post()` calls it internally). This includes when the post is updated via the classic editor and the block editor (Gutenberg), as well whenever it's updated via the REST API. The only reason it wouldn't fire is if the post was being updated via SQL directly (via a plugin or otherwise), or when only post meta is updated via a function. So no, this is not the expected behaviour. If your function isn't firing then it could be interference from another theme or plugin, or it could be an issue with the function itself, but there's not enough information in the question to say either way.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, hooks, actions" }
custom word in custom permalink structure I can see that there is a custom structure option which has things like %year%, %postname% etc. but how can I put my own one there? I would like something like:
You can just type it in, no need to do anything special.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, permalinks" }
How to rewrite wordpress search to work on specific category I want my wordpress search to work on specific category within custom search, by default this actually work fine `example.com/categoryname/?s=keyword` but I want to make it work like this `example.com/categoryname/search/keyword/` I have the below code but it only work on the url `example.com/search/keyword` function wp_change_search_url() { if ( is_search() && ! empty( $_GET['s'] ) ) { wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) ); exit(); } } add_action( 'template_redirect', 'wp_change_search_url' ); but if i try `example.com/categoryname/search/keyword/` i get 404 error page Please I need help I want it to work within the category.
You can use `add_rewrite_rule()`: add_action( 'init', function(){ // Non-paged requests. E.g. example.com/categoryname/search/keyword/ add_rewrite_rule( '^categoryname/search/([^/]+)/?$', 'index.php?category=categoryname&s=$matches[1]', 'top' ); // For paged requests. E.g. example.com/categoryname/search/keyword/page/2/ add_rewrite_rule( '^categoryname/search/([^/]+)/page/(\d+)/?$', 'index.php?category=categoryname&s=$matches[1]&paged=$matches[2]', 'top' ); } ); **Be sure to flush the permalinks -- simply visit the Permalink Settings page.**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, categories, url rewriting, search, htaccess" }
How to target only one element if more elements share the same CSS class I am developing a website in wordpress using flatsome theme. I am facing a problem of images sizes. Actually all the thumbnails share the same class of CSS so when I change this class for one image all the other image sizes changes as well but I do not want that. I want to change the image thumbnail size of only one page and the rest of the image thumbnail sizes should be same although they are sharing same class. Please help in this regard.
I don't know how comfortable you are with development, but it is possible to do what I think you're asking. Option 1: Customize the theme templates to apply a different class to the first item. Requires some WordPress templating and php know-how. Option 2: Use css pseudo classes to target the first image with that class and give it different styles (something like `.yourclass:first-child{ border: 1px solid red; }` ). Requires some css/less/sass know-how (not sure how the theme is set up). Without seeing a sample page I can't tell you much more than that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css, images" }
Manual use of Walker_Category class Trying to create a menu with category terms as I read in the WP docs "Using Walker Manually": < $menu_items = get_categories(); $walk = new \Walker_Category(); print_r( $walk->walk( $menu_items, -1 ) ); I get this warning: Notice: Undefined index: use_desc_for_title in /srv/www/my-site.com/current/web/wp/wp-includes/class-walker-category.php on line 114 What is the right way to use Walker_category class?
the Walker_Category class you are using requires 3 params in walk() method, the third param will be use_desc_for_title value (this is due to how Walker_Category::start_el() method is written). In other words, to use the walk() method without generating a notice you should change your last line to `print_r( $walk->walk( $menu_items, -1, -1 ) );` The third param is a boolean: * "-1" (or false) - will remove the "title" attribute from the generated menu links * "1" ( or true) - will make the menu use category description for the title attribute.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "walker" }
why css doesnt work when i change my file of wordpress and sql to another computer? HIII, I've developed a website using "Elementor" and when I copy the file sql and the file wordpress installed on my disk , I moved these files on another computer and I put it the file and run sql on phpmy admin , the problem is when I run wordpress in my another computer, css doesn't work I mean my design appears in disorder , no positions and so on , can you help me ?
There are two parts to WP: the database (stores the posts/pages/settings) and the theme (stores the code that generates the page and styles it). The WP 'engine" uses both to generate the pages of your site. So, you have to copy the theme files to the new system. The link in the comment to your question tells you how to move a WP site to another server. And you may also need to move the plugins. Quick way: copy the wp-content/themes and wp-content/plugins folder to the new system. Plugins and themes store their settings/customizations in the database.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "css" }
Convert UL to dropdown list not working I am running a plugin called Divi Staff to show the staff on the website. I don't like how the specialisms are displayed and wanted to convert them to a dropdown list. I have tried to get this to work and followed a whole bunch of similar questions on here and Stackoverflow, tried to implement what they suggested and I am getting nowhere fast. I have created a Fiddle with the list working correctly, but when I implement it on the testing site, it refuses to work. Can someone help me figure out why this script isn't firing on the site? My testing server is < Any tips gratefully received.
@CharlieJustUs when you use Fiddle is automatically sets the $ variable for you. When your script tries to run on your site, that variable is not set, and it fails. Try this please. jQuery(document).ready(function($) { $(function() { $('ul.clearfix').each(function() { var $select = $('<select class="dropdown-toggle" />'); $(this).find('a').each(function() { var $option = $('<option />'); $option.attr('value', $(this).attr('href')).html($(this).html()); $select.append($option); }); $(this).replaceWith($select); }); }); // This will grab the value the select is being set to and redirect to the link $('select.dropdown-toggle').on('change', function(){ window.location.href = $( this ).val(); }); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, dropdown, list" }
Advanced Access Manager: RESTful endpoint to refresh token I'm using Advanced Access Manager (AAM) plugin, and have been trying to refresh a still valid JWT token using the `/aam/v1/refresh-jwt` RESTful endpoing, however I’m getting the following error: “rest_jwt_validation_failure”: [“Wrong number of segments”] The way I’m calling the endpoint is as follows: POST {{Base URL}}/wp-json/aam/v1/authenticate HEADERS Authentication: Bearer {{token}} Any though on what am I doing wrong?
At first glance it looks like you need to POST the token as a 'jwt' property in a JSON object, the same way you'd POST it to the validate endpoint: curl -X POST \ \ -H 'Content-Type: application/json' \ -H 'cache-control: no-cache' \ -d '{ "jwt": "0yJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NDM4OTExNjQsImV4cCI6MTU0Mzk3NzU2NCwidXNlcklkIjoxfQ.0wGIbcTDH5yWSsdStZFct_-auyOFJqf3NKQasTCs4QU" }' (based on < It doesn't look like this code reads the token from the Authorization header (and it's 'Authorization' not 'Authentication').
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api, authentication" }
Wordpress Multisite - Domain Mapping I recently installed a Wordpress Multisite and have set everything up. The one aspect that seems to have severally lacking information is how to map custom domains to each sub-site (i.e. jcs.examplesite.com to joescrabshack.com). I did see there is a plugin that 1000s of people used to do this, but it hasn't been supported now with further development in 3+ years and seems to unreliable moving forward. If anybody could share resources or tutorials on how to map sub-sites to custom domain names, I would greatly appreciate. Do I need to have a separate IP address for each to redirect via DNS? Thank you
As you might already know, this is done via the Edit button for the site. That contains all of the wp-options table rows for that sub-site. I always go through that entire list (it is long) and change all occurances of www.example.com/site1 to www.mydomain.com (the domain name for that subsite). Many plugins/themes store info in the wp-options table, so you have to check each entry in that subsite edit screen. Then bring up a few pages with the new domain name, and use the F12/Inspector and look at the network tab to ensure that all the requests are to the new domain name. Note that you may also need to fix any old urls for media entries. I'd use a search/replace plugin (I use the "Better Search and Replace" one) to easily change all www.example.com/site1 to www.newdomain.com . Backup your database first, of course.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, domain mapping" }
WordPress default theme CSS version problem and not loading WordPress default theme CSS version problem and not loading. After change the css code not apply the old css only load. we manually the style version the new code load. style.css?ver=5.1 to style.css?ver=5.2 How to change wordpress default theme style.css version in WordPress v 5.1
you can pass **time()** function in version parameter. so you dont have to change version to update a css code. function add_dynamic_version_css_scripts() { wp_enqueue_style( 'dynamic-style', get_template_directory_uri() . '/css/custom-style.css','style-css', time() ); } add_action( 'wp_enqueue_scripts', 'add_dynamic_version_css_scripts' ); let me know if this works for you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Changing a parent theme safely Im looking to edit a parent theme, and not just the functions and style files. I find that child themes don’t have the flexibility i want. How can i edit the parent theme without all the risk and the possibility of an update overriding all my changes?
In short: Not easily. First - just to say it: with child themes you can hook into functions, filter values, change templates or even exchange javascript files. This is usually enough. Edit based on the comments: If the theme is coded with best practices and checks for child theme directory you may just copy the template from the parent theme to the child theme and do your changes there. If child theme is not enough you have two possibilities: 1. Write down your changes manually or backup the files. Once you update the theme reproduce the steps. 2. Connect to your server with ssh. Install a git in the themes folder (or root if you need to). Check in your changes. Whenever you update the theme git merge the changes into the updated theme. Git is nothing for beginners. Make sure to backup your complete installation before experimenting with git. There's no other solution imho.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes" }
include multiple wp-blog-header.php from different blogs I want to include more than one wp-blog-header.php like the following. $config = array( array( "path" => "/path/to/blog/1/" ), array( "path" => "/path/to/blog/2/" ) ); foreach($config as $site){ include($site['path']."wp-blog-header.php"); echo get_site_url().' '.$site['path'].'<br>'; } I get echo out the first site_url 2 times. So i believe there wordpress doesn't connect to second blog. Is there a way to reset connection and everything which was included?
This will never work, you cannot include `wp-blog-header.php` multiple times from different installs. After you include the first blog header, all of the WP functions are now present in the global namespace, all the databse details set, plugins and theme loaded, etc. In order to reset things you would need an entirely new request, defeating the point. If your goal is to gather data from multiple instances there are better solutions: * A multisite installation, allowing `switch_to_blog()` to do this * Calling the REST API ( this can be done via JS or even a different program written in a different language ) * WP CLI commands But loading the code of multiple WP installations at the same time is not a solution, and will never work
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp blog header.php" }
How To Export User's Custom Fields in CSV or XLSX Hi Guys I have a BIG problem.. I'm using Eduma LMS and I have 2 type of customers... Some buy single video course, some others buy a membership (managed by Paid Membership Pro). When a user buy a product or a membership he/she it has to fill a required custom field (codice snep). That is the ID number of their network marketing account. Today the company asked me for a CSV files with all their names and the ID codice snep. I tried to export with some plugins but all of them ignore that custom field (ID) codice snep.. How can I export it too? The free plugins are not working :( They just export the basic fields of wp, ignoring custom fields. Thank u in advance! <3
Probably the easiest way to do this is to connect to the database using MySQL Workbench or similar, and extract the data using a SQL query e.g. select u.user_login, u.user_email, m1.meta_value as first_name, m2.meta_value as last_name, m3.meta_value as billing_codice_snep, m4.meta_value as codice_snep from wp_users u left join wp_usermeta m1 on m1.user_id = u.id and m1.meta_key = 'first_name' left join wp_usermeta m2 on m2.user_id = u.id and m2.meta_key = 'last_name' left join wp_usermeta m3 on m3.user_id = u.id and m3.meta_key = 'billing_codice_snep' left join wp_usermeta m4 on m4.user_id = u.id and m4.meta_key = 'codice_snep' and then you can use Workbench's export to save this as a CSV or XLSX. I'm guessing that you have called your user meta fields 'codice_snep' and 'billing_codice_snep'. If not, you'll have to change the last two lines of the query with the correct user meta keys.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, users, user meta, export, code" }
Check if emojis is disabled How can check if the emoji is disabled on the site or not? I have searched for an official function but I haven't found anything officially, We are creating a theme and will publish it soon and need to check if the customer has disabled the emojis by adding any function or by any another way.
To completely remove emojis this is the code: remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); So to check if any of those are active you could use `has_action()` like this: $emoji_script front = has_action( 'wp_head', 'print_emoji_detection_script' ); if( $emoji_script_front ) { // The emoji script is loaded on the front end } You could do different things for each of the actions. `has_action` does not care about priority, and this should work in the functions.php file since it runs later than all of those actions. More about has_action() on WordPress.org
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "emoji" }
Translate are not working for standard admin I'm developing a plugin which uses strings of the "default" textdomain, but several strings will not shown translated. My locale language is "de_DE" (german). I try to access the word "Count", which is available inside the "admin-de_DE.po" file. (To make sure, the loaded .mo file is actual, I compiled it with Poedit and Loco for debugging.) Other strings of that file will be shown translated, for example "[Pending]" as "[Ausstehend]", but not "Count" as "Anzahl". What is my mistake? add_action( 'admin_init', 'action_admin_init' ); function action_admin_init() { _e( 'Count' ); }
The only instance of `"Count"` I can see in the default domain's admin file has a context value of `"Number/count of items"`. So your code should be: add_action( 'admin_init', 'action_admin_init' ); function action_admin_init() { _ex( 'Count', 'Number/count of items' ); } Ref: _ex.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "actions, translation" }
Yoast taking over my Wordpress title tag I have this code: <h1><?php the_title(); ?></h1> That is meant to display the title of my blog post only. But because Yoast has a SEO title of something else, it is displaying that title on the page instead of `the_title()` eg: It should be: **This is a title** And not what Yoast is doing: **This is a title - my site name**
That's not what the SEO title does/is for. It appears that you've used the `wp_title()` function in your template by mistake. `wp_title()` is intended for use in the `<title>` tag in the `<head>` for setting the browser tab/document title. However, since WordPress 4.1 this has been superseded (but not officially _deprecated_ , yet) by `add_theme_support( 'title-tag' )`, so these days `wp_title()` really shouldn't be used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, title, seo, plugin wp seo yoast" }
Woocommerce: Variable Product - get variation name I want to get the Woocommerce variable product variation name. If, for example, I have a product that is available in different sizes: small, medium and large. Then I would like to print for example "large". I have almost got it to work. The problem is, I also get the product name at the same time like: "Product name - Large" Here is my code: `$product_variation = wc_get_product($variation['variation_id']);` `$product_variation->get_name()` Hope someone can help, thanks. :-)
> i have tested below code it works properly for variation name $variationId = 39; $variation = new WC_Product_Variation($variationId); $variationName = implode(" / ", $variation->get_variation_attributes()); echo $variationName;
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "woocommerce offtopic" }
Getting ACF Field in Page - From the Footer I'm trying to get ACF field that is part of an ACF block in a _Page_ I've created, say "Home Page". I'm trying to do this from the footer, but with no success. I've tried the following: I got the "post" id (despite it's a page) from the url in the admin console: `/wp-admin/post.php?post=7&action=edit`. My code may seem strange, it's a php blade template, I'm using Root.io Sage theme. {{ the_field('hours-o-mo', 7) }} and @php the_field('hours-o-mo', 7) @endphp I haven't "registered" any blocks, per se, I'm just using this plugin ( < ) to make template-only acf blocks, that automatically show in my Gutenberg page builder. I've also tried `get_field`. I'm not sure what I'm doing wrong, it should be simple to get an ACF field from a specific page, from the footer. Right?
I have the same issue, the acf get_field() function in footer returned null. Native WP function get_post_meta( get_the_ID(), 'option_key', true ) didn't work to. But when I've noticed that get_the_ID() function in footer returned the wrong value because I forgot to reset query after custom WP_Query. So, reset custom WP_Query (wp_reset_query()) or hard code the page ID.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, advanced custom fields, block editor, footer" }
Multisite setup creating custom table If I'm running a multi-site setup and I create a new table and add it to the WordPress database, will it be accessible to all sites or is it created to be site specific?
It's up to you. Normally when you create and query a table you use the `$wpdb->prefix` property as part of the table name. In a multisite install this prefix includes the current site ID. So if you use `dbDelta()` to create a table with the name `$wpdb->prefix . 'tablename'`, then -- assuming the default prefix of `wp_` -- this table will be created as `wp_2_tablename`, and `wp_3_tablename` etc. This ultimately means that each site in the network gets its own copy of the table, and you query the current site's table with `$wpdb->prefix . 'tablename'`. However, if you want a single table shared across the network, then you should create and query it with `$wpdb->base_prefix`, which will be the same on all sites (`wp_`, if you use the default). That way if you query it with `$wpdb->base_prefix . 'tablename'` the same table will be queried regardless of which site you're currently on.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "multisite, database" }
some profile informations like youtube link doesnt seem youtube icon which is represented in code with "fa fa-youtube" doesnt seem but i have youtube link on my profile settings. <?php $youtube_profile = get_the_author_meta( 'youtube_profile' ); if ( $youtube_profile && $youtube_profile != '' ) { echo '<span class="fa fa-youtube"><a href="'.esc_url($youtube_profile).'" ></a></span> '; }?>
Your reply to gregory24 isn't really explicit enough I'm afraid.. The reason you can display a FontAwesome icon without the if statement is only because this html `<span class="fa fa-youtube">...</span>` is loaded into the DOM of you page meanwhile your `$youtube_profile` variable is likely containing some value but your statement is wrong. this should work if `$youtube_profile` isn't empty: <?php $youtube_profile = get_the_author_meta( 'youtube_profile' ); if ( !empty($youtube_profile) || $youtube_profile != '' ) { echo '<span class="fa fa-youtube"><a href="'.esc_url($youtube_profile).'"></a</span> '; } ?> BUT.. you don't need to check twice for the same thing: `!empty($youtube_profile)` AND `$youtube_profile != ''` checks are the same the most simple way would be to simply check it like this, no need of checking if not FALSE just check if TRUE `if ( $youtube_profile ) { ... }`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
WordPress Contact 7 Form - Remove WordPress from the From Sections I want to remove the WordPress tag from the From section in when using the contact 7 plugin on WordPress. How can i do this? ![wordpress email from tag]( See below for the settings I use for the Contact 7 Plugin. ![enter image description here](
> change contact form setting as shown in below screens ![contact from setting](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin contact form 7" }
Trigger WP CRON from a date in a Custom Field? I have Custom Post Types which have a vanilla 'date-picker' for each post. My **Custom Posts** are actually events that are always in the future. I'd like to know if I can somehow trigger an alert when an event is over? I am using a Custom Post Type plugin called "Pods" which is awesome. Can anyone think of a way to make this happen? Ideally, I'd have an email sent to me or to trigger a Zapier API call, or similar... Any ideas on how to approach this? Thanks!
You will have to write a plugin which creates a daily cron job in the WordPress system. Here's an article describing how to write a cron plugin: < The function (callback) that you trigger in the cron plugin will use WP_QUERY to get a list of all your published custom post types after a certain date. e.g. $my_query = new WP_Query( array( 'post_type' => 'your-cpt-name-here', 'order' => 'ASC', 'posts_per_page' => 1, 'date_query' => array( array( 'after' => '1 day', ) ), ) ); Run through the results and send an email using `wp_mail()`. Alternatively, ask on fiver.com and get a developer to do it for you. It's pretty simple so won't cost very much at all.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp cron" }
Save URL into database I apologize in advance. I don't know even how to ask, what to ask, or what search for. Let say users can access my website from different URLs. > < > < > < How can I those "something" **save into DB**? Or another way to **store** those "something" variables. I want have overview of all attempts to access my website. What can I do? Any ideas?
1. If you have **simple data** , you can use add_option function to save the data to the wp_options database table. You can pass an array, it will be serialized automatically. Just pass the array to the function in the second argument, and specify the option name in the first argument (something like `all_visits`). And then you can retrieve it later using get_option function — just pass option name (in our case, `all_visits`) as the first argument. The value will be retrieved from the wp_options database table and unserialized automatically. 2. If you want to save **complex data** , take a look at the wpdb class — it contains a set of functions used to interact with a database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "urls" }
Add media attachment filter to custom wp.media frame Using `wp.media` function to create custom uploader popup I can't find argument to show attachment filters. if(typeof wp === 'undefined' || typeof wp.media === 'undefined') { return false; } var frame = wp.media({ title: 'Custom title', multiple: false }); My result: ![enter image description here]( Desired result: ![enter image description here]( Any help will be appreciated
You need to make use of `filterable` property. To do that, you can extend the library and use that as a custom state. // Create state var myCustomState = wp.media.controller.Library.extend({ defaults : _.defaults({ id: 'my-custom-state', title: 'Upload Image', allowLocalEdits: true, displaySettings: true, filterable: 'all', // This is the property you need. Accepts 'all', 'uploaded', or 'unattached'. displayUserSettings: true, multiple : false, }, wp.media.controller.Library.prototype.defaults ) }); //Setup media frame frame = wp.media({ button: { text: 'Select' }, state: 'my-custom-state', // set the custom state as default state states: [ new myCustomState() // add the state ] });
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "uploads, media library" }
How to disable primary main site header and logo in wordpress (Astra Theme) I have installed astra theme on my wordpress. How can i disable primary header ? I used following code in child theme but still didn't work. add_action( 'wp', 'astra_remove_header' ); function astra_remove_header() { remove_action( 'astra_masthead', 'astra_masthead_primary_template' ); } here is the screenshot, I want to delete upper logo: ![enter image description here](
With CSS you can disable this upper logo. display: none;
stackexchange-wordpress
{ "answer_score": -3, "question_score": 0, "tags": "themes, headers" }