INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
links format change "on clic" i have an issue on my site, and i don't know where it comes from. every link "change" ( comes bigger & change place ) when i click it. on menu link, they still are clicable, but with link in page, it doesnt work at all. exemple : < try to click on "aix en provence" to see what happen. thanks in advance for your help
It comes from the css definition in style.css around line 125. There is this rule: .hotel-detail-booknow a, a:active defined that gives the link its enormous size and blue colour. I would guess that it should be: .hotel-detail-booknow a, .hotel-detail-booknow a:active In your case, the rule is applied to all clicked links, not just the ones within a `.hotel-detail-booknow` element.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Enable right click on WordPress site I can not right click on my site and I don't know why! Is there any function to enable right click on the site?
This isn't something WordPress is doing but probably your theme. Perhaps it's an attempt to get people to not download your images or code, this is basically useless and doesn't prevent anything like that. Your theme might be using something similar to this... `document.addEventListener('contextmenu', event => event.preventDefault());` Try searching your theme files for `contextmenu` and see what you can find.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, javascript" }
Wordpress 404 on style.css but not on all pages I have noticed an issue when running a site audit on all of my websites using SEMrush I picked up the error: > issues with broken internal JavaScript and CSS files Examples > < < < All the sites are WordPress and some use a child theme and some do not, the example site does use a child theme. The style.css error is currently on 34 pages but not all. I did update the permissions after editing the files but nothing has worked, the current permissions are dir 755 and the stylesheet is 644. I am not sure what the issue is as it does not look like the permissions are the issue and if it was the child theme not loading the stylesheet then it would break across all the pages.
By looking at the source of `/about-us` the culprit seems to be the contact form in the footer, present in more pages of your website.Look here. Look at the Code module inside the divi builder, you'll see a `<link>` tag referring to a `style.css`: that's the code that's causing your 404. By the fact that the link tag is placed before a form I'm getting you wanted to style the form with some custom css? In that case just use the Divi theme options page and paste the css there, giving a proper id or class to the form.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, css" }
CSS to remove “comments count” icon from main page as the title suggests, can you help me on how to remove icons on the homepage that show the comment count of each article? I do not know CSS, and I do not know exactly what to change. I am using the following theme: < and I want to remove all the zeros in red. Thanks for any answers
you have to add "display:none;" to specific CSS class. add span.comments-link a { display: none; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, css, homepage, icon" }
Comment status shows 'closed' in db, but it shows 'open' when i echo it Here is database ss. And comment_status is `closed` ![enter image description here]( But when i print it, it shows `open` echo $post->comment_status; Also, in page settings, comments checkbox is unchecked. ![enter image description here]( So, i can't hide comments in pages. How can i fix it?
First thing I would do to debug such case is printing `$post->ID` just before printing the comment status. (And make sure if it is equal to 414 - the post you’re checking in DB) I’m almost certain that somewhere in your page you make another wp_query and modify the global `$post` variable. So when you’re printing the comment status it’s showing the real value but for different post. If you do such wp_query, then you'll have to remember to use `wp_reset_postdata` after that loop, so the global `$post` variable is restored to its original value.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, comments" }
How can I mass-update/save all WordPress posts and pages? I'm using a free SEO plugin for WordPress called Rank Math - < Overall, I like it a lot. But it has some problems for users with existing WP sites who are importing data from another plugin like Yoast. Rank Math is relying on individual posts and pages to be edited (not using WP's bulk quick edit feature, but opening each post and re-saving them one-by-one). This happens with author sitemaps for example. An author's page is only added to the sitemap if I manually open and re-save one of their posts and then re-save the sitemap settings. It doesn't find and add existing authors otherwise. Is there any way to simulate clicking the "update" button for all posts and pages without changing any actual content in a circumstance like this? Thanks.
Add to your functions.php file, but dont forget to take it off after use it !!!!! function update_all_posts() { $args = array( 'post_type' => 'post', 'numberposts' => -1 ); $all_posts = get_posts($args); foreach ($all_posts as $single_post){ $single_post->post_title = $single_post->post_title.''; wp_update_post( $single_post ); } } add_action( 'wp_loaded', 'update_all_posts' ); PS : BE SURE TO MAKE A DATABASE BACKUP BEFORE EXECUTE !!!
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "plugins" }
underscore template dynamically remove row Jquery I have this underscore template to add and delete row : <# jQuery( document ).ready( function() { jQuery( '.add-ingr' ).click( function() { jQuery( '#re-ingr .ingr' ).append( '<div><input type="text" name="ingr[]" value=""/><a href="#" class="remove_field" style="margin-left:10px;">Remove</a><div>'); }); jQuery( '.remove_field' ).on("click", function(e){ e.preventDefault(); jQuery(this).parent('div').remove(); }); }); #> the add row with remove link works , it generates the good html output: <div><input type="text" name="ingredients[]" value=""><a href="#" class="remove_field" style="margin-left:10px;">Remove</a><div></div> </div> But not the remove , nothing happen when i click on the remove hyperlink Any idea pls
This isn't WP related but Its not working because you are trying to add an event to a dynamically created element. Replace... jQuery( '.remove_field' ).on("click", function(e){ e.preventDefault(); jQuery(this).parent('div').remove(); }); With jQuery( 'body' ).on("click", '.remove_field', function(e){ e.preventDefault(); jQuery(this).parent('div').remove(); }); You can read more about your issue here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, templates, underscore" }
Personalize checkout text I would like to hide some of the text in the checkout page: billing details, Order notes (optional) and product/total row in "your order" section. I am able to remove the input fields, but I cant find a way to remove the text. Any help will be very appreciated.
If you look at the WooCommerce docs, you'll see that you can override template parts by having a replacement file in a `woocommerce` folder in your theme. A lot of the text you're talking about is hardcoded into `woocommerce > templates > checkout > review-order.php` Copy that file and modify as needed. Normally I would advocate for trying to use filters instead of duping the template file but I think there's going to be a few things you will have to do in that template file to accomplish what you need.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, woocommerce offtopic" }
WordPress eMails not working What should I be looking at? No emails from Wordpress (registration/login) even order emails are going to the customer. I am using Wordpress installed on NGINX VPS. I have lifted SMTP block off the server. All configuration in Wordpress / Woocommerce have been double checked and are correct. What else should I be looking at and testing? Thanks all.
Check if youre WP can send out any emails to begin with : < is a good one to try. If you have trouble sending emails with the standard setup you could also try < and use Gmail or a 3rd party SMTP service to send email. This plugin also has fairly advanced debugging options to work out whats wrong with your setup.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic, email" }
How to work with constraints on wordpress user metadata? For example, I want to add a custom user metadata field for projects he is assigned to. But this field must have a foreign key constraint to another table to make sure that the project it is referencing, is valid. Is there a way to handle this scenario with pure user metadata instead of creating an extra table to link the users with the projects?
You won’t be able to do this with meta. All user meta is stored in the `meta_value` column of `wp_usermeta`, so if you tried to set a constraint on that column you’d just prevent any other user meta from being set.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb" }
Localize plugin name Plugin name is a comment in WordPress. Since you can't write `php` code in the comments, is there a way to localize the plugin name and make it translatable?
Just add the full string of the plugin name into the plugin's text domain. WordPress looks this up automatically. Same with Description, PluginURI, Author and AuthorURI. See the internal function _get_plugin_data_markup_translate. The string extractor in Glotpress (and my own plugin Loco Translate) adds these header strings automatically to new POT files.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, localization, l10n" }
How can i add multiple variable to a !== query i'm trying to add a taxonomy filter on multiple CPT linked to this taxonomy. i'm good for 1 cpt at a time, but i'm definitly sure i can do much easyier with one function for all cpt. actually i have cpt "region", and i wish to add more like "region2", "region3", how can i do this ? my code : if ( 'region' !== $post_type ) // xxx endif;
You could for example use `in_array`. Like so, if ( ! in_array( $post_type, array( 'region', 'region2', 'region3' ) ) ) { // something }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
How can I make error messages in admin In my WP Plugin I have made an error handler. It works so far but I'd like to **not echo in admin_notices** , but have that nice little message box of wordpress if sth is going wrong: ![red box]( How can I do so?
All you need is the correct html markup, namely a paragraph `p` inside a container `div` with a certain class. Usable classes are `updated` green, `error` & `notice-error` red, `notice-warning` orange, `notice-info` blue. Exemplary usage: add_action( 'admin_notices', 'wpse330943_admin_notices' ); function wpse330943_admin_notices() { <div class="notice notice-error"> <p> //some text </p> </div> }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "errors, notifications" }
Customize categroy catalog page In "appearance > customize > woocommerce > product catalog" I choosed to display the categories for the shop display page. This wokrs fine and the categories are now shown on the main shop page. BUT, I want to change the html output like I was able to do it for the product loop in content-product.php tempalte. For example I changed the `<li>` to `<div>` in the content-product.php tempalte and I want to do the same with the category loop output. How can I do that. It seems so simple but I can't find it. The category loop output is still `<li class="product-category product"> ...` and can't find where to change this. THX
`content-product_cat.php` is the equivalent template for the category thumbnails. You want to copy `templates/content-product_cat.php` to your theme and modify it, the same way you presumably did for `content-product.php`. As with the product template, though, the only HTML in the template is the `<li>` tag. The rest is output through hooks.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, templates" }
W3 Cache redirects to front page when I press purge all caches I migrated my site to a new server. Everything seems to be fine, but the browser is redirected to the frontpage when I save configurations in either the "W3 Total Cache" plugin or in "Duplicate post" plugin. It does save the edits, but it´s annoing with the redirect. For example when I press purge all caches from W3 Cache, it is redirected to www.mysite.com/?w3tc_note=flush_all I can´t find a solution that solves it. I tried with: define('WP_HOME',' define('WP_SITEURL',' In my wp-config.php And with these google results: Redirecting to home-page when saving any edited code < I also looked at the wp_options in the DB. But seems allright. I tried to change the wp permanent link options in the admin settings too. The "Duplicate post" plugin was installed after the site migration.
Okay, I found a solution. To anyone in the future having this problem here's what i did: * I used the plugin "Duplicator" and made a package of the site. * Then i downloaded the installer and the archive. * I then deleted everything in the database and on the ftp. * Then I transfered the archive and installer file to the FTP and run the installer.php Now everything works again :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, migration, plugin w3 total cache" }
WP /wp-admin/admin-ajax.php produces 404 Our site has been working fine in the last week. Today, I can't add a new page to our menu. Clicking "Add to Menu" just produces a spinning icon that never disappears. If I look at the Chrome console, I see: > POST < 404 (Not Found) There are no restrictions on `/wp-admin` or `/wp-admin/admin-ajax.php` in `/.htaccess` or `/wp-admin/.htaccess`. I've Googled for this problem but most Q&A post relate to custom ajax calls. In our case we're not making custom ajax calls. Troubleshooting steps appreciated. PS - I am waiting on the web host to check if `mod_security` is causing this issue.
Your `/wp-admin/admin-ajax.php` might have been modified by another php file or plugin. Try downloading a copy of your wordpress version and overwrite `admin-ajax.php` with the original source file. If that doesn't work, try deactivating your plugins (or theme) one by one until you notice a difference.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "menus, ajax, wp admin" }
Change username before login How to change username before submitting in login form ? I have used `mobile number` as username when a user registers in site. also I have removed `0` from the beginning of the mobile number. Now in login form I need to remove `0` from the beginning of the mobile number, if user enter the mobile number with `0`. Is there a function to use as an action in `functions.php`
You can use `wp_authenticate` filter for that... This filter is fired before the user is authenticated. Params are passed by reference, so you can modify them. // user name is passed in by reference function wp_authenticate_by_email( &$username ) { // make sure that the condition below works for you if ( is_numeric( $username ) && '0' == substr( $username, 0, 1 ) ) { $username = substr( $username, 1 ); } } add_action( 'wp_authenticate', 'wp_remove_leading_zero_from_phone_number' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "filters, hooks, login, wp login form, username" }
How to redirect Wordpress home page to custom static HTML page I am facing an issue while I upload the custom HTML page into my Wordpress site. The page all alone working fine as I put it in separate folder or if I change its name to `index.php` . But then their arise a conflict between this custom page and the other WP theme pages .If I set this as a `index.php` page in theme or root WP .This page runs swiftly but other theme pages doesn’t work .Just show the same **index** page but with broken _css_ So all I want is not to broke my theme page as well to set custom html page it as my default **Home Page** How can I achieve this ? I am using divi them HTML page that I want to set as my Default Home page : < Rest of site : <
This code may help resolve the issue for this particular situation. Put this code in yor theme's `functions.php`. add_action('template_redirect', 'default_page'); function default_page(){ if(is_home() or is_front_page()){ exit( wp_redirect(" } } Replace ` to exact url of html file. I hope this helps.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "customization, page template, homepage" }
Newbie: Help with Vertical Spacing on Footer Widget I'm a WP newbie here and trying to get a sense of how everything's working around WP and CSS in particular. I'm currently designing my Footer layout that has 4 Widget areas arranged horizontally. The widgets I choose are the Posts Categories, Pages, Menus, and Woocommerce Product Categories, which give me a list of all menus and pages of my site. For some reason, the list from Woocommerce Product Categories is not vertically aligned with those from other widgets. The spacing seems off and each row looks slightly below where it should be positioned (please see attached image). Anybody could help point out where I go wrong? Thank you in advance! ![enter image description here](
You can change CSS as below. .widget.woocommerce.widget_product_categories ul li { display: block; margin: 0; padding: 0 0 3px; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "widgets, footer" }
WordPress visual editor internal link default https I have a WordPress site running on **`https`**. When I insert a link to another page using the Visual Editor it defaults to **`http`**. Can i change this somewhere? The closes thing i could find is this: In my case I would than need to replace **`http:`** to **`https:`** , but there has to be a better way.
You need to make sure your URL in _Settings > General_ uses ` That's where the URL comes from.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "visual editor, https" }
meta_post_meta return value 1 I want to return some post meta , but when i use the functions get_post_meta or get_post_custom the functions returns allways the values 1 for all the meta data, i tried several thinks but they returns the same value , i suspect that they returns boolean value. In the wp_postmeta table the meta_value is equal to 30. $build['time'] = get_post_meta($id, 'prep_time') ; //retun 1 $build['time'] = maybe_unserialize(get_post_meta($id, 'prep_time')) ; Any Idea what is wrong ?
`get_post_meta` takes 3 params, not two: get_post_meta( int $post_id, string $key = '', bool $single = false ) As you can see, the third param is false by default. It means, that if you don’t pass it, the function will return an array with all custom fields for that key. If you have only one meta field with key `prep_time`, you’ll get: Array( 0 => "30" ) On the other hand I’m pretty sure that’s not what you’re expecting, so you should pass `true` as the third param like so: $build['time'] = get_post_meta($id, 'prep_time', true);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "post meta" }
How to insert a comma to the child comment construction in function.php? I insert the name of parent comment's author in child comment if( $comment->comment_parent ) comment_author( $comment->comment_parent ); How to insert a comma to this construction in function.php? Example, if( $comment->comment_parent ) comment_author( $comment->comment_parent ) . ', '; do not work. Thanks
`comment_author` prints the author. It doesn’t return anything. So if you do this: if ( $comment->comment_parent ) comment_author( $comment->comment_parent ) . ', '; Then, what it really does is: * check if comment has parent and if so: * print its author * get the result of function `comment_author` (which is empty) and concatenate it with string containing ', ' * don’t do anything with that string And what you want is this: if ( $comment->comment_parent ) { comment_author( $comment->comment_parent ); echo ', '; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments" }
What does $temp do? I am new in WordPress Development. And I saw a sample which uses `$temp` to store the old `$wp_query` instance before instantiating a new `WP_Query`. I guess it is used to return original state when showing some posts other than the current `$wp_query` contains. But, I would like to be sure and learn other reasons. And I wonder what is the best way of this type of operations.
What any variables used in samples do depends entirely on that specific sample. If a sample assigns a query to a variable called `$temp`, then that's what `$temp` does. It doesn't mean anything else, it's just what's shown in the sample. Guide and tutorial writers can and will create and use any variables they want. You will need to read and understand the guide to understand what they're doing, or ask the author if you're unsure. If you need to, learn basic PHP first, as it will help a great deal. That being said, what you've described -- modifying `$wp_query` directly and then resetting it -- is something you should absolutely **_never_** do. Do not take further advice from any source that told you to do this. If you need to query posts for your own purposes, use `new WP_Query()` or `get_posts()`, and if you need to modify the main query, use the `pre_get_posts` filter. These are thoroughly documented across the web, and this site, if you need to know more.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Remove lines from RSS Feed I'm trying to remove the "The post xxx appeared first on xxx" line in my RSS feed using the the_content_feed hook. I've tested the regex function outside wordpress on the feed and it works. I'm using the my custom functions plugin to insert this into functions.php. It does not seem to be working and I'm at a loss. Any ideas? add_action('the_content_feed', 'remove_rss_links'); function remove_rss_links($content) { return preg_replace(".*appeared first on.*$", "", $content); } Here is part of my feed (slightly redacted): </p> <p>The post <a rel="nofollow" href=" appeared first on <a rel="nofollow" href=" Course Renovation</a>.</p> ]]></description>
Turns out I don't need to edit the RSS at all. The lines I'm looking to remove don't originate in WP at all. They come from a Yoast SEO feature, and it can be turned off in the options: SEO -> Search Appearance -> RSS
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks" }
Error establishing a database connection in wordpress I know this is self explanatory but why can't I connect to my database? I have a live website that I wanted to update by first doing development in my local computer. I exported the db to my local pc then imported it to phpmyadmin. When I try to access the site thru localhost/sitename, the error **_Error establishing a database connection_** keeps popping up. I have tried every tutorial and forums out there but still the error persists. I have checked the credentials from wp-config.php and it was the same(same db name, username, password). Is there other contents should I change property? Thanks in advance!
I had this issue some days ago with a multisite, loading a live dump to local development. After some debugging I noticed, that the error message wasn't right. The database was connected, but the path in the database to the sites was wrong. You can check table `<your-prefix>_site` and `<your-prefix>_blogs` if columns `domain` and `path` are correct. That solved my problem, as the error message told something else.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database" }
WooCommerce checkout page price break down table hook I want to add a new price break down line to the WooCommerce breakdown page. I've looked at using these hooks which supposedly should allow me to post to the table. woocommerce_review_order_after_cart_contents woocommerce_review_order_before_shipping woocommerce_review_order_before_cart_contents However, if I echo a string as a test it always appears above the checkout table price break down. Is there any way to add a new line item to the WooCommerce checkout table?
I think the hooks you're looking for are going to be either `woocommerce_review_order_after_shipping` or `woocommerce_review_order_before_order_total`. If you need to get in between where those two put you then you're looking at modifying a template, which isn't as future proof but is still a viable option when the hooks aren't enough.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, hooks" }
Displaying the right content on a page url I created a WordPress theme with one page design format which means I wrote all the code in the main index.php file. Now I need to make a different page with separate URL but for some reason it still displays the same content. Basically < is the main page and I need to have a new separate page for some content like < but for some reason whenever I create a new page it still shows the content from the main page. I don't know what's the WordPress way of doing things like that, should I just create a new directory with new files?
Because the naming convention is matter. You can create a new template for your different page and name it " **page.php** " and on the header portion give it a name: <?php /** * Template name: Different page tempate */ get_header(); ?> <div class="yourclass"> <!-- Your different template code should go here --> </div> <?php get_footer(); Once you are done then go to Pages>Add New & on the right sidebar you will see the new template name under "Template" dropdown. Select it as your new page template and publish. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
download link for uploaded images for wordpress Is there a way have a download link so that users can directly download uploaded images on a wordpress theme? I have seen this guide for something like this < but it is not wordpress specific and was not able to get it to work Is there something easier to implement? Currently i am able to link directly to the image and users are able to view the image in the browser but i want users to be able to download instead. thanks
You should just be able to use the HTML5 download attribute for that. So just make your links look like this: <a href="<?php echo wp_get_attachment_image_url($id); ?>" download>Download Image</a> where `$id` is the attachment ID
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }
Scroll Form with page scrolling and add form on slider On my Wordpress Theme i want to add a contact form which should be display on slider on right side so that when user scrolls the page the form must be scroll with the page. How to achieve this functionality? Is there any plugin available for that? Thanks
I believe you are trying to achieve "sticky" effect. This might help you do this. My Sticky Sidebar Plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms" }
How to edit the properties of a page programmatically? I know that I can programmatically create a new page via wp_insert_post setting 'post-type' to 'page.' How do I go about editing that page programmatically? (title, content, slug, etc.) Also, if I wanted to set the template for that page programmatically, how would I do that?
If you look at the documentation, you can insert title, content, slug, etc. using `wp_insert_post` then use `update_post_meta` to assign the template to that post. You can write like this $post_arr = array( 'post_title'=>'My title goes here', 'post_content'=>'This is my long content.', 'post_excerpt' => 'My Excerpt', 'post_status' => 'publish', ); $new_post_id = wp_insert_post($post_arr); Then set template like this. update_post_meta( $new_post_id, '_wp_page_template', 'template-file.php' ); To see more options for `wp_insert_post`, you can check it's documentation page.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "plugin development, pages" }
How to call a function or method that is Namespaced using another plugin I'm using an action from one plugin that needs to call a function from another plugin. That function is name spaced. Typically, I would use something like: add_action( 'hook_name', 'function_name' ); But the plugin's function is Namespaced and/or object-oriented, so I'm not sure how to reference the function in that case. I.e., how do I reference that specific function?
Here is generic code that worked for me. If anyone wants a real-life example, please let me know. This creates a function that calls the plugin's function assuming the namespace is "Custom" add_action( 'hook_name', 'my_custom_function_name' ); function my_custom_function_name() { // Check if "Custom Plugin" installed and activated if ( did_action( 'plugin/loaded' ) ) { // call the Plugin's function (clear_cache function example here) \Custom\Plugin::instance()->files_manager->clear_cache(); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters, hooks, actions" }
Uploading images to custom table I'm building my own WordPress plugin and I have a form where I put in some data. In addition, every entry has an image. Does anybody know how I can upload an image using the WordPress media selector?
< Maybe this can help you out. This function handles the upload of the file and adds the attachment as WordPress media record. Don't forget to include dependencies if you're uploading from frontend.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, images, uploads" }
View the number of entries recorded per day I want to display a chart of the number of articles published from a post_type within a specified time period (e.g. 30 days). Example : 1/1/2019 (1) 1/2/2019 (15) 1/3/2019 (0) 1/4/2019 (6) 1/5/2019 (0) 1/6/2019 (3) 1/7/2019 (7)
The easiest way is by using custom MySQL query with `WPDB` class. global $wpdb; $table = $wpdb->prefix . 'posts'; $sql = "SELECT DATE(post_date) AS date, COUNT(ID) AS count FROM {$table} WHERE post_type = 'my_post_type' AND post_status = 'publish' GROUP BY DATE(post_date)"; $rows = $wpdb->get_results($sql); Or if you want to prevent SQL injection, you can use prepared statement like this: global $wpdb; $sql = $wpdb->prepare( "SELECT DATE(post_date) AS date, COUNT(ID) AS count FROM %s WHERE post_type = %s AND post_status = 'publish' GROUP BY DATE(post_date)", array( $wpdb->prefix . 'posts', 'my_post_type' ) ); $rows = $wpdb->get_results($sql); Then you can iterate the `$rows` to show the data. foreach ($rows as $row) { echo $row->date . ' -- ' . $row->count; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, post type" }
Add a svg and show some text on the parts of that view when the user hover or click on that part in WordPress I am working in my WordPress website and I want to add a svg to my website and show some text on the parts of that view when the user hover or click on that part in WordPress. I have searched a lot and I am not getting any reference. Any help is much appreciated.
First, you have to create an SVG and using the tooltip js, you can show any content on the hover. Ex: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "svg" }
How to show metabox on page if it is using a template I was creating metaboxes for a special kind of pages. But i got stuck when showing metaboxes to the pages only who currently have the template 'Sky'. my template file name is sky-template.php and holds this code. /* Template Name: Sky */ And I am adding metaboxes using this function. add_action( 'add_meta_boxes', 'cd_meta_box_add' ); function cd_meta_box_add() { add_meta_box( 'sky_page_excerpt', 'SkyScraper Page Excerpt and Links', 'sky_page_excerpts', 'page', 'advanced', 'high' ); } I want to add the metaboxes only to pages with template sky. How will i do that. Thanks in advance
Use the page-specific meta box hook & accept the `$post` object that's passed to it - then you can check if it currently has a page template of `sky-template.php`. add_action( 'add_meta_boxes_page', function ( $post ) { if ( $post->_wp_page_template === 'sky-template.php' ) { add_meta_box( 'sky_page_excerpt', 'SkyScraper Page Excerpt and Links', 'sky_page_excerpts', 'page', 'advanced', 'high' ); } }); **Note:** this will only work on submit/refresh i.e. when you first (de)select the template when editing, you'll need to save changes and have the page reload for the meta box to take affect.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, pages, page template, child theme" }
How can I remove the ::after CSS selector which is automaticaly appended to the_content()? I have a CPT which displays meta values after the_content() in the front end, and this ::after selector is messing with my layout. The selector always appears right after the final element inside the_content().
It has nothing to do with `the_content()`. `::after` is a pseudo element that's added with CSS. Note that the `::after` element in the dev tools is only there to help development. It does not exist in the HTML source. So your theme's CSS must be adding it to whatever element is wrapping `the_content()` in your template. You can remove it by setting `content: none;` on the selector for it. For example, if the element that's wrapping your content is `<div class="entry-content">` then the CSS to remove it could be: .entry-content::after { content: none; } The rules of specificity still apply though, so whatever selector you use to remove it needs to be more specific than the one that added it. Also keep in mind that your theme likely does this for a reason. Most commonly elements like this are used to clear floats and prevent float-aligned content, like images, from breaking outside the parent element.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css" }
nginx.conf appeared in all WordPress installations on folder I run a couple of WordPress sites on a cloud server that I own. All of these sites run on the same Apache installation. Recently, I've found that in all of my WordPress webroot folders, an empty file called `nginx.conf` has appeared. Should I be concerned (about a security breach)? I don't think WordPress creates an `nginx.conf` file on the webroot when updating or being installed. But I can't find anything about this on Google.
Late to the party but if anyone finds this as a result of a search. this will have been auto-created when you installed Ithemes security. By default, it will create an Nginx.conf file in the site public_html folder you can change the location of this file in the settings. If it is on apache it shouldn't really do this though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "nginx, configuration" }
Show own shortcode data on each page I have shortcode [cities] and i need that when i import my pages to wordpress with text with this shortcode, there was own city by page id. Is it possible to do? I created a simple shortcode: add_shortcode ('cities', 'show_cities'); function show_cities(){ return "New York"; } Think that i need some array with cities and page id's but i don't understand how to do this. Can you give me a hint?
Best way to achieve the desired functionality is to use post_meta / custom field. add_shortcode ('cities', 'show_cities'); function show_cities(){ /* Create a custom field 'city' to save city name in page editor */ $city = get_post_meta( get_the_id(), 'city', true ); return $city; } Using an array can also do the work as under: add_shortcode ('cities', 'show_cities'); function show_cities(){ /* Create an array using Page_id as index, e.g. $cities [ 'page_id' ] = "City Name"; */ $cities [ 7 ] = "New York"; $cities [ 10 ] = "Alabama"; return $cities [ get_the_id() ]; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "pages, shortcode" }
How to link Gutenberg Gallery images To Media file automatically? Really I'm gonna be crazy :(, After searching for two months no one talking about this issue!! I'm stuck with that!! I mange a multi writers blog, and all our users uploading gallery images, and they didn't know the difference between (attachment, media file or none), I'm using Lightbox plugin and working only when images linked to file. ![enter image description here]( Before WordPress version 5+ I was linked all gallery images to "file" automatically by using this filter below. add_filter( 'shortcode_atts_gallery', function( $out ){ $out['link'] = 'file'; return $out; } ); But after WP 5+ how can I make it to work again? I really need to link all gallery images to "media file" automatically! I hope someone will help me or even giving me the right way. Thanks for your time.
Finally by luck i found the answer by @Tomas function gallery_template_to_posts() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/gallery', array( 'linkTo' => 'media', ) ), ); } add_action( 'init', 'gallery_template_to_posts' );
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "images, gallery, block editor" }
Wordpress add_rewrite_rule with 2 variables I need to create a rewrite rule that accepts 2 variables. I'm very new to this and am not sure If I'm even on the right track. If there is a better solution to what I'm trying to achieve, I'm open for suggestions. The url should look like this: localhost/states/id/state-slug Here is what I have: function prefix_movie_rewrite_rule() { add_rewrite_rule ( 'states/([A-Za-z0-9\-\_]+)', 'index.php? state_id=$matches[1]', 'top' ); add_rewrite_rule ( 'states/([A-Za-z0-9\-\_]+)/state([A-Za-z0-9\-\_]+)', 'index.php?state_id=$matches[1]&state=$matches[2]', 'top' ); } add_action( 'init', 'prefix_movie_rewrite_rule'); Using what I have, I'm able to get the first variable (state_id) but not the second (state).
After lots of pulling my hair out I figured out the problem. I needed to use the add_rewrite_tag() function to tell wordpress to allow my query vars. function prefix_movie_rewrite_rule() { add_rewrite_tag('%state_id%', '([A-Za-z0-9\-\_]+)'); add_rewrite_tag('%state%', '([A-Za-z0-9\-\_]+)'); add_rewrite_rule ( 'states/([A-Za-z0-9\-\_]+)/([A-Za-z0-9\-\_]+)', 'index.php? state_id=$matches[1]&state=$matches[2]', 'top' ); } add_action( 'init', 'prefix_movie_rewrite_rule');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rewrite rules, regex" }
How to hide specific Gutenberg blocks settings from users Is there any way to hide specific Gutenberg block settings from users? For example: "Crop Images", "Link To", and "Additional CSS Class" ![enter image description here](
As far as I know, as of right now there isn't a built-in way of removing unwanted inspector controls. You can read THIS POST, but the gist is that there are proposed solutions out there and devs are aware but they have bigger fish to fry atm, apparently. With that said, I guess you are left with 2 options. **1 - Copy the block in question and remake it without the options** This could be difficult, especially if you don't have any JS and/or block editor dev experience. **2 - Use some crazy CSS selector to add display:none to the options** This is probably easier but you still have to figure out the right CSS selector, which is difficult due to no IDs or classes on the option elements. Neither of these solutions are great but I think thats what we have, for now...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 10, "tags": "posts, block editor" }
Enqueing External JS on the remote server JS wp_register_script( 'custom-js', ' array( 'jquery' ), '1.1', true ); wp_enqueue_script( 'custom-js' ); Above is the **function** through which I am trying to enqueue an external javascript, but this is not working. where am I going wrong and how can I fix this? Full code here: if ( ! function_exists( 'function_script' ) ) { function function_script() { // Register the script like this for a theme: wp_register_script( 'custom-js', ' array( 'jquery' ), '1.1', true ); wp_enqueue_script( 'custom-js' ); wp_enqueue_style( 'styles', THEMEROOT . '/style.css' ); // wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css' ); // wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles')); } } add_action('wp_enqueue_scripts','function_script');
You use `$` in `custom.js` file and probably that's the reason, because jQuery is included in WordPress in **noConflict mode**. You can replace `$` with `jQuery` in `custom.js` or wrap the code as shown below: (function( $ ) { // --- your code --- $(document).ready(function() { //... }); })(jQuery); Or jQuery(document).ready(function($) { // code from file whithout line "$(document).ready(function(){" //... }); More about using jQuery in Wordpress you can read in "JavaScript Best Practices" on codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, wp enqueue script" }
Multisite installation steps? I activated the **Multisite** feature. I'd like to create a site in a _subdomain_. I have two questions: * do I have to create a subdomain on the server before creating a site within the multisite admin dashboard, or after? * if yes, do I have to install a WordPress installation in this subdomain before creating a site within the multisite admin dashboard, or after? I found this on StackExchange but it does not help me or I just don't understand. Subdomain multisite gives 404 on sub sites Thanks, François
Welcome into the community. To answer to your question: > do I have to create a subdomain on the server before creating a site within the multisite admin dashboard, or after? yes, you need to create subdomains on your server using cPanel or plesk. > if yes, do I have to install a WordPress installation in this subdomain before creating a site within the multisite admin dashboard, or after? You don't need to install wordpress for the subdomains. Be careful to point the root of every created subdomain to the root of your wordpress multisite installation. Multisite network will share the same wordpress installation, so you don't need to reinstall it each time you add a subdomain. I had a similar issue, you can read the topic here.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, subdomains" }
Get category's parent category while using get_the_category_list I use `get_the_category_list` to create a cat link in the header of my posts in the archive page, like so : $categories_list = get_the_category_list( esc_html__( ', ', 'mytheme' ) ); if ( $categories_list ) { echo '<div class="cat-links">'; get_template_part('images/inline', 'picto-actu.svg'); $categories_list . '</div>'; } I am trying to include the parent category to show it like so on the frontend : parent category > the category . But I'm probably not using the right method because whatever i try, i can't seem to get the parent, i can't even get the id of the child category from `$categories_list`, which would help me find the parent...
get_the_category_list() returns a formatted list of category names, which does not (as you discovered) include the IDs. get_the_category(), by contrast, returns an array of WP Term objects. A WP Term object looks like this: ["term_id"]=> //int ["name"]=> //string ["slug"]=> //string ["term_group"]=> //int ["term_taxonomy_id"]=> //int ["taxonomy"]=> //string ["description"]=> //string ["parent"]=> //int ["count"]=> // int ["filter"]= //string ["meta"]= array(0) {} //array Source: < As you can see, you can very easily pull out both the ID and the parent ID if present. Once you have the parent ID, you can fetch its name with get_cat_name( $cat_id );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Just display content between shortcode brackets I am rewriting a theme with shortcodes in the all the posts from the old theme. I searched all the files for the original shortcode function but get no results. So in a vanilla theme the page prints [shortcode dostuff]content here[/shortcode] I am trying to get the shortcode to output what is between the brackets, without editing every page on the site, so the page just shows: content here I can remove the shortcode with code like function remove-shortcode() { return '';} but then all the content inside the brackets gets removed as well and the page would be blank. I tried function `remove-shortcode() {return the_content();}` and the page crashes. What formula will return the content inside the shortcode brackets?
I have good news: the answer is simple. The WordPress Codex concerning Enclosing Shortcodes (like the one you posted here) shows that the shortcode callback has 2 arguments, `$atts` and `$content`. You want to work with `$content`: function wporg_shortcode($atts = [], $content = null) { // do something to $content // always return return $content; } add_shortcode('wporg', 'wporg_shortcode');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "shortcode" }
How to show more posts on an archive page? I'd like to show more posts on my custom archive page, but can't seem to figure out the right way to do it. Currently it displays 10, which is the number set in WP Settings and the number I'd like on my homepage. But on archives I'd like more. Right now the call for posts is super simple: <?php if ( have_posts() ) : ?> <?php // Start the loop. while ( have_posts() ) : the_post(); ?> This works nicely and works with my pagination. Is there a way to modify that to 100 posts? Is this where `pre_get_posts` would work? Thank you.
You can use `pre_get_posts` action to achieve that: add_action( 'pre_get_posts', function ($query) { if ( ! is_admin() && is_archive() && $query->is_main_query() ) { $query->set( 'posts_per_page', 100 ); } }); In the code above I use `is_archive()`, but you can use other conditional tags in there...
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "custom post types, actions, archives, pre get posts" }
how to add extra GET parameters to post to url with add_rewrite_rule? I have a blog that has a custom post type `article`, and the link is ` How can I use `add_rewrite_rule` to add a new link style to the same post ` in such a way that the part `readers` add a `GET` parameter `&showReaders=true` to the page `
You want to use the add_rewrite_endpoint since what you are concerned with is at the end of the URL. function wpseo331941_reader_endpoint() { add_rewrite_endpoint('readers', EP_PERMALINK | EP_PAGES); } add_action('init', 'wpseo331941_reader_endpoint', 10, 0); //When you want to check if the 'readers' is being used if ( false !== get_query_var('readers', false) ){ //.... } _Note that the false !== has to be present, because your query var "readers" will have an empty string as its value._
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, rewrite rules" }
WP_Query - multiple orderby with a rand field, doesn't work I have this query: $args = array( 'posts_per_page' => -1, 'post_type' => 'page', 'post_status' => 'publish', 'meta_query' => array( 'relation' => 'AND', 'tipo_pagina_clause' => array( 'key' => 'tipo_pagina', 'value' => 'prodotto', 'compare' => '=' ), 'tipo_prodotto_clause' => array( 'key' => 'tipo_prodotto', 'compare' => 'EXISTS', ), array( 'key' => 'brand', 'value' => get_the_id(), 'compare' => 'LIKE', ), ), 'orderby' => array( 'tipo_prodotto_clause' => 'ASC', 'post_title' => 'asc', ), ); // query $prodotti_brand = new WP_Query( $args ); Everything works fine, but what I want is 'post_title' = > 'rand', but the 'rand' seems not to work. What am I doing wrong?
The short answer is "you can't do that." Take a look at the Codex. When using orderby as an array the value can either be `ASC` or `DESC`. If you want to set `rand` you would do so as a key only. That being said, ordering by random will override any other orders, so you won't really get a benefit from ordering by `tipo_prodotto_clause` first. 'order' => 'ASC', 'orderby' => 'rand', Also make sure you take note of the required context for orderby rand: > Random order. You can also use 'RAND(x)' where 'x' is an integer seed value. **Note an "order" parameter needs to be present for "orderby"** **rand to work.** A piece of advice: ordering randomly is highly discouraged. The query does not perform well in mysql and has the potential to break caching on a site for every request or not appear to work if caching is less flexible. In fact, WP Engine has banned its usage by default. Be careful using this. It's usually better to find an alternative solution.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Custom category listings Maybe the question is stupid sorry - I'm a beginner when it comes to WordPress. But... What do I have to do to have a separate page listing for articles from a given category? Do I need a special _theme_ for this? Is the _OceanWP_ _theme_ allows this?
WordPress automatically creates an archive for each category. If you look in wp-admin, under Posts > Categories, you can click "view" to view a category and that will show you what it looks like and what the URL is. It is possible that a theme could override this functionality, but it's unlikely. Most themes have a template to display this type of automatically-created page - either a `category.php` specifically for categories, or an `archive.php` which covers not only categories but other archives.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp list pages" }
Product related to post by title How to insert to single post related woocommerce product with the same title? Best would be something like WC shortcode [add_to_cart id="XX"] but like this [add_to_cart title="XXXXXXXXX"]
default woocommerce shortcodes won't do that. you'll need to write something custom to get the product by title, grab the ID from there, and then call the add to cart shortcode using the ID. something like this: add_shortcode('add_to_cart_by_title', 'add_to_cart_by_title'); function add_to_cart_by_title ($atts) { if (!class_exists('WooCommerce')) { return ''; } $args = shortcode_atts(array( 'title' => '' ), $atts); $related_product = get_page_by_title($args['title'], OBJECT, 'product'); if ($related_product) { $product_id = $related_product->ID; return do_shortcode('[add_to_cart id="' . $product_id . '"]'); } return ''; } which you would then call like `[add_to_cart_by_title title="whatever"]` You could also remove the title attribute from the shortcode call and have it just get the title of the current post via `get_the_title()`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Is the root index.php file part of the Core? The contents of the `/index.php` is as follows: /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require( dirname( __FILE__ ) . '/wp-blog-header.php' ); If I make any changes in this file, then do a Wordpress Update, will the contents of this file be replaced? I've not been able to find any references online for this file, only Wordpress' `/wp-includes` and `/wp-admin` folders. I don't have access to the php.ini file and want to change the session cookie lifetime setting by adding the following code: $seconds = 31557600; //1 year ini_set('session.gc_maxlifetime', $seconds); ini_set('session.cookie_lifetime', $seconds); but don't want to add it to a file that potentially could be overridden in a couple of months time.
Yes, index.php is part of core and is liable to be overwritten. In fact, if you look at the process to manually update WordPress, step 7 is: > Upload all new loose files from the root directory of the new version to your existing WordPress root directory That may include index.php. You can put custom PHP code in a custom plugin or theme. If using a pre-built theme, first create a child theme and then put your code in that child theme's functions.php.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "updates, core" }
How to perform action when plugin/theme editor is used? I'm attempting to log lots of WP activities to create an audit trail. I'd like to disable the plugin and theme editors entirely, but it is not an option. Those functions appear to be very light on pluggability, best option I can see is to listen to the nonce validation and filter all of them. Does anyone know of an alternate, less brittle seeming method of running a little bit of code every time the plugin or theme editor saves a file?
The ajax action that runs on theme or plugin update is `edit-theme-plugin-file` so you should be able to hook into it by running code on the `wp_ajax_edit-theme-plugin-file` hook. add_action('wp_ajax_edit-theme-plugin-file', 'log_cowboy_coders'); function log_cowboy_coders() { $user = get_current_user_id(); if (!empty($__POST['theme'])) { // Log that someone is editing a theme } else if (!empty($__POST['plugin'])) { //log that someone is editing a plugin } if (!empty($__POST['file'])) { //log what file they are editing } } the entire updated contents of that file is also included in the POST data(`$__POST['newcontent']`) so if you run your function before default ajax action runs you could probably get the original content and save the difference between the two.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, editor" }
How to load page template according to the Searched Page I have a search form which uses RELEVANSSI plugin to perform search and display Search Results. On my Search Results page there is pagination and Search Filters(hyperlinks) which allows user to show 10, 20 or 30 records on screen. The Issue: In my website I have some internal pages which have different HEADER AND FOOTER and a Search BOX. By adding some checks If user performs search from these internal pages then it will load relevant and correct header and footer. But if I click on Pagination Filter or Search Filters (Show 10 Records, show 20 records) then it will load main website header and footer. I need a way to pass some variable which recognizes that from which page user come and according to that variable it will load header and footer. Thanks
Just use `wp_get_referer()`, and a few other functions to get the simple name of the referring page, e.g. if (basename(parse_url(wp_get_referer(), PHP_URL_PATH)) == 'my-search-page') { (Or you could use string searching or matching instead of `parse_url`and `basename`). (Also note `wp_get_referer` is deliberately misspelled. It originates in a misspelling in one of the web standards) _Addendum_ Might have to tweak this a bit to deal with the case where there's no referrer (e.g. a bookmark was used to get to the page).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "page template" }
Error inserting into custom table - Object of class wpdb could not be converted to string Getting the above error when trying to insert into custom table .I am unable to find out what is the cause of the error. The error comes at line 17. Any help is greatly appreicated. The code is below: <?php session_start(); require_once "wp-load.php"; require_once "dbconfig.php"; global $wpdb, $current_user; $current_user=wp_get_current_user(); $current_username = $current_user->user_login; $table_name='persons'; $first_name=$_POST['first_name']; $last_name= $_POST['last_name']; $email=$_POST['email']; $telephone=$_POST['telephone']; $wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->$table_name ( first_name, last_name, email,telephone,user_name) VALUES ( %s, %s, %s,%s,%s ) ", $first_name,$last_name,$email,$telephone,$current_username ) );
`$wpdb->$table_name` is not a valid table name. Use `$table_name` $wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->$table_name ( first_name, last_name, email,telephone,user_name) VALUES ( %s, %s, %s,%s,%s ) ", $first_name,$last_name,$email,$telephone,$current_username ) ); should be $wpdb->query( $wpdb->prepare( " INSERT INTO $table_name ( first_name, last_name, email,telephone,user_name) VALUES ( %s, %s, %s,%s,%s ) ", $first_name,$last_name,$email,$telephone,$current_username ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql" }
How to remove the WooCommerce Product->Category thumbnail from admin I've successfully removed the thumbnail from the Admin->Products add_filter( 'manage_edit-product_columns`, 'myRemoveProductColumns' ); function myRemoveProductColumns( $columns) { unset( $columns['thumb'] ); return $columns; } but can't seem to remove that same column from the Product->Categories. I tried: add_filter( 'manage_edit-product_cat_columns`, 'myRemoveProductCategoryColumns' ); function myRemoveProductCategoryColumns( $columns) { unset( $columns['thumb'] ); return $columns; } to no avail. Any thoughts? Have I missed something here? Thanks
Add lower priority to your action, then it should work. ( _At least it worked on my local WP sandbox_ ) add_filter( 'manage_edit-product_cat_columns', 'myRemoveProductCategoryColumns', 99 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
URL rewrite rule I have taxonomy `product_brand` and `product_cat` I have a link: /product_brand/brand_name/?attributes[product_cat]=product_cat_id How to convert to pretty url? `/product_brand/brand_name/product_cat_name` function custom_rewrite_rules() { add_rewrite_rule('^product_brand/(.*)/(.*)?', 'index.php?&attributes[product_cat]=$matches[1]', 'top'); } add_action('init', 'custom_rewrite_rules');
function custom_rewrite_rules() { add_rewrite_rule( '^product_brand/([^/]+)/page/([0-9]{1,})/?', 'index.php?product_brand=$matches[1]&page=$matches[2]', 'top' ); add_rewrite_rule( '^product_brand/([^/]+)/([^/]+)/page/([0-9]{1,})/?', 'index.php?product_brand=$matches[1]&product_cat=$matches[2]&page=$matches[3]', 'top' ); add_rewrite_rule('^product_brand/([^/]+)/([^/]+)?', 'index.php?product_brand=$matches[1]&product_cat=$matches[2]', 'top'); add_filter( 'query_vars', function( $vars ){ $vars[] = 'product_brand'; $vars[] = 'product_cat'; return $vars; } ); } add_action('init', 'custom_rewrite_rules'); and pagination add_action( 'pre_get_posts', function() { $page = get_query_var('page'); $query->set( 'paged', $page ); return $query; } );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, url rewriting" }
Redirect all users to dashboard unless custom post type I am trying to redirect any visitors to the dashboard unless they land on a specific custom post type (fruits). So the following URLs would all redirect to the dashboard... But the following would work as usual.. I have this so far... function redirect_to_backend() { if (!is_singular( 'fruits' )) { wp_redirect( admin_url(), 301 ); exit(); } } add_action( 'init', 'redirect_to_backend' ); But this is not working, anyone point me in the right direction?
The earliest hook that `is_singular()` will work on is `wp`. replace `init` with `wp` in your `add_action` call
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "redirect" }
add_image_size not working with after_switch_theme This is a weird one - this exact code works with `after_setup_theme` but not with `after_switch_theme`. Of course I would rather use `after_switch_theme` because `after_setup_theme` runs all the time - but it just will not work. add_action( 'after_setup_theme', 'wpdocs_theme_setup' ); function wpdocs_theme_setup() { add_theme_support( 'post-thumbnails' ); add_image_size( 'hero_image', 1920, 800, true); add_image_size( 'hero_image_md_lg', 991, 490, true); add_image_size( 'hero_image_md', 767, 460, true); add_image_size( 'hero_image_sm', 549, 575, true); ... } For reference: yes, I am switching the theme. Yes, I am regenerating the thumbnails. And in my `wpdocs_theme_setup` function I'm also adding custom roles that work regardless of which hook is being used. Any thoughts?
The reason adding custom roles works on `after_switch_theme` is because roles are saved in the database. In fact, because it saves to the database, it should _not_ run on `after_setup_theme`. `add_image_size()`, on the other hand, does not save anything to the database, so needs to run on every page load, and needs to be hooked on a hook that runs for every page load. So `after_setup_theme` is the correct hook to use.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, images" }
How to use acf field value to order category? I am trying to order category by acf field value. How can I achieve this using acf filed value? ![enter image description here]( $categories = get_categories('taxonomy=toc_category'); $sorted_cats = array(); foreach($categories as $cat){ $ordr = get_field('order', 'toc_category' . '_' . $cat->term_id); $sorted_cats[$ordr] = $cat; echo '<pre>'; print_r($cat); echo $cat->name; // it not returns expexted output } krsort($sorted_cats); return $sorted_cats;
> Use this code. $categories = get_terms('toc_category'); $sorted_cats = array(); foreach($categories as $cat){ $ordr = get_field('order', 'toc_category_'.$cat->term_id); $sorted_cats[$ordr] = $cat->name; } krsort($sorted_cats); return $sorted_cats;
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "categories, advanced custom fields" }
Copying and pasting emoji in a wordpress post There's this site that allows to copy and paste emoji's < If I copy and paste from there into my posts will it work everywhere? Is it something like Font awesome? To use them I have to include the font and css files. How does it work in case of emojis? Where are they "defined"?
Emoji are just letters. They're defined by the user's operating system. The same way the alphabet is. You don't need to do anything special. If you did, then that website would be pointless. The only thing you need to consider is older operating systems that don't support Emoji, but WordPress itself loads a script that enables Emoji for those operating systems.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, images, css" }
how do links move when I move my site? Very new at this, so maybe I am missing some fundamental understanding of how WordPress handles links. But, I'm building a website on my local machine, expecting to upload it to a provider when I'm done. Right now everything resolves to localhost. Here's the problem. One of the pages has a list of links to other pages on the site. WordPress created those links as < Shouldn't there be a placeholder for the domain name there instead of a hardcoded localhost? Or better yet, shouldn't they be relative links instead of fully qualified URLs? Or will WordPress automatically fix those links when I move my site to a provider?
Some links (those built in code) will automatically change to your new domain. Others (those in post content) you will want to swap out using something like better search replace to swap out localhost for your new domain.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }
Add to previous posts under post **Goal** : After each post (that contains under a certain amount of words), display the two posts that were published before it in that category/tab. I found **this** on stack, where they do something similar, but they're displaying the 2 most recent posts. I want to display the 2 that were published before the currently-read article, though. Is there a way to modify this code?
Try to add `date_query` to the $qry in the solution mentioned here. $qry = new WP_Query( array( 'cat' => $current_post_categories[0], 'posts_per_page' => 2, 'post__not_in' => array( $current_post_id ), 'date_query' => array( array( 'before' => $post->post_date, ), ), ));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, date query" }
Looking for Image Slider that is based on default WP Media Library For my WordPress site, I want to have a new solution for my image sliders. What I expect in the frontend is a slider like I have here: < But I am not happy with my current situation because my images are divided into the default WP media library and the library of the NextGen plugin. Furthermore, the plugin requires too many resources. In short: I need a plugin that allows me to select images from the WP media library and place it as a slideshow/carousel in an article. In the best case, this is possible within the Gutenberg editor. Has anyone an idea how I can solve it? Thanks in advance! I am searching for plugins for the last hours without success so far.
Try the Gutenberg Block Gallery plugin: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, images, media library, block editor" }
Woocommerce: limit user to see only the products he created I have this code where the authors can see only own posts. I need the authors to see only the products they have created on woocommerce. I know the woocommerce products have no authors by default, but I can add this with a plugin. Whats I want to do is to change this snippet to limit the lists of products in the custom post type of woocommerce. Someone know the best way to do that? Thanks! function posts_for_current_author($query) { global $pagenow; if( 'edit.php' != $pagenow || !$query->is_admin ) return $query; if( !current_user_can( 'manage_options' ) ) { global $user_ID; $query->set('author', $user_ID ); } return $query; } add_filter('pre_get_posts', 'posts_for_current_author');
I believe changing the following conditional: if( !current_user_can( 'manage_options' ) ) to this one: if( !current_user_can( 'manage_options' ) && 'product' === $query->get( 'post_type' ) ) would do it. Brief explanation: I added a second condition which checks if the query is for WooCommerce products where the post type is `product`. ## UPDATE If you want to make certain that the code runs only on the products page (WooCommerce -> Products), then you can (remove the `global $pagenow;` and) change this: if( 'edit.php' != $pagenow || !$query->is_admin ) to this one: if( !$query->is_admin || 'edit-product' !== get_current_screen()->id ) And instead of relying on the global `$user_ID`, you should probably use `get_current_user_id()`: `$query->set( 'author', get_current_user_id() );` :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, woocommerce offtopic, author" }
How replace theme styles? I have some theme. I am running shortcode for my plugin in some page like this: `[my_plugin_code atr="1"]` But all styles is import from CSS theme. I want my custom CSS. How to do it without interfering with template styles?
WordPress dashboard -> Appeareance menu -> Customizer allows you to add custom CSS without editing any files.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, themes, css" }
correctness of URL if I call shortcode in some page, then this address is correct? Wordpress automatically add "/". As far as I remember, it has always been: All work's but is this correct?
See the accepted answer to this question: < tl;dr Either way is correct, but consistency in the result is the key to best SEO practices, because with/without is a different URL. If you don't want the trailing slash (or you do), you can change it in your Admin, Permalinks screen.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, filters, urls" }
Use Repository Pattern in WP theme In my template files I have a lot of WP_Query to get posts of an author or from a specif category ecc... I'm thinking to use Repository Patter in order to have cleaner code and a layer between database and theme. This PostRepository class will have some methods like: \- getByID \- getByAuthor \- getByCategory Could be a good idea? Have somebody use somethink like this?
Yes absolutely, It would be great to abstract away your queries at a single place. You might also use caching in your repository.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query, oop, repository" }
How to search by metadata using REST API I have a custom post type like this: register_post_type('horario_busao', [ 'labels' => [ 'name' => 'Horário Busões', 'singular_name' => 'Horário Busão' ], 'public' => true, 'has_archive' => true, 'show_in_rest' => true ]); And it contains a metadata `city`, which I update it this way: return update_post_meta($postId, 'city', $city); So I'm fetching it by the endpoint `/wp-json/wp/v2/horario_busao`. As I see in the documentation, it only contain the query param `search`. How can I search it by metadata?
> How can I search it by metadata? _As far as I know, there's no standard/built-in way of doing that (for the time being). But with **custom coding** , you can make it possible:_ You can append a `city` to the query string: /wp-json/wp/v2/horario_busao?city=London And then use the `rest_{$this->post_type}_query` filter to set the meta key/value pair which would be passed to `WP_Query`. Here's an example: add_filter( 'rest_horario_busao_query', function( $args, $request ){ if ( $city = $request->get_param( 'city' ) ) { $args['meta_key'] = 'city'; $args['meta_value'] = $city; } return $args; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "metabox, rest api" }
Display $pagenow error notice on all admin pages I need to show my client error message on all admin pages. I have the following code, that adds a custom notice only on the admin dashboard page: add_action('admin_bar_menu', 'custom_toolbar_link2', 999); function general_admin_notice(){ global $pagenow; if ( $pagenow == 'index.php' ) { echo '<div class="notice notice-error"> <h3>My custom text</h3> </div>'; } } Is there any way to display this notice on all admin pages?
function my_admin_notice() { /* * The class of admin notice should be "notice" plus any one of * -"notice-error", * -"notice-warning", * -"notice-success" * -"notice-info". * Optionally use "is-dismissible" to apply a closing icon. */ echo '<div class="notice notice-info"><p>Custom notice text</p></div>'; } add_action( 'admin_notices', 'my_admin_notice' ); The only thing is, these notices does not show up on New Post, Edit Post and similar where Gutenberg reins. There must be the solution, but I can't find it right now.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp admin, hooks, admin bar" }
How to change response of admin-ajax request? Request generated by fullcalendar js, which implemented by plugin WP FullCalendar (github link for code) Request url: ` Plugin contain following code: `add_action('wp_ajax_nopriv_WP_FullCalendar', array('WP_FullCalendar','ajax') );` So i figured out that request should be handled by `WP_FullCalendar::ajax` method, but then i edit it directly nothing changes. I tried log some debug info into file, but seem like this method not running at all (init method still running). All caches are turned off. Author of plugin not responding. I want to apply `the_title` filter on titles of events, so it will be translated by WPMultilang plugin. What should i do to achieve this?
`WP_Fullcalendar::ajax` overrided by `WP_EventsManager` plugin in file `em-wpfc.php`, if wpfc and wpem used in combination. Here is my final code in `functions.php` /** * Translate WP_Fullcalendar titles for events * @param $items * @return array */ function wp_fc_translate($items) { foreach ($items as &$item) { $item['title'] = apply_filters('the_title', $item['title']); } return $items; } add_action('wpfc_events', 'wp_fc_translate');
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "plugins, filters, ajax" }
Get only children category name On a single post, I display the post's categories like this: $categories = get_the_category($id); My category hierarchy is: `cat1` parent of `cat2`, parent of `cat3`, etc. I would like to display only children categories (from `cat2` to `catN`). I tried to use `get_category_by_slug($id,'cat1')` with no results...
For this specific question, Try this $categories = get_the_category($id); foreach($categories as $category){ if($category->parent != 0){ // Display it here echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>'; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
get_search_query() not working with search queries with ampersand in it I am using plain simple code to make a search page $argscontactdirectory = array( "s" => get_search_query(), 'post_type' => array( 'expertarticle'), 'orderby' => 'title', 'order' => 'ASC', ); Above is the code I am using, however, when the search query contains the "&" character it simply doesn't work, if the search query is `M&M` the URL bar will show `?s=M&amp;M` I tried many things, include `urlencode()`, but it doesn't work either. A live example can be seen here: Any help is appreciated.
`get_search_query` escapes the data for outputting to HTML. Can you try the following instead: $argscontactdirectory = array( 's' => sanitize_text_field( get_search_query( false ) ), 'post_type' => array( 'expertarticle'), 'orderby' => 'title', 'order' => 'ASC', );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Is it necessary to network enable both the parent and child theme for multisite installations? for multisite networks, is it necessary for me to network enable both the parent and child theme if I'm only using the child theme in my sites? Does it cause my site to slow down if I have more themes network-enabled? When a parent theme gets updated, do I have to perform any action on the child theme? Thank you!
A little late to the party, came across this question looking for the same answer myself - to answer your first question, I've done a brief test locally and it seems that the parent theme _can_ be network disabled. I have three sites running, with three child themes network enabled where the parent theme is not and they're all still standing.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, themes, child theme, parent theme" }
Custom post type show on both Home and Date Archive Found below snippet to pull posts from a custom post type 'pictures' into the home page and date archive page.. Added to `functions.php` this works for home page: function add_custom_post_type_to_query( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'post_type', array('post', 'pictures') ); } } add_action( 'pre_get_posts', 'add_custom_post_type_to_query' ); But this works for neither: function add_custom_post_type_to_query( $query ) { if ( $query->is_home() && $query->is_date() && $query->is_main_query() ) { $query->set( 'post_type', array('post', 'pictures') ); } } add_action( 'pre_get_posts', 'add_custom_post_type_to_query' ); Would also like to add in `!is_admin()` to keep the admin screens clear, and not sure how to go about that. thanks,
In your code `( $query->is_home() && $query->is_date() && $query->is_main_query() )` always returns `false` because `$query->is_home()` and `$query->is_date()` cannot be `true` on same page. Try this, function add_custom_post_type_to_query( $query ) { if ( ! is_admin() && $query->is_main_query() ) { if ( $query->is_date() || $query->is_home() ) { $query->set( 'post_type', array('post', 'pictures') ); } } } add_action( 'pre_get_posts', 'add_custom_post_type_to_query' ); I hope this helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, pre get posts" }
wrapping 'rest_api_init' in 'is_admin()' function i'm create custom admin page via `add_menu_page`, let's imagine that my custom page has url > wp-admin/admin.php?page=settings_page then i'm checki `is_admin()` function via `var_dump` on my `settings_page` and it returns `true` \- that's OK, but when i'm wrap `rest_api_init` action in `if is_admin()` statement, like this: if(is_admin()){ add_action('rest_api_init', [$this, 'myRegisterRoutesFunction']); } it returns me `404 - No route was found matching the URL and request method`. But if i remove `if` statement, it works fine. Can't understand why, thanks for the advices!
Essentially, you shouldn't wrap your REST route declarations inside is_admin() since Wordpress will not load them (see @DarkNueron comment). What you can do is pass a 'permission_callback' function to the `register_rest_route` function. If the function returns true, the request is allowed to continue; if false, an error is returned. So you could do: register_rest_route('your-namespace/v1', '/options/', [ 'methods' => 'PATCH', 'callback' => [__CLASS__, 'update_option'], 'permission_callback' => function () { return current_user_can('manage_options'); } ]);
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "wp admin, rest api, admin menu" }
problem with my my theme "search.php" **when I try to search something it shows me that I have an error in line 9** > The code on line 9 on my page "search.php" of my theme <div class="p-title"><h2 style="background-color: #1AB3EE;">Searching for <?php $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<strong class="terms_search">'); echo $key; _e('</strong>'); _e(' - About '); echo $count . ' '; _e('results'); wp_reset_query(); ?></h2></div> > The error message ![enter image description here](
Using `&new` in object creation is deprecated in PHP 7+ because objects are passed by be reference by default. Remove the `&`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "themes" }
Can I clone plugin folder to another directory so that I don't have to reinstall them? I built a multisite network and it got broken due to a developer who now claimed that it can't be fixed: The subsites' dashboards can no longer be accessed and the pages give the error message "page cannot be found". Since I haven't worked on it for very long, I am fine with "abandoning" the site and restarting. Right now, I would like to move all my installed plugins (paid and non-paid ones) from this site to a new single site installation (not multisite). Is this possible? How do I do it? Thank you
Sure you can copy the folders and their contents over. A few caveats: * they will start as deactivated * their database records will not be copied over automatically. Some paid plugins store the license key in the database. * there may be compatibility issues if your new site is on a different version of WordPress, PHP, etc., Especially since you said the site is a couple of years old and you haven't touched it in a while Personally I would rather try to fix what you have and then go from there. "Can't be fixed" is subjective. If you reinstall the core WordPress files, network deactivate the plugins, and network-wide deactivate non-core themes, you still can't get into the subsites' dashboards?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, migration" }
Get arguments from URL I have example link how get `user_id` and `reg` values form `$_GET`? if i write: echo ($_GET['user_id']); Then get this: 6?reg=true And i try : echo get_query_var( 'user_id'); But not work. What i do wrong?
Your URL querystring is malformed. `?` good before the first variable. `&` goes before any others. Your url should be `
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, urls, links" }
Develop Admin Panel Page How to develop a Admin Panel Page in WordPress DashBoard like All Posts page ? ![enter image description here](
**WP_List_Table** class is used to generate the List Tables that populate WordPress' various admin screens. It has an advantage over previous implementations in that it can be dynamically altered with AJAX and may be hooked in future WordPress releases. **If you want to use this class pay attention to this warning by Wordpress.** > **This class's access is marked as private**. That means it is not intended for use by plugin and theme developers as it is subject to change without warning in any future WordPress release. **If you would still like to make use of the class, you should make a copy to use and distribute with your own project, or else use it at your own risk**. Here are **Tutorial 1 and Tutorial 2**, that may help you start.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, wp admin, admin menu, dashboard" }
Auto delete post if certain custom field data is empty This question can be stupid but I really need a solution for it.. I am generating classified post using cron job. I have some custom filed as well with the cron job like 'source_link'. Sometimes that custom filed data may not be set for error or any kind of situation. So I want that post with empty data for custom field 'source_link' to be deleted automatically. Is this possible anyway ? Here the code how I do I create post and set custom field data kses_remove_filters(); $new_id = wp_insert_post($post_arr, true); kses_init_filters(); if (is_wp_error($new_id)) { $this->write_log("error occurred in wordpress post entry: " . $new_id->get_error_message() . " " . $new_id->get_error_code(), true); return; } update_post_meta($new_id, 'source_link', $url);
kses_remove_filters(); $new_id = wp_insert_post($post_arr, true); kses_init_filters(); if (is_wp_error($new_id)) { $this->write_log("error occurred in wordpress post entry: " . $new_id->get_error_message() . " " . $new_id->get_error_code(), true); return; } if($url) update_post_meta($new_id, 'source_link', $url); else { // wp_delete_post($new_id); // Move post to trash $deleted = wp_delete_post($new_id, true); // Permanently delete post if(! $deleted ){ $this->write_log("error deleting post entry.", true); return; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, custom field" }
Filter to wp_list_authors I am using wp_list_authors, to, how function name says, make a list of authors, but i want to show only "Authors". Now in my site, any account who publish a text ("Admin", "Editor") show his name in my list of authors, but i want ONLY users who are Authors. How can i make this happen? My code now <?php $args = array( 'orderby' => 'name', 'order' => 'ASC', 'number' => 6, 'optioncount' => true, 'exclude_admin' => true, 'show_fullname' => false, 'hide_empty' => true, 'echo' => true, 'style' => 'list', 'html' => true); ?>
wp_list_authors(), displays a list of the sites's authors (users), and **if the user has authored any posts,** the author name is displayed as a link to their posts. Use $authors = get_users( [ 'role__in' => [ 'auther'] ], // add other parameters ); Then loop through $authors to create your own list. foreach ( $authors as $author ) { // your list goes here } I hope this helps to start.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, filters, users, list authors" }
Wordpress redirect all 404 pages to the Homepage I want to redirect all 404 error pages on my WordPress site to the homepage, or to a specific page. Any advice?
> **_Note: I have read somewhere that redirecting all 404 to Homepage is_** **_not a good approach for SEO purposes_** * * * Simplest way to redirect all 404 to homepage in wordpress. if( !function_exists('redirect_404_to_homepage') ){ add_action( 'template_redirect', 'redirect_404_to_homepage' ); function redirect_404_to_homepage(){ if(is_404()): wp_safe_redirect( home_url('/') ); exit; endif; } }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "plugins, htaccess, code" }
Site title not showing. Please help me Please help me, My WordPress site's title not showing. It's just displaying the domain like, www.example.com. site: < Please check my site code and suggest how to display the normal title tag.
> Use this code in Header.php file. <title><?php wp_title(' - ', true, 'right'); ?></title> But as per page view source code.you have forgot to close tag above tag in header. so please close tag. see this screenshot **Should code like this:** <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); </script> <title><?php wp_title(' - ', true, 'right'); ?></title>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, css, errors, title" }
how to post default thumbnail if post not created yet I want to show a default thumbnail if a custom post not created yet. Here is my loop: <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <?php if ( has_post_thumbnail( ) ) { the_post_thumbnail( 'full', array( 'class' => 'mySlides' ) ); } else { echo '<img src="dummy-image-1-1.jpg" class="mySlides" height="350px"/>'; } ?> <?php endwhile; wp_reset_postdata(); ?> If I created a post but not posted a thumbnail then show default thumbnail. But If I didn't create a post yet I want to show a default thumbnail. How to fix it?
> **Create "images" folder in current active theme the put "dummy-image-1-1.jpg" in that folder.** <?php if ($the_query->have_posts() ) : while ($the_query->have_posts()) : $the_query->the_post(); if ( has_post_thumbnail( ) ) { the_post_thumbnail( 'full', array( 'class' => 'mySlides' ) ); } else { ?> <img src="<?php echo get_template_directory_uri().'/images/dummy-image-1-1.jpg'; ?>" class="mySlides" height="350px"/> <?php } endwhile; else: ?> <img src="<?php echo get_template_directory_uri().'/images/dummy-image-1-1.jpg'; ?>" class="mySlides" height="350px"/> <?php endif; wp_reset_postdata(); ?> > Use path according to the theme(parent or child) * `get_stylesheet_directory_uri()`: url path to current Theme directory * `get_template_directory_uri()`: url path to parent Theme directory
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, post thumbnails, thumbnails" }
Child CSS not working for some of the classes - twenty seventeen theme Parent and child CSS both classes loading as per CSS rules, but parent is functioning and child failing. .navigation-top { background: #fff; border-bottom: 1px solid #eee; border-top: 1px solid #eee; font-size: 16px; font-size: 1rem; position: relative; } .navigation-top { background-color: #eeeeee; border-bottom: 2px solid #e60909; } My `functions.php` is shown below: <?php add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX); function enqueue_child_theme_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' ); } ?>
You should type with !important; Tag with css like these it will work .navigation-top { background-color: #eeeeee !important; border-bottom: 2px solid #e60909 !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "theme twenty seventeen" }
Check and load class of theme from a plugin I'm in the process of breaking down a theme to a bunch of plugins, I wanna do it one by one so hell won't break loose. Question is, Suppose I have a plugin which depends on a class from the theme, where and how should I validate his existence and load it, and if not exist how do I properly show an error and avoid loading the plugin, is it on the activation hook? I'm pretty new to plugins, and would love to get best practices, or any good docs references regarding my issue, thanks! I don't need to check another plugins existence, just another code that is currently part of the theme.
I'd recommend to not use methods from your theme in the plugins. **Only the other way around. Let your plugins provide methods to be used in the theme.** Then you could simply use `is_plugin_active()`. * * * Nonetheless you could use PHP's `class_exists()` to check for the existence of a class. Another common practice seems to be to let your plugin `die;` at the very top before anything else can be loaded. <?php /* Plugin Name: My Plugin Description: Lorem ipsum dolor sit amet. Version: 1.0 Author: You Author URI: */ if ( ! class_exists('MyThemeClass') ) { die; } class MyPlugin() { // ... } new MyPlugin;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development" }
Move add to cart in Woocommerce I would like to have "add to cart" button nearby the price like in the picture. By default, the button is placed after the price in the code, and I would like to move the button in the same tag of the price. But I don't know which template of Woocommerce I have to edit to make this. Thank's ! ![enter image description here](
> You can change the priority/order by removing and re-adding the parts you want the position changed - like this: remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 ); add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10 ); **Drop this piece of code into your functions.php to take effect.**
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic" }
How to disable updates in WordPress theme I am working on a WordPress website. Earlier before me, there was one another guy has worked on that website. Now he has done all his changes in parent theme without creating a child theme. Now, what should I do to prevent updating theme? Also, I know it is nearly impossible but If anybody can suggest me any step to separate both changes. that would be more helpfull. Theme is twentyseventeen
First of all, it is a very bad idea to modify the original theme without creating a child theme. Disabling updates of such theme is even worse idea, because without updates, your site may get infected or attacked. So the long-term solution would be to: 1. Check the version of modified theme. 2. Download that version from official repository. 3. Compare the original files with modified ones. 4. Create a child theme containing only necessary modifications. If you need to disable the updates for a few days, there is an easy way to do it - just change the version of your theme to 9.9.9 - WordPress will think that it is newer than the one in repository and it won't get updated. (BUT... Don't think of this hack as a solution - it's just a dirty temporary fix and you still should perform the process from points above).
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "child theme, updates" }
remove add to cart for free (0 $) product woocommerce I use woocommerce. How to hide the "Add to cart" Button on a single-Product page IF the product is for free (0 $) . Have an idea to do it?
Please try to add following code into your theme **functions.php** file function remove_add_to_cart_option( $purchasable, $product ){ if( $product->get_price() == 0 ) $purchasable = false; return $purchasable; } add_filter( 'woocommerce_is_purchasable', 'remove_add_to_cart_option', 10, 2 ); Replace below function instead of above and check again /* * Override via functions.php **/ if (!function_exists('woocommerce_template_loop_add_to_cart')) { function woocommerce_template_loop_add_to_cart() { global $product; if ( ! $product->is_in_stock() || ! $product->is_purchasable() ) return; woocommerce_get_template('loop/add-to-cart.php'); } } Let me know if any query. Hope it will help you !
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to have the Header show different content on different pages? I made a Navigation (primary) via Appearance->Menus which navigates the user to anchor tags on the side, but I also have subpages, where I want a different navigation - only with my 'Home'-button in it. Which would mean I need to get rid of the other navigation points. I did create another sub-navigation for the subpages, but don't know how to get it up. My `header.php` shows me `<php if (has_nav_menu ( 'primary') ) : ?>` Can i just do an `else` with another navigation? My Theme only supports one menu though ... Big thanks for the help! :)
It doesn't sound like you need another Navigation menu. How about something like this: <?php if ( is_page() && $post->post_parent > 0 ) { // we know we are on a sub/child page now... // PS. another way to handle this would be to check if you were on a particular page template or particular page ids etc. ?> <a class="awesome-button" href="<?php echo esc_url( home_url( '/' ) ); ?>">Go home!</a> <?php // just show a link Home for the subpages... } else { // now we are NOT on a subpage, so show the Primary nav menu... wp_nav_menu( array('menu' => 'primary') ); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus, navigation" }
Add to array, redirect and display I want add text to array and display after redirect and unset array. class test{ public function one(){ $this->save(2, 'some'); $url = get_site_url(null, '/redirect_to_two'); wp_safe_redirect( $url ); } public function two(){ $this->display(); } }
If you need to pass some data over the redirect, you can do that by adding parameters to the redirect url with `add_query_arg()`. But other more elegant solutions might exist also. Single parameter, wp_redirect( add_query_arg( 'notice', 'success', get_site_url(null, '/redirect_to_two') ) ); exit; or multiple parameters wp_redirect( add_query_arg( array( 'notice' => 'success', 'foo' => 'bar' ), get_site_url(null, '/redirect_to_two') ) ); exit; Then use `$_GET` to grab the parameter(s), if ( ! empty( $_GET['notice'] ) && 'success' == $_GET['notice'] ) { // Do whatever. } If I'm not mistaken, I don't think you need to worry about unsetting arrays as data doesn't normally persist in WordPress. Once you do a redirect all the data in your `$variables` are gone.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, redirect, array" }
WordPress ajax-action how to return content So I'm trying to set up an AJAX action for a plugin I'm building. When using `/wp-admin/admin-ajax.php?action=beacon_podio-get_apps` I was just getting `hello world0` and I'm not seeing `Request is valid` or the `Invalid request` so it seems like the action is not being called I think I'm missing something but I'm not sure what I'm missing. class testClass { public function __construct(){ echo "hello world"; add_action('wp_ajax_beacon_podio-get_apps', array($this, "get_apps")); } public function get_apps(){ if(isset($_POST['app_id'])){ $app_id = $_POST['app_id']; die("Request is valid"); }else{ die("Invalid request"); } } } new testClass(); I have been reading < but it's missing the URL I'm supposed to be using. ![Output from wordpress](
This appeared to be a bug in WordPress, coming back to this and upgrading to version 5.2 the problem seems to have been fixed for some reason the has_action was failing to find the action unsure why but it seems to have been fixed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, actions" }
How to save a shortcode in a Gutenberg custom block? I am creating a Gutenberg block, and in the save function I am returning a shortcode. When I click on save the page, a message is displayed: "Failed to update", but when I check the front end it has been saved. What error may be occurring? save: props => { return '[custom-shortcode param_1="value_1" param_2="value_2" /]'; }
What you are looking for is RawHTML to render on the front end. To use a player shortcode in the post you can use the code below remember that the edit function needs to mirror the markup for the save function for Gutenberg to validate the block. Include RawHTML: const { RawHTML } = wp.element; Save & Edit Functions: edit: function( props ) { return ( <div> <RawHTML></RawHTML> </div> ); }, save: function( props ) { var myShortcode = '[custom-shortcode param_1="value_1" param_2="value_2" /]'; return ( <div> <RawHTML>{ myShortcode }</RawHTML> </div> ); },
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "shortcode, block editor" }
Why wp_update_post() does not update GUID? Trying to update `GUID` on a attachment using the `wp_update_post()` function but its not updating GUID nor its throwing any error. Example code: $post = [ 'ID' => 45, 'guid' => ' ]; wp_update_post($post);
Turns out WordPress do not recommend updating `GUID` thus its disallowed. But we can update it using sql query: global $wpdb; $wpdb->update($wpdb->posts, ['guid' => $newGUID], ['ID' => $postID]);
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "wp update post" }
What permissions does a role need for the user to be assigned as the author of a post? I have a Wordpress site with custom roles (except for administrator) and now wanted to create a role so that a user with this role can be manually assigned as the author of a post. I thus created a role which had all permissions checked in the "post" submenu, but none in the others (since this role is only there for this reason). A user that has this role assigned can now however still not be chosen as the author of a post, but only the ones with an administrator role. My question therefore is: What permissions does a role need so that the user can be assigned as the author of a post? I would really like to not make this user an administrator
You probably need to add 3 capabilities: * edit_published_posts * publish_posts * delete_published_posts but at the very least, you need to add `publish_posts` as that is the capability WordPress uses to determine what users are shown in Authors drop-down. Note: Changing capabilities is stored in the database so the recommendation is to modify these values via a plugin and only when the plugin is activated or deactivated rather than on every request.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, author, members, plugin members" }
Merge tags in multistep Gravity Form? I want to use a multi-step form where the user enters their name in step one, then on step two the form will say "Hello, [name]" with the rest of the content and steps to follow. Any ideas? EDIT: I want to use data entered in step one on step 2. Reading GF documentation I think something like {[Field Name]:[field_id]} should work, but it does not. Digging further I found that this would only work once a form has been submitted already. So my question is, is there a way that will enable me to use the merge tags within the current form from data being submitted in a previous step?
This is possible with **Live Merge Tags** , a feature of Gravity Forms Populate Anything. If you're looking to get your hands dirty with some code, Gravity Forms has an example of how this might work with a snippet on their docs for the `gform_pre_render` filter: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin gravity forms" }
I have Wordpress setup on primary domain, how do I set it up on its subdomain using the same database? I have a site www.domain.com with Wordpress installed. I need to create a subdomain for testing a new theme and have it linked to the main site's database. I have manually added the Wordpress files into the subdomain and during the install in the browser I added the database info of the main site. However when I then try to complete the installation it tells me that I already have Wordpress installed and directs me to log into the main site. When I do so there is no option to view the subdomain. How do I link the subdomain to the main site's database and have them work independently?
Change the `$table_prefix` in the `wp-config.php` file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, query" }
do I need to sanitize a shortcode's function input? I'm using the following custom plugin to count the number of members in the MemberPress database: function display_member_count( $atts ) { global $wpdb; $sql = "SELECT COUNT(`meta_key`) as count FROM `wp_usermeta` WHERE `meta_key` = 'mepr-address-state' && `meta_value` = '" . $atts[0] . "';"; $myrows = $wpdb->get_results($sql); $member_count = $myrows[0]->count; return $member_count; } add_shortcode( 'member-count', 'display_member_count' ); I would then use the shortcode `[member-count nsw]` to display the number of members in NSW. Do I need to sanitize `$atts`? If so, how please? Help appreciated.
Of course you do have to sanitize it and escape it. Otherwise any author/editor of the site will be able to perform any query on your database. First of all you should never create SQL queries like you do in your code. Never concatenate the raw SQL with anything that is variable or comes from user. You should use `$wpdb->prepare` for that. So your code should look more like that: $sql = "SELECT COUNT(meta_key) as count FROM {$wpdb->usermeta} WHERE meta_key = %s && meta_value = %s"; $member_count = $wpdb->get_var( $wpdb->prepare( $sql, 'mepr-address-state', $atts[0] ) ); As you can see, there is also no point in getting all rows (there’s only one) and there’s no point in getting all columns (there also is only one). That’s the escaping part that will save you from SQL injections. But yes - most likely you should also put some validation in there - but it depends on what are the available values for that param.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, sanitization" }
WooCommerce Description and Short Description <p> tags removal When adding content into the description and short description fields for a product, line-breaks and tags are completely removed from the markup. Other than installing Advanced TinyMCE, is there any setting, filter, or hook I need to check to make these fields include elements. In review of the Product object array in WooCommerce, it looks like the value for description is wrapped in the wpautop() function, but it doesn't appear to be working (it's possibly I'm just not understanding this part of the code correctly within the plugin). Any ideas on how to force paragraphs into short/description content in WooCommerce? Note: I only have ACF and WooCommerce installed as plugins. I'm using Underscores as a parent theme to build my own custom theme and product templates.
So, I realized I was using the actual object in the template to call the description `$product-get_description()`. If you're experiencing this issue, then you can wrap this in a `wpautop()`, or you can do what WC actually does (not sure how I didn't remember) and use the simple `the_content()` function to get the description. That will wrap any line breaks in your the editor with `<p>` tags if you want them.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "woocommerce offtopic, wp autop" }
Reorder attachements in the media library I have a plugin that takes an user selected image from the media library, puts some special effects on it, and then saves a copy of the "enhanced" image back to the library using media_handle_upload(). This works fine, but it puts the updated image at the top of the media library, separating it from the original. I want to keep the enhanced attachment next to the original, and I learned from this question that data for post attachments is mainly stored in the wp_posts table. However I can't find what column in the wp_posts is used to sort attachments when the wordpress media library displays them. Any help with this problem would be much appreciated, thank you!
Attachments in Media Library are obtained using WP_Query, so you can modify that query with `pre_get_posts` action. By default they are sorted DESC by post_date. So the easiest way to fix your code would be to change so the new modified attachment has the same post_date set as the original one.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "media library" }