INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Display all subcategories from parent category I have 20 subcategories from a parent category, and they are like that Parent * September * November * … up to 20 Here is the code that try it to display, but I get only 1 category instead <?php $categories = get_categories('child_of=505'); foreach($categories as $category): ?> <div class="qitem"> <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>"> <?php echo $category->name; ?> </a> <h4> <span class="caption"> <?php echo $category->name; ?> </span> </h4> <p> <span class="caption"> <?php echo $category->description; ?> </span> </p> </div> <?php endforeach; ?>
`get_categories()` uses `get_terms()` so the array argument you can pass it will be the same. From the documentation the array can have a property `hide_empty`, by default its `true`. I'm guessing that those categories have no posts attached to it, if that is the case you will need to set it to `false`. The code would be like this. get_categories([ 'child_of' => 505, 'hide_empty' => false ]); ## Update If you want to order the results you can add `order` to the array, the default value is `ASC` so you will need to set it to `DESC`. get_categories([ 'child_of' => 505, 'hide_empty' => false, 'order' => 'DESC' ]); You can check WP_Term_Query::__construct( string|array $query = '' ) for all the available arguments you can use.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
How to get a page slug in WordPress? I would like to know if anyone knows how I can get the call to a wordpress slug with a wordpress function. All this in order that everything is added automatically in the following way, EXAMPLE: <link rel = "alternate" hreflang = "fr-BE" href = " HERE}}" /> As you can see, I only need the function to take the slug of the page without including directories or anything like that. Thanks for your support!
Going by your link tag and the place you want the slug in, the code would be like this. <link rel="alternate" hreflang="fr-BE" href=" get_post_field('post_name'); ?>" /> You don't need to add all those spaces in attributes, for example, instead of `rel = "alternate"` do `rel="alternate"`, and so on.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "slug" }
SQL Query to Update Admin Email After pushing a staging site to production I have `[email protected]` set as the admin email which I need to change. Obviously I can't access that email to verify the change because it doesn't exist so I wrote this query: UPDATE wp_options SET option_value = '[email protected]' WHERE option_name = 'admin_email' I found this related answer but I do not use phpMyAdmin. Is this an OK method to override this? Or is there a more proper method?
While your SQL query will probably do the trick, you don't need to interface directly with the database to accomplish this. The preferred methods would by using Wordpress' `update_option()` function or by running the WP-CLI command:`wp option update`. ## Via `update_option()` To override the admin email change confirmation process, add the following to your `functions.php` file and hit "save changes". `update_option( 'admin_email', '[email protected]' );` Then once you've verified that the change worked, you can go back to your `functions.php` and remove the snippet. * * * ## Via WP-CLI If you have WP-CLI installed, you can run the following command from your shell/terminal (much faster): `wp option update admin_email [email protected]` If WP-CLI is owned by root, you'll obviously need to run it with `sudo`. Success will give you the following output: `Success: Updated 'admin_email' option.`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "database, admin, email verification" }
Looking for a better way to initiate cron job Is there any other good way to initiate an hourly cron job other than using `register_activation_hook` within a plugin? As looks like it will not be useful for websites that have already installed and activated that plugin. Thanks
Simply check if the event is scheduled, and if not, schedule it: add_action( 'init', function () { if ( ! wp_next_scheduled( 'my_scheduled_event' ) ) { wp_schedule_event( time(), 'hourly', 'my_scheduled_event' ); } } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, wp cron" }
What's the name of the custom post type yearly archive template? I know there's a name for every kind of template. archive-CPT.php, or single-CPT even taxonomies taxonomy-taxonomyname.php but, what's the name I should use for the template that have my yearly archive?
CPT's don't have date archives, those are a `post` specific feature. Having said that, nothing prevents you building a custom bespoke date archive for a CPT. Just don't expect WordPress core to do it for you, it would be a 100% custom job, you'd have to load your own date templates, modify the query, add the rewrite rules, and construct the URLs yourself. The closest you can get out of the box, is visiting a CPT's archive, and appending query args to the URL, e.g. `example.com/yourcpt?year=2022`, but this will give you the same archive as that URL but with the additional filtering to 2022. Note that this only works with standard archives, it will not work if you replace the main query, rely on page templates to recreate archives, or use a page builder. It also won't be considered a date archive by WordPress functions and APIs
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy, archives, custom post type archives" }
Add Line Break/Remove Commas for Checkbox options sent via Email from Contact Form 7 Currently when someone submits a contact form that contains multiple checkbox options, when it comes through via email it’s all on the same line split by commas. Is it possible to change the Contact Form 7 email format so it instead adds a line break and removes the commas for checkbox options? We do want it to remain as it is on the actual contact form (where the options are all in one line/a paragraph, not split up by line breaks) – just want the email results to change. **So for example we would like to checkbox results sent via email to showing:** Eggs, Bread, Milk, Water, Oranges **To this (without the bulletpoint):** * Eggs * Bread * Milk * Water * Oranges Is this possible? And if so how would we configure this to work?
yes, this is possible using the CF7 `'wpcf7_mail_tag_replaced'` filter, add_filter('wpcf7_mail_tag_replaced', 'format_chackbox',10,4); function format_chackbox($replaced, $submitted, $is_html, $mail_tag){ //you can check if this is the right field if need be. if('my-checkbox-field' != $mail_tag->field_name()) return $replaced; //$submitted contains the raw submitted data. //$replaced is the formatted data, you can use either. $a = explode(',', $replaced); //check if you have multiple values and the email accepts html (set with the use html checkbox in the mail notification settings). if(is_array($a) && $is_html){ $replaced = '<ul>'.PHP_EOL; foreach($a as $v) $replaced .= '<li>'.trim($v).'</li>'.PHP_EOL; $replaced .= '</ul>'.PHP_EOL; } return $replaced; } place this in your `functions.php` file
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin contact form 7" }
How do I modify the custom footer text and get theme version number to show in wordpress admin? I am trying to modify the footer text inside the wordpress admin and also get my custom themes version number to show as well but my function is not working properly, I am still very green at PHP ~ Thank-you in advance! function modify_admin_footer() { echo '<span id="footer-thankyou">Developed by <a href=" target="_blank" rel="noopener noreferrer">Toolcart Theme Version:</a>.</span>'; wp_get_theme()->parent()->Version; } add_filter( 'admin_footer_text', 'modify_admin_footer' );
Try returning your span instead of echoing it. function modify_admin_footer() { return '<span id="footer-thankyou">Developed by <a href=" target="_blank" rel="noopener noreferrer">Toolcart Theme Version:</a>.</span>' . wp_get_theme()->parent()->Version; } add_filter( 'admin_footer_text', 'modify_admin_footer' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, wp admin" }
paypal not showing on woocommerce payments ![enter image description here]( Had install a fresh wordpress installation on localhost, and after install woocommerce plugin, the paypal default - payment isnt there on woocommerce tab "payments". On the live website paypal continues working just fine. Do I need a plugin now, anyone knows something about it
Paypal standard is now hidden for new installs, possible to read about it in < for those who want to use it copy paste this code on functions.php add_filter( 'woocommerce_should_load_paypal_standard', '__return_true' ); Since july 2021 woocommerce recommends users to use the recommended PayPal extension instead
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic, paypal" }
wp-mail attachment is not sent for no reason? I'm using wp-mail to send an image. The problem is that it does not attach the image ! Here is `$attachment_img` string : ` So the path is correct Here is the function : function send_mail_to_admin($orderId , $attachment_img){ $headers = array('Content-Type: text/html; charset=UTF-8','From: انجمن آبزیان <[email protected]>'); $body = "<html><body> <b style='font-size:14px;direction:rtl;text-align:center;'>یک مشتری سفارش با شماره $orderId ثبت کرد</b> </body></html>"; wp_mail( "[email protected]", "دریافت نامه کاربر", $body, $headers , array($attachment_img) ); }
I changed the code to this and it worked ! Don't know why I should do this and this is very odd but whatever. function send_mail_to_admin($orderId , $attachment_img){ $attachment_img = str_replace(" , "" , $attachment_img); $attachment_img = array( WP_CONTENT_DIR . $attachment_img ); $headers = array('Content-Type: text/html; charset=UTF-8','From: انجمن آبزیان <[email protected]>'); $body = "<html><body> <b style='font-size:14px;direction:rtl;text-align:center;'>یک مشتری سفارش با شماره $orderId ثبت کرد</b> </body></html>"; wp_mail( "[email protected]", "دریافت نامه کاربر", $body, $headers , $attachment_img ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, directory, wp mail" }
How to send variable to wp meta_query value? I try to to make compare by company title so I need to send this title as variable to meta query value. I use this code and get value = NULL. Please tell me why? $company_name = the_title( ); $params = array( 'meta_query' => array( array( 'key' => 'user_company', 'value' => $company_name ) ) );
Use `get_the_title` to get the title. `the_title` is for when you want to output directly to the browser.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "meta query" }
Get term from multiple taxonomy I am trying to show all the terms from these taxonomies. However, I can't get them working. Please help, thanks <?php $terms = get_terms( 'taxonomy' => array( 'category', 'profile_status', 'profile_skill') ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ echo '<ul>'; foreach ( $terms as $term ) { echo '<li>' . $term->name . '</li>'; } echo '</ul>'; } ?>
Your `get_terms` is causing a parse error, you are missing the array part. Also when using `get_terms` take into account that by default it will not return taxonomies that don't have posts attached to them. The proper code would be like this $terms = get_terms([ 'taxonomy' => [ 'category', 'profile_status', 'profile_skill' ] ]); If you want to include empty taxonomies (taxonomies without posts attached to them), do this $terms = get_terms([ 'taxonomy' => [ 'category', 'profile_status', 'profile_skill' ], 'hide_empty' => false ]);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "taxonomy, terms" }
hide elements of admin with css file i use woocommerce and woocommerce Product Vendors (< i want hide elements of admin with css file "my-admin.css" I put css file "my-admin.css" at the root of my child theme wordpress and use this code in functions.php. This does not work?!? function admin_css() { $admin_handle = 'admin_css'; $admin_stylesheet = get_template_directory_uri() . 'my-admin.css'; wp_enqueue_style($admin_handle, $admin_stylesheet); } add_action('admin_print_styles', 'admin_css', 11); is this an obselete method? because: when i use this other method in functions.php, it's ok it works add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo '<style> body, td, textarea, input, select { font-family: "Lucida Grande"; font-size: 12px; } </style>'; } What do you think ? thanks !!! :)
It's always better to encapsulate your styles in a separate file, so your first example is closer. That said, the documentation for admin_print_styles says quite clearly: > admin_print_styles should not be used to enqueue styles or scripts on the admin pages. Use admin_enqueue_scripts instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, admin css" }
make admin.css in my child theme i want hide elements of admin with css file "my-admin.css" I put css file "my-admin.css" at the root of my child theme wordpress and use this code in functions.php but does not work? there may be an error? thank you ! : <?php /* activation theme */ function wpm_enqueue_styles(){ wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'wpm_enqueue_styles' ); /* admin stylesheet */ function wp245372_admin_enqueue_scripts() { wp_enqueue_style( 'my-admin-css', get_template_directory_uri() . '/my-admin.css' ); } add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );
The `get_template_directory_uri()` function gets the URL to the _parent_ theme. The equivalent function for child themes is `get_stylesheet_directory_uri()`. However these days the proper function to use to get the URL for a file in a child theme is `get_theme_file_uri()`: function wp245372_admin_enqueue_scripts() { wp_enqueue_style( 'my-admin-css', get_theme_file_uri( 'my-admin.css' ) ); } add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue style, admin css" }
Variable global scope I'm trying to create a few custom post types, and instead of hard-coding their names I just want to define them as a globally scoped variable. I thought I understood the scope but apparently not. The code below results in an error of `Undefined variable`: $filmLabel = "Films"; $showLabel = "Shows"; function CreatePostTypes() { register_post_type( $filmLabel, GenerateFilmType($filmLabel)); register_post_type( $showLabel, GenerateFilmType($showLabel)); } add_action( 'init', 'CreatePostTypes' ); I've tried using `$GLOBAL` as well, with the same result. Can anyone spot what's wrong?
Globals are generally discourgaged. You can use define instead. <?php define("FILM_LABEL", "Films"); define("SHOW_LABEL", "Shows"); function CreatePostTypes() { register_post_type( FILM_LABEL, GenerateFilmType( FILM_LABEL ) ); register_post_type( SHOW_LABEL, GenerateFilmType( SHOW_LABEL ) ); } add_action( 'init', 'CreatePostTypes' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, variables" }
Add $args to wp_list_categories I'm trying to add an argument to wp_list_categories of the Categories Widget: function cat_list_show_all( $list, $args ) { $args['show_option_all'] = __( 'All Cateogries', 'textDomain' ) . '<span>' . wp_count_posts()->publish . '</span>'; return $args; } add_filter( 'wp_list_categories', 'cat_list_show_all', 10, 2 ); But, it return "Array" on front-end. What's the right way to do it?
The documentation for the `wp_list_categories` filter says that it: > Filters the HTML output of a taxonomy list. So it filters the final HTML, not the args, but you're returning `$args`, which means that the final HTML is replaced with the args array. That's why you're seeing "Array". To filter the args for the categories list in the Categories widget, you need to use the `widget_categories_args` filter. function cat_list_show_all( $args ) { $args['show_option_all'] = __( 'All Cateogries', 'textDomain' ) . '<span>' . wp_count_posts()->publish . '</span>'; return $args; } add_filter( 'widget_categories_args', 'cat_list_show_all' ); However, be aware that this filter only works for the "legacy" Categories widget. Newer sites will only have access to the Categories _block_. The Categories block does not have an equivalent filter, so filtering the args is not possible.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, filters" }
Multisite login - registration is duplicated I am running a Multisite installation of Wordpress that runs WooCommerce. There six subsites, three of which are a traditional B2C retail and another three that are B2B Wholesale. Anybody can access the B2C (they are territory dependent), create an account and transact. The B2B is different; we manually create the accounts for our Wholesale customers. * **B2C** \- www.domain.com/my-account * **B2B** \- www.domain.com/wholesale/my-account So we have have noticed that if the Wholesale customer goes to the B2C my account page mistakingly and uses their B2B credentials then they are logged in and a new registration is created there. SO they now have access to both the B2B and B2C sites which can lead to confusion. How I can prevent this auto 'dual' login
By default WordPress Multisite indeed has a shared user base. So, there is no new registration created in de B2B site. It is simply the same registration for all six sites. Of course, this can be modified. You could try programming this yourself, but there are plenty plugins that will do this for you. We don't do software recommendations around here, but you could try googling for "wordpress multisite user management plugin".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, multisite" }
Automatic excerpt is not shown with the_excerpt() command I've been looking for an answer to this question for a long time, but haven't found anything: how come when I use the_excerpt() on a given site it doesn't automatically print the first few characters of the content? The excerpt only prints it if something has been added to the WordPress summary field of the post. How can I fix this problem? With other sites this does not happen and if no text is added on the summary the excerpt is generated automatically. What could it be that the excerpt is not automatically generated? My situation is similar to this: Automatic Excerpt Not Working but your response did not provide me with any advice unfortunately.
By default, `the_excerpt()`, doesn't uses the post/page content wysiwyg, it has its own textarea, that by default is not visible, you need to enable it first via screen options. ![enter image description here]( After you checked this checkbox you can scroll down to the bottom of the post/page and see a new textarea, this is the excerpt. ![enter image description here]( If you want to use the content (wysiwyg, `the_conetnt()` or `get_the_content()`) as excerpt, you will need to use wp_trim_words. Something like this. // the second argument is how many words to trim, default is 55 <?= wp_trim_words(get_the_content(), 30); ?> Anothe option, if you want to keep the html structure would be to do this. <?= force_balance_tags(html_entity_decode(wp_trim_words(htmlentities(wpautop(get_the_content())), 30))); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, excerpt" }
Conditional Generation of Image Sizes using add_image_size The add_image_size function is used to add image sizes in addition to the default thumbnail, medium, large, & full which are generated in WordPress by default. Is there any way to only add those image sizes for specific uploads? Or are we limited to generating all possible image sizes for every upload?
Take a look at the intermediate_image_sizes_advanced filter. This filter receives the attachment ID in question, so with that you should be able to work out whether or not you want the intermediate sizes, and return an empty array if not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, theme development, images" }
Automatically download, install and activate plugins that my plugin depends, how? I'm developing a plugin that requires a couple of plugins from WordPress repository to work correctly. Is it possible to download and install from WordPress repository and activate one or more plugin that my custom plugin requires automatically on plugin activation? There is a safe and correct way to do this via PHP?
TGMPA is a useful php class to perform the required actions: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development" }
How to change widget title in wordpress version 5.8.1? Maybe this is a novice question but I am stumped. I am trying to change the title of a widget (recent posts) in WordPress 5.8.1 version. I have installed WordPress after a long time again and can not seem to find the option to change a widget title. How to do this? Please remember that I do not want to change the title programmatically as I can do that. Just want an easy point and click option like the old WordPress. I have attached a screenshot of the widget admin screen. ![enter image description here](
In WordPress 5.8 the ability to add Blocks to widget areas, and several core widgets were replaced with Blocks. Blocks do not have a standardised title field. So to add titles you will need to use a heading bock, and for any blocks that do have a title, whether or how a title can be changed would depend entirely on the block.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, widget text" }
Mass SQL Wordpress Meta Key deletion hi i am newbie with SQL data base so forgive my dumbness i have installed KK Star rating plugin on my wp site which noticed its recording lot of entries and my db size is over 280 MB and 188MB is wp_postmeta table. uninstalled the plugin and i want to run sql query to delete all postmeta with kkstar recorcs. the meta key record is: kksr_fingerprint_default so please give me correct command line to run thanks in advance
DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' {PREFIX} is the string `$table_prefix` defined in wp-config.php; of course be careful in run SQL DELETE, create a table backup and (maybe) execute first a single line deletion to check the result DELETE FROM `{PREFIX}post_meta` WHERE meta_key = 'kksr_fingerprint_default' LIMIT 1
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, post meta, mysql" }
Set a specific page as 404 - not found via my own plugin I'm developing a plugin that create some pages and set a specific template for each of these pages. It creates a page in which it sets a template for 404 - not found, how can set this specifc page as WordPress 404 (so it will be displayed when needed)?
You can filter `404_template` and return the path of your custom file from the plugin directory like this: add_filter( '404_template', fn() => plugin_dir_path( __FILE__ ) . '404.php' ); This hook exists only when a 404 happens, so you don't need any custom detection.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, pages, 404 error" }
i need to let a user to add a role from a frontend form i need to let a registered user who already has role or 2 roles the ability to add himself a role via frontend form. i tried to look for it and didn't find anything related that can help me. any ideas? thanks.
I think each user can only have one role. However this is how its possible to change role, if for some reason that I dont know the user can have more than one role, remove the remove role line. you can check the available roles here. $current_user = wp_get_current_user(); // Remove role $current_user->remove_role( 'subscriber' ); // Add role $current_user->add_role( 'editor' );
stackexchange-wordpress
{ "answer_score": -2, "question_score": 0, "tags": "users, user roles" }
Get posts that do not have the same tags as current I'm trying to get all posts in a custom plugin loop that DO NOT share the same tag as the current one. I'm trying: $events = tribe_get_events([ 'start_date' => 'now', 'eventDisplay' => 'list', 'posts_per_page' => 3, 'tag' => $current_tag // <-- Trying to do the exact opposite of this ]); I'm using < 's plugin. But under the hood, that just uses the normal WP args setup. Is there a way to invert the tag selection to get posts that DO NOT have that tag?
I found an answer to my own question: If I use the `tax_query` arg then I could specify `'operator' => 'NOT IN'` like so: $events = tribe_get_events([ 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'field' => 'name', 'terms' => $current_tag, 'operator' => 'NOT IN' // HERE ) ), 'start_date' => 'now', 'eventDisplay' => 'list', 'posts_per_page' => 3, ]);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, loop, tags, query posts" }
How do I include SVG file used as featured image? I'm new, can I use include() or get_template_part to load an SVG file uploaded as featured image directly in the HTML page? I need to animate the svg images, but i need to easily change the image on each page. I have tried this code but does't work, I can't find the right path, I can load only the svg images in the same folder. $domain = get_site_url(); $svg_url = get_the_post_thumbnail_url(get_the_ID()); $svg = str_replace( $domain, '', $svg_url ); echo $svg; //only for read the url get_template_part($svg); // or inlcude $svg;
First, you don't need the URL but the server path to the file, you can get it with `get_attached_file` function, passing any WordPress attachment ID as a parameter. Then you need to load the contents of that SVG file directly, via `file_get_contents` function and echo it out to the page. $thumbnail_id = get_post_thumbnail_id( get_the_ID() ); $thumbnail_path = get_attached_file( $thumbnail_id ); echo file_get_contents( $thumbnail_path );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, svg" }
Will I get an error if I try unscheduling a WP Cron scheduled task that wasn't scheduled? So, I'm developing a plugin, I wanted to know if I call $timestamp = wp_next_scheduled( 'scheduled_hook' ); wp_unschedule_event( $timestamp, 'scheduled_hook' ); Without checking if it's scheduling at all, will it give me an error or will it just go through it and unschedule it in case it is actually scheduled and ignore it otherwise?
So yeah, it does give errors for trying to unschedule something that isn't scheduled, but the answer is pretty easy and simple: $timestamp = wp_next_scheduled( 'scheduled_hook' ); if ($timestamp) wp_unschedule_event( $timestamp, 'scheduled_hook' ); Since `wp_next_scheduled` will return false for unscheduled hooks, a simple `if` in front of the call to `wp_unschedule_event` will prevent it from being called it there's nothing scheduled
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, wp cron" }
Applying WP-cli Search & Replace to Static SQL Dump File I have a wp db dump file inside my site directory. Can someone show me an example of how to use wp-cli search and replace command on the static sql file, not the active db to change my url from "old-example.com" to "new-example.com" /var/www/html/wp-site.com/dumps/oldexample.com/dumpeddb.sql /var/www/html/wp-site.com/dumps/newexample.com/ready-for-import.sql Not quite sure how to apply this to already exported db dump. `$wp search-replace foo bar --export=database.sql`
This is not possible, WP CLI uses SQL queries to acquire and update information. You would need to import the SQL file into a database to perform a search replace with WP CLI.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, database, search, mysql" }
Put featured image under post title in admin area Instead of inserting a new column with a featured image on it, I would like to put the featured image under the post's already existing title. I can't seem to figure out how you insert things on the title property however. Achieving this: ![enter image description here]( I've found this post: How can i place Feature Image under title field in wp-admin? With a snippet that I can't get to work. Otherwise there are lots of solutions for adding new columns with featured images in them. I've arrived at something like this: add_action('admin_head-edit.php', function(){ add_filter('the_title', function( $title, $id ) { return $title . get_the_post_thumbnail_url(); }, 100, 2); }); But if I use `get_the_post_thumbnail_url` the url is embedded as part of the title, and if I use `the_post_thumbnail( 'thumbnail' )` it renders the image twice.
add_action('admin_head-edit.php', function(){ add_filter('the_title', function( $title, $id ) { return $title . the_post_thumbnail( 'thumbnail' ); }, 100, 2); }); Will produce 2 images because there are two titles on custom posts, apparently. One that is hidden and one that isn't. Adding the image markup to the hidden element will break the CSS that hides it. So the solution is to insert admin-css that hides it. .column-title .hidden ~ img{ display: none; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp admin, post thumbnails" }
Polylang : Display term archive even if no posts I use ACF to customize **taxonomy term archives pages** which are in fact **Team member pages**. Pages are translated with the help of Polylang. Problem is : If the member has no related posts, I can access directly the member page, but the translated page is not linked to the language switcher menu. Instead it has been replaced with a link to translated homepage. I found that this is common behaviour in Polylang. It is programmed to never show translated pages with no posts. After some research, if found this filter that might be helping. It has been added a while ago but there is no sign of it in the Polylang documentation. Anybody knows how to use is ? Thanks
Solution given by filter author : add_filter( 'pll_hide_archive_translation_url', '__return_false' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "terms, custom post type archives, plugin polylang" }
Display Current Date using shortcode I am using the below code to display current date in php using shortcodes for Indian time zones: add_shortcode( 'current_date', 'mth_footer_date2' ); function mth_footer_date2() { ob_start(); date_default_timezone_set("Asia/Kolkata"); echo gmdate("jS F Y"); return ob_get_clean(); } We need to add `[current_date]` Shortcode to display current date. This code is displaying date but I think, this is not in Indian Timezone. Please provide me such codes to display time in Indian Timezone. I want Date in following format, **Sunday, 24th October, 2021**. Also provide ways to show tomorrow date in same format.
You need to use `date()` in place of `gmdate()`, which returns the date/time for GMT. To get the output you want, change the code to: echo date('l, jS F, Y'); For displaying tomorrow's date, use the following code accordingly: $timestamp = strtotime('tomorrow'); echo date('l, jS F, Y', $timestamp);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "date" }
How do I add nopin="nopin" to the default avatar? I noticed that if someone clicks on my Pinterest share button on a blog post, several unrelated images show up. I was able to use _nopin= "nopin"_ per Pinterest's documentation on most of these images to clean most of it up. However, I have a custom avatar set in my functions.php... //* Add new default gravatar to Settings » Discussion page */ add_filter( 'avatar_defaults', 'wpb_new_gravatar' ); function wpb_new_gravatar ($avatar_defaults) { $myavatar = ' $avatar_defaults[$myavatar] = "Default Gravatar"; return $avatar_defaults; } If someone gets that avatar in a comment, then the image shows up as a choice on a Pinterest share. How do I add the _nopin= "nopin"_ attribute to this avatar image? I found a similar post discussing this issue, but it's way over my head and seems a little different because he's using an array (lol, also over my head). Any help is greatly appreciated!
You can try this one: function wp_ste_add_nopin_args( $args ) { $extra_attr = 'nopin="nopin"'; $args['extra_attr'] = $extra_attr; return $args; } add_filter( 'get_avatar_data', 'wp_ste_add_nopin_args', 999, 1 ); For further reading, please visit: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, avatar, gravatar" }
wp-json how to fetch image link? i'm trying to fetch some data and images. everything is working good, but i'm really tired to fetch the post thumbnail image. $data = array( ':attachment' => $record['_links']['wp:attachment'][0]['href'], ); the above code fetching media link such as ` but i want to fetch like that ` how i can do that? please try with a wordpress website with wp-json to see the structure.
i already fix this by using this $data = array( ':attachment' => $record[_embedded]['wp:featuredmedia']['0'][source_url] ); thanks for no person answered my question.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "json" }
Add attributes to wrapper html generated by wp_nav_menu I want to add some extra html attributes to the default div html generated by wp_nav_menu. I need to add simple code for example a short style code: `style="top:10px;"` _I can't do what I am doing in a css file_ ; _the html needs to be added in the php_. I have looked at many examples, of walkers, replacement codes like str_replace. I can't find a solution that functions the way I envision it exactly. I prefer to not use a walker code that is ten pages long php code just for doing this simple code addition. If there is not a simple way, the alternative is to wrap the menu in a second div and that is what I will do probably if I can't find another way; but I would prefer to learn a simple way to add the html code to the original div generated by wp_nav_menu.
Modifying the wrapper for the `wp_nav_menu()` is customizable with the `items_wrap` parameter. < The documentation states that the default wrapper is a `<ul>` element with an ID an CLASS attribute. This can be modified as you wish by modifying the markup passed to the `sprintf()` function used by `wp_nav_menu()`. The value for `items_wrap` is the argument passed for the wrapper. To output a `<div>` element with a style attribute: wp_nav_menu( array( 'items_wrap' => '<div style="css here">%3$s</div>' ) ); The `%3$s` in the example represents the items within the wrapper HTML.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, walker" }
JSON REST API Wordpress only showing first 10 categories Alphabetically ordered categories are shown first (first 10). If I try to show all categories in JSON / Wordpress, it's not showing it. So, imagine these are the categories: A B C D E F G H I J K (=10) L = not shown anymore How can I make sure I fetch them all? I am trying to fetch them in Dart via JSON, so I can only pass that to Dart. Is there a way I can achieve this?
This is normal behaviour, you've not accounted for pagination. The REST API returns 10 results per page by default, and can be configured to return up to but no more than 100 per page. You may be tempted to try `-1`, but this will not work, 100 is the maximum results per page that can be requested for performance and scaling reasons. WordPress provides 2 http headers indicating the total number of pages, and the total number of results across all pages so that you know how many requests are needed to fetch all results. I _**strongly**_ recommend reading the REST API handbook in the official documentation. This page covers how to use and control pagination, sorting, etc.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, categories, rest api, json" }
How to not display tags with less than X posts Is there a way to avoid displaying tags which have less than X Posts? the answer here is close Remove from Google Tags with less than 2 posts however it suggests to send a respose header to google. I would ideally like to NOT have these tags in my sitemap so that google does not index these pages which are basically duplicates of the original post with a different tag, not a good thing for SEO!
Tags don't create duplicate posts, so the likelihood of them hurting your SEO by appearing in a sitemap are slim. You can add a filter to the return of the taxonomies sitemap to remove tags. This is just a quick attempt I threw together. I haven't tested it but it should provide a basis to work from at the very least. function remove_low_tags($taxonomies) { //create a new array of tags with count above 2 array $allowed_tags; //loop through current array of tags and add them to $allowed_tags if they are > 2 foreach ($taxonomies as $tags) { if (count($tags) > 2) { $allowed_tags[] = $tags; } } return $allowed_tags; } add_filter('wp_sitemaps_taxonomies', 'remove_low_tags');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, tags, conditional tags" }
I'm getting a 401 while calling the wp-json endpoint via ajax **N.B. Resolved - I hadn't noticed it was a POST rather than a GET.** I'm trying to use an AJAX call from a front end page to pull a list "Staff" (custom post type). I can get the data in the browser via wp-json/wp/v2/staff but I get a 401 when I try to pull the data via AJAX. I'm assuming I need to authenticate somehow but can't work out how to to do it. Thanks in advance.
I had accidentally created a POST rather than a GET. Obviously, you need credentials if you post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "ajax" }
Why would the child theme load in the Customize preview, but not on the site itself? I have my child theme folder, the style.css sheet with the required template comment and some custom css, and I have the functions.php page with the required enqueing code. Everything seems to be in order, except that my custom css is not reflected on my website. However, it _IS_ reflected in the Wordpress Customize screen. Why would this be the case, and how would I get my site to display the custom CSS?
It appears to work correctly now, I do not know why emptying the cache didn't work before to allow the changes to show but it seems to work correctly now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css, child theme, theme customizer, wp enqueue style" }
Using a filter to change a path I know this is probably basic Wordpress coding but how would I achieve this? > Use the filter “wcvendors_pro_table_display_rows_path” — and return a path to the new template file. (/plugins/wc-vendors-pro/public/class-wcvendors-pro-table-helper.php Line #328.) Line #328 of plugins/wc-vendors-pro/public/class-wcvendors-pro-table-helper.php is: public function display_rows() { include apply_filters( 'wcvendors_pro_table_display_rows_path', 'partials/helpers/table/wcvendors-pro-table-data.php' ); } I have created a duplicate of wcvendors-pro-table-data.php in my child theme.
Create the template you want to use, say `wc-vp-table-rows.php`, put it in your theme, and add the following to your `functions.php`: add_filter( 'wcvendors_pro_table_display_rows_path', fn() => locate_template( 'wc-vp-table-rows.php' ) ); `locate_template()` returns a complete path; it also searches in parent and child themes.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, filters" }
How do I override template-tags.php in 2021 theme I've created a child theme and I want to overwrite functions in inc/template-tags.php file. I thought if I copy this file and recreate folder structure in my child them then it will work but it doesn't? How to do it properly?
Notice how the parent theme checks if they are already defined e.g. if ( ! function_exists( 'twenty_twenty_one_entry_meta_footer' ) ) { ... } Then just define them in your child theme's `functions.php` file, to override the corresponding template tag. It should work because the child theme's `functions.php` file is loaded before the parent's `functions.php` file that loads: // Custom template tags for the theme. require get_template_directory() . '/inc/template-tags.php';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme twenty twenty one" }
Product subcat with duplicate name of a subcat of another cat gets the category name in the slug Suppose the following categories tree in Woo: Men (slug men) -- Shoes (slug shoes / was created first) Women -- Shoes (slug shoes-women / was created second) Why is this happening? Both subcats belong to different categories. Why is the category slug appended to the name of the second _duplicate_ subcat? And anyway, for whatever reason Autommatic decided to program it that way, I need to change it, as the nature of the e-shop I'm building is full of such _duplicate_ subcat names, as it will sell clothing, and there will be the same subcat and even subsubcat names for many categories (Men, Women, Kids, etc)... Any insight on this?
It took me two days to figure this out in the proper way, so I'll add it here for anyone else that may need it in the future. add_filter('wp_unique_term_slug', 'prevent_cat_suffix', 10, 3); function prevent_cat_suffix($slug, $term, $original_slug) { if ($term->post_type == 'product' && $term->parent !== 0) { return $original_slug; } return $slug; } As you can see in the code, I've narrowed it down to products only, but you can make it suitable for any other post type also by removing the `$term->post_type == 'product' &&` in the code above.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "hierarchical" }
Get last published post in Wordpress using wp-cli I'm using below `wp-cli` command to get latest post ID: `wp post list --order='DESC' --orderby='ID' --field='ID' | head -1` This, however is inefficient as all posts are retrieved from DB and then `head` limits the number of returned posts. Is there a way to limit the number of returned posts using wp query?
Simply add: --posts_per_page=1 to limit the queried items to a single item.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp cli" }
Block to Popup Page, on demand? I have embedded HTML in a block which renders a Python console. What I want to do is to be able to pop-out the Block in a separate window. If that is not possible then may be a link that when I click on it pops-up a page that contains the console. How do i do that ? * * * I don't want the pop-up to be full-screen. I want to be able to move it around, so the text below can be seen. The HTML can be anything, I just give it as example. Let say : <div id=ABC>12345</div> * * * i know js/html/css but no idea of how wp works... Do i just embed html link with onclick=window.open(...) pointing to a wp-page ? Ooo but i have to somehow make it pure page i.e. no theme !! HOW? And second i have to hide ABC ! * * * Got it : < here is working : < dont look at the site ... it is still under construction ;)
Solved it : < here is working : < First install the “Blank Slate” plugin. Create New Page Leave the Title empty Set in Page property Template=”Blank Slate” Add whatever content you want Because there is no Title, we need set a Permalink so that is human readable, let say : your-site/blah Publish the page Go to the page you want to have the popup window show up on clicking a link Add the following code : <a href='' onclick='window.open(" target='blank'>Popup window</a>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages" }
Custom meta_query order for Elementor based on post meta key I'm failing at writing an Elementor `$meta_query` function so posts will be ordered by `meta_value_num` of a given key. Each post has a numeric value for the key `google_unique_page_views` My example is below: // Custom query to order 'recommended reading' posts by populatrity add_action( 'elementor/query/my_custom_filter', function( $query ) { $meta_query = $query->get( 'meta_query' ); if ( ! $meta_query ) { $meta_query = []; } $meta_query[] = [ 'order'=> 'DESC', 'key' => 'google_unique_page_views', 'orderby' => 'meta_value_num', ]; $query->set( 'meta_query', $meta_query ); }); Do I need to include the `value` query?
Assuming that you want to get posts with that meta key, regardless of content, and order by that meta value, you would need to set two properties. 1. meta_query 2. orderby So the code, based of your question would be like this // Custom query to order 'recommended reading' posts by populatrity add_action('elementor/query/my_custom_filter', function ($query) { if (empty($meta_query = $query->get('meta_query'))) $meta_query = []; // add our condition to the meta_query $meta_query['google_unique_page_views'] = [ 'key' => 'google_unique_page_views', 'compare' => 'EXISTS', ]; // set the new meta_query $query->set('meta_query', $meta_query); // set the new orderby $query->set('orderby', [ 'google_unique_page_views' => 'DESC' // or ASC, based on your needs ]); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, filters, meta query" }
How to get current cart values using WC_Shortcodes? I am trying to get current cart items from my own plugin using WC_Shortcodes::cart(); this will return cart details in html format. WC()->cart->get_cart(); code not working. i need only cart data without html format. please advise thank you.
You can get the value by using the global var global $woocommerce; $cart_value = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) ); Or WC()->cart->total
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, functions, shortcode" }
How can I add a UTM tag with PHP code to pick up the post slug dynamically in the UTM? The thing I want to do is doable, but I don't know how to do it. Embarrassment moment coming up: I actually did this a few years ago but lost the code and can't find online how it's done. What I want to do is to add a dynamic UTM tag on a link in my header so that the UTM tag picks up the slug of the page the visitor is clicking from. Example: If the visitor is on a post with the slug /something-goes-here/ and clicks on the CTA button, the CTA page that he goes to should have /second-page/?utm_source=something-goes-here Do you guys know how this can be done with a bit of code in PHP?
What comes to mind is getting the current post by `global $post`, next getting the post slug by `$post->post_name`, next checking the slug if it needs to update a link with a utm query. So something like this. // get the current post global $post; // get the post slug, if not set then set it to empty string $post_slug = $post->post_name ?? ''; // an array of slugs that need to add utm to link $utm_slugs = [ 'slug-1', 'slug-2', 'slug-3' ]; // set default value (empty string), in case no slug was matched $utm_query = ''; // if post slug exists and in the utm slugs array, set a utm query if (!empty($post_slug) && in_array($post_slug, $utm_slugs)) $utm_query = '?utm_source=' . $post_slug; Now that we have the php part taken care of we need to create the link. This is just an example so change it accordingly. <a href=" $utm_query; ?>">Some link</a>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, google analytics" }
Gutenberg custom block using only register_block_type() and HTML I have the following core block HTML <!-- wp:group --> <div class="wp-block-group"><!-- wp:heading --> <h2 id="hello-world">Hello world</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Lorem ipsum dolor...</p> <!-- /wp:paragraph --></div> <!-- /wp:group --> Is it possible to create a custom block from PHP using that HTML? Similar to as I would create Patterns? register_block_type() can be used to register blocks from PHP. Is it possible to simply pass the HTML to `register_block_type()` and create the custom block?
No, blocks are built with more than HTML - they need JS and PHP. However, you could add an HTML block wherever you need it, then click the More Options dots in the block's toolbar, click Add to Reusable Blocks, name your block, and save it. That block will then be available to use wherever you want it, and if you edit it, that will apply the changes everywhere.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, block editor, json" }
How to add a CSS class to this php code How can I add a CSS class to "هر متر طول" in this php code: add_filter( 'woocommerce_get_price_html', 'themefars_text_after_price' ); function themefars_text_after_price($price){ global $post; $product_id = $post->ID; $product_array = array( 1204,1202 );//add in the product IDs to add text after price if ( in_array( $product_id, $product_array )) { $text_to_add_after_price = ' هر متر طول '; //change text in bracket to your preferred text return $price . $text_to_add_after_price; }else{ return $price; } }
I am not sure where this html tags are allowed where this text is going, but maybe something like this: $text_to_add_after_price = '<span class="myclass"> هر متر طول </span>'; Change myclass to the class you want to use.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css" }
How do I use pre_option_{option_name} correctly? I am using a filter to decrypt an api_key that is stored with encryption. I have registered the following hook: // Decrypt API key after it is retrieved add_filter('pre_option_percify_api_key', array( __CLASS__, 'decrypt_api_key') ); The problem is, I cannot get at the stored value in the callback: public static function decrypt_api_key($encrypted) { // $encrypted is empty: echo($encrypted); // ... Am I calling the function correctly? How do I access the stored value of `percify_api_key` within `decrypt_api_key`?
The `pre_option_{$option}` hook is used to filter the value of the option **before** it's retrieved. You need to hook after the value is retrieved so you can manipulate it. In this case, you can use the `option_{$option}` hook. So your code will look like this: add_filter('option_percify_api_key', array( __CLASS__, 'decrypt_api_key') ); For more info - take a look at the source of the `get_option` function here. Specifically line #225.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks" }
Edit the_category (); for a hierarchical display For my wp theme I want to use the categories as tags on my posts. Example: ![enter image description here]( The problem is that the category in red must always be the parent and in gold the child. Except that returns the categories to me in alphabetical order and not in hierarchical order, so sometimes I end up with the child in red and the parent in gold ... Knowing that I would only use 2 categories per posts so 1 = the parent and 2 = the child Do you have a solution?
You could assign the post only to the child category, and call the function like so: the_category( ' ', 'multiple' ); This will output (notice the whitepsace between the anchor tags): <a href=" <a href=" rel="category tag">child</a>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, categories, tags, hierarchical" }
last_name + first_name orderby with meta_query [solved] I have small issue with orderby. I´m looking solution to orderby ASC (lastname + firstname) example: 1. Selanne Andy 2. Selanne Beeny 3. Selanne Teemu But now it arrays something like this: 1. Selanne Beeny 2. Selanne Teemu 3. Selanne Andy Here is code: $order_by_1 = array( 'meta_key' => 'last_name', 'meta_query' => array( array( 'key' => 'last_name', 'orderby' => 'meta_value', 'order' => 'ASC' ), array( 'key' => 'first_name', 'orderby' => 'meta_value', 'order' => 'ASC' ), ), 'orderby' => 'meta_value', 'order' => 'ASC' ); $usr_1 = get_users($order_by_1); // Array of stdClass objects. foreach ( $usr_1 as $user ) { .... Thanks for the help.
To do this you need to use named meta query clauses according to the official developer docs for `WP_Query`: > ## ‘orderby’ with multiple ‘meta_key’s > > If you wish to order by two different pieces of postmeta (for example, City first and State second), you need to combine and link your meta query to your orderby array using ‘named meta queries’. See the example below: > > > 'meta_query' => array( > 'relation' => 'AND', > 'state_clause' => array( > 'key' => 'state', > 'value' => 'Wisconsin', > ), > 'city_clause' => array( > 'key' => 'city', > 'compare' => 'EXISTS', > ), > ), > 'orderby' => array( > 'city_clause' => 'ASC', > 'state_clause' => 'DESC', > ), ) ); ``` > < This question was also asked and answered already here: Order by multiple meta key and meta value
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "meta query, user meta, array, order, wp user query" }
Can you make a custom gutenberg block that allows the gutenberg editor within it? I'm looking to achieve basically a wrapper for a collection of gutenberg blocks. The idea is that I can apply some ACF fields to the wrapper and then allow gutenberg to do whatever it does for the inner content. However, I can't add "gutenberg" as one of the fields in a custom ACF block. The closest thing I can get is a WYSIWYG editor, so that won't work. Has anyone here managed to get something like this working? Either a wrapper, or allowing the gutenberg editor to be nested within a custom block?
Shucks, no sooner than the second I desperately resort to asking here, I run into the answer. So for anyone else who just wants a straight answer and not some 45 minute video that never gets to the point... acf_register_block_type( array( 'title' => __( 'Wrapper', 'client_textdomain' ), 'name' => 'wrapper', 'render_template' => 'partials/blocks/wrapper.php', 'mode' => 'preview', 'supports' => [ 'jsx' => true, // this is the line that makes it work ] )); That supports jsx line allows you to assign ACF fields to the wrapper and then the user can gutenberg all they want inside it. Your custom block's html needs this in it as well: <InnerBlocks /> That will enable the gutenberg interface when adding your block in the editor.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "advanced custom fields, block editor" }
Shop page custom buttons which is visible to only administrator I created two custom button in woocommerce shop page for every products, and i'm trying to do visible this two buttons only for administrator when he/she login as an administrator. ![enter image description here]( add_action( 'woocommerce_after_shop_loop_item', 'product_visibility_button', 5 ); function product_visibility_button() { echo '<div>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '</div>'; }
you can use the following code to check if a user is logged in and has a valid role. add_action( 'woocommerce_after_shop_loop_item', 'product_visibility_button', 5 ); function product_visibility_button() { if ( is_user_logged_in() ) { $user = wp_get_current_user(); if ( in_array( 'administrator', (array) $user->roles ) ) { echo '<div>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '<a class="button" style="margin:10px">BTN1</a>'; echo '</div>'; } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization" }
WordPress Gutenberg react make import of __experimentalUseInnerBlocksProps which is no more experimetal I have a plugin with import import { __experimentalUseInnerBlocksProps as useInnerBlocksProps } from '@wordpress/block-editor'; but it's not working with newest Gutenberg plugin 11.9, because this `useInnerBlocksProps` is no longer _experimental_ so I can use import { useInnerBlocksProps } from '@wordpress/block-editor'; but then it will not work for older versions, or WordPress installation without Gutenberg plugin. What's the correct way to make it compatible with both scenarios? How to import __experimentalUseInnerBlocksProps if exists and directly useInnerBlocksProps if not?
Ok, this is probably the easiest workaround I was able to find, but if someone has better idea, then feel free to post it here ;) import { __experimentalUseInnerBlocksProps, useInnerBlocksProps, } from '@wordpress/block-editor'; if( typeof useInnerBlocksProps == 'undefined' ){ var compatibleUseInnerBlocksProps = __experimentalUseInnerBlocksProps; }else{ var compatibleUseInnerBlocksProps = useInnerBlocksProps; } * so basically I can import both (experimental and no-experimental) without any error * then I can just do simple type test if the new one is already supported * if it's supported I will remember it in `compatibleUseInnerBlocksProps` variable * otherwise I will remember old _experimental_ * then I need to replace all other occurrences of `useInnerBlocksProps` with `compatibleUseInnerBlocksProps` in my code
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, plugin development, block editor, import" }
How can I get wordpress slug without certain phrase? I got this code: `<?php echo basename(get_permalink()); ?>` and I get slug of current post page example: "dog-training" And my wordpress posts are like this: domain.com/dog-training/ domain.com/dog-toys/ domain.com/dog-food/ etc. And I need to get the slug but only the part "toys", "food" and "training" so I need to get rid of the "dog-" part. Will You help me with this. I`m not a programmer ? Thanks
Previous answer here. You'll want to use `str_replace` $permalink = get_the_permalink(); $permalink = str_replace("dog-", "", $permalink);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "slug" }
How can I prevent wordpress from creating tag pages? I use the built in wp tag functionality to group my posts thematically and then I use the WP_query to have the posts displayed according to custom design. I do not need the tag pages created by default in wordpress and I would either like to have them NOT created at all (ideally) or be able to add a noindex meta to the post, as these should not be indexed separately. Is there some way to accomplish this? EDIT: one additional possibility I have looked at is to exclude all matching urls from the sitemap eg exclude all urls matchine /tag/* . I use the Yoast plugin, but I don't see any filter which would allow me to do this type of exclusion.
To redirect from the automatically-generated tag archive pages, you can check to see if `is_tag()` is true in the `template_redirect` action hook, and redirect with `wp_redirect()` if it is: add_action( 'template_redirect', function() { if ( is_tag() ) { // Currently redirects to the site's home page. wp_redirect( '/' ); // Use the 301 Permanent redirect if desired. // wp_redirect( '/', 301 ); exit; } } ); To exclude the tags from the sitemap generated by WordPress (Plan B in your question), you can use the `wp_sitemaps_taxonomies` filter. add_filter( 'wp_sitemaps_taxonomies', function( $taxonomies ) { if ( ! empty( $taxonomies['post_tag'] ) ) { unset( $taxonomies['post_tag'] ); } return $taxonomies; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tags" }
Show popover with url and option to open in new window I am creating a custom block and I want to show a button which the user can edit the text of and I want them to be able to select a page/enter a link. I have this working but using `URLInputButton` does not give the option to open in a new tab like the default wordpress popover when you highlight some text and then choose to add a hyperlink. This is what I currently have: <URLInputButton url={url} onChange={onURLChange} /> I have also played around with a popover but not sure how to put what I want in there. This just does what it says and shows text that says 'Popover is toggled!" <Button variant="secondary" onClick={toggleVisible}> Toggle Popover! {isVisible && <Popover>Popover is toggled!</Popover>} </Button>
There's no support for such a setting in `URLInputButton`/`URLInput` and those components are deprecated. Try `LinkControl`. It may be helpful to study its use in the core Button block. That seems similar to what you are building.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, block editor" }
How to change the date and time in REST API for comments? /** * Add a Formatted Date to the WordPress REST API JSON Post Object * */ add_action('rest_api_init', function() { register_rest_field( array('comment'), 'formatted_date', array( 'get_callback' => function() { return get_the_date(); }, 'update_callback' => null, 'schema' => null, ) ); }); This is not working for me. I am constantly getting the following in my JSON: "formatted_date":false," How can I show it in a format like: `"28 November 2021, 15:00"`?
In general I would be careful modifying existing endpoints, but you could try using the object passed into the callback, e.g.: 'get_callback' => function( $object ) { return date_i18n( __( 'j. F Y, H:i', 'wpse' ), strtotime( $object['date'] ) ); },
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api, api, date, date time, wp api" }
How to get tags outside of loop for specific page I'm on? Outside the loop, if I use the following code in my child theme... $mtags = get_tags(array( 'taxonomy' => 'custom_tag', 'orderby' => 'name' )); It prints out all my tags. But how can I only get tags relating to the page I am viewing?
First you need to get the ID of the page/post/content you're viewing. Then, you can call `get_the_terms()` and pass it that ID so it knows you want the tags for that specific piece of content. <?php $mtags = get_the_terms( get_queried_object_id(), 'custom_tag' ); ?> There isn't an `orderby` parameter, so you may need to sort the array afterward if you want them in a specific order.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags" }
GitHub plugins safe to use in my website? I have some question about GitHub files, I hope it is a proper place to ask. I downloaded the gravity forms from < You may know that the plugin itself is sold by min price 59$/year in its website < I am surprised if it is not free in the original website, how it can be downloaded for free at GitHub? Do you think I can use the version from GitHub without any stability and safety issues? Thanks
The GitHub repository changelog is updated until version 2.4.20. The official Wordpress is currently updated to version 3.1.25. So in answer to your question, you can see that the GitHub repository appears to be abandoned, and therefore it does pose security flaws and you won’t get updates.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, plugin gravity forms, github" }
Gutenberg: how to hide server side render output in the editor but keep it in frontend? My goal is to use the Gutenberg Block for the backend editor to collect the data but output it only with php. I added a server-side-render component to my block. Now I can edit attributes in the Gutenberg Editor and output them on the server side with php. But the output is renderer in the editor as well. I don't need that because it displays everything twice. How do I hide the server side render output in editor? Do I prevent the output in php with something like "if is_frontend() {return $output}" or is there an attribute for server side render to keep it off Gutenberg?
This can be down in the php render_function. Check if it is an API REST request: function create_block() { register_block_type( __DIR__ ,[ 'render_callback' => 'render_php' ] ); } function render_php(){ if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return "<p>Backend says hello from php</p>"; } else { return "<p>Frontend says hello from php</p>"; }; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "block editor" }
Storefront theme : Add Categoy to recent products section I want to modify the Recent Products section Storefront theme to be able to include juste a specific category. i tried that : add_filter( 'storefront_recent_products_args', 'my_custom_storefront_category_args' ); function my_custom_storefront_category_args( $args ){ $args = array( 'limit' => 8, 'columns' => 4, 'category__in' => array ('35') ); return $args; } but no success
I found it , the question is resolved : Solution : add_filter( 'storefront_recent_products_args','my_custom_storefront_category_args' ); function my_custom_storefront_category_args( $args ){ $args = array( 'limit' => 6, 'columns' => 3, 'orderby' => 'date', 'order' => 'desc', 'category' => 'your-cat-slug', 'cat_operator' => 'AND' ); return $args; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme" }
Get the URL of the page from which an ajax request has been launched within ajax callback I'm calling a server-side function written in PHP via `wp-ajax`. The server-side function eventually redirects to another page for an authentication step, and then redirects back to the initially shown page. For this to work in a generic way, I need to pass the URL from which the AJAX request was fired onto the server-side function. How can I actually do this? When I try for example this, I get the link to `wp-admin/admin-ajax.php`... I know that I could in theory use `window.href`or whatever in js and send that to the server, but I want to avoid this extra-piece of data sent, as I'm thinking that there must be some built-in wp feature for this...?
Ok got it, knew there must be some built-in WP solution to this. Simply call `wp_get_referer()` in your callback (for details, see this). At least it's working as I need it, let me know if there's any better solution. _**UPDATE**_ Thanks to @Tom J Nowell, we should also mention that referrers could get stripped for privacy reasons or similar. To thus be on the safe side, there's no way around passing the referrer's URL explicitely to the data sent across AJAX, like using `document.location.href`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, ajax, urls, site url" }
Display Ad on Specific Categories I want to display the ad only in specific categories. Can anyone help me here's the code to display the ad on all single posts/ <?php get_template_part( 'template-parts/ads/below-head' ); ?>
This will display the ad on all posts belonging to the categories listed in the array: <?php global $post; if ( in_category( array('news', 'cats', 'dogs'), $post->ID ) ) { get_template_part( 'template-parts/ads/below-head' ); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, posts" }
how to create a custom page in child theme or plugin? i'm kind of new to plugins . for a project we need to create a special form which normal plugin won't help us . we should create a special form page which insert data to db . the main problem is because of limit of modification of main theme i can not directly do changes i want. my question was is there any way to create that custom page template using plugin or child theme ? every answers will be welcomed :)
you just need to copy a Page Template from the Parent Theme into your Child Theme and rename that template with the new which you want to set into the site or create a new template PHP file add below code: <?php /* Template Name: -- Template Name -- */​ get_header(); get_footer(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, child theme" }
Redirect when not logged and parametr in link how do I redirect to 'domain.com/sub' for unlogged users, when the url is without the "one_time_login" parameter? This should not work when a user is trying to login via sub.domain.com/wp-admin. Have no idea. I understand that htaccess cant make this? Thanks for your help!
This should work for what you're looking to achieve; add_action( 'template_redirect', 'redirect_to_specific_page' ); function redirect_to_specific_page() { if ( ! is_user_logged_in() && ! is_page('one_time_login') ) { wp_redirect( 'domain.com/sub', 301 ); exit; } } This should be added to your theme (or child theme) functions.php file
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
WooCommerce get_price returning wrong price when used via ajax I'm working on a site that uses the Events Tickets plugin, and I need to get the price of a ticket (Woo product) by ID. I'm using `wc_get_product( $ticketID )->get_price();` to to do this. Adding the price to the page using the code below gives the correct price (e.g. 30): echo '<input type="hidden" id="ticketpricetest" value="' . wc_get_product( 28612 )->get_price() . '">'; However, when I try and get the price using the same method within an Ajax call it returns 300: function get_ticket_price() { $ticketID = $_REQUEST['ticketID']; echo wc_get_product( $ticketID )->get_price(); } add_action( 'wp_ajax_get_ticket_price', 'get_ticket_price' ); add_action( 'wp_ajax_nopriv_get_ticket_price', 'get_ticket_price' ); I've also tried using `get_regular_price` but that also returns 300. Any ideas what's going on here?
It's important to exit the function when using the wp_ajax hooks. Hopefully this fixes it. function get_ticket_price() { $ticketID = $_REQUEST['ticketID']; echo wc_get_product( $ticketID )->get_price(); // Don't forget to stop execution afterward. wp_die(); } add_action( 'wp_ajax_get_ticket_price', 'get_ticket_price' ); add_action( 'wp_ajax_nopriv_get_ticket_price', 'get_ticket_price' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, php, plugin development, theme development, ajax" }
Override a function defined in wp-includes/comment-template.php I need to override the function `get_cancel_comment_reply_link` or `cancel_comment_reply_link` that are defined in wp-includes/comment-template.php These functions are not listed in `pluggable.php`. **How can I override them from my theme's`functions.php`?** I tried remove_filter('get_cancel_comment_reply_link', 'cancel_comment_reply_link'); add_filter('get_cancel_comment_reply_link', function($text='') { return ''; }, 1, 1); without success.
If you look at the end of the function `get_cancel_comment_reply_link( $text = '' )` in the file `wp-includes/comment-template.php`, you see the filter `cancel_comment_reply_link`. return apply_filters( 'cancel_comment_reply_link', $formatted_link, $link, $text ); It may work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, filters, actions, pluggable" }
get_the_ID() in the footer returns wrong value I'm using `get_the_ID()` in `footer.php` but it returns a wrong value. It might come from any of the plugin which is altering The Loop without resetting it after with `wp_reset_postdata()` as mentioned in $post->ID and the_id() always return the wrong value. Indeed the page shows a list of recent posts, etc. so this might modify the current Loop. If I can't modify this (because of third party code), how to **get the ID of the current post** in the footer anyway, with PHP?
In an environment without third party code, `get_the_ID()` should give you the correct value. It sounds like some plugin is interfering with this. So you can do what they forgot and simply call wp_reset_postdata() in your footer before you need the values.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query, loop, id, get the id" }
How to make content area in full width in Twenty Twenty-One theme? I've a child Twenty Twenty-One theme and I want to make the content area in full with. I don't want to use any plugin. I've searched and found that adding following code in CSS may work but for me it's not working. How to do it with css if it is possible? .entry-content > *:not(.alignwide):not(.alignfull):not(.alignleft):not(.alignright):not(.is-style-wide) { max-width: 87rem; width: calc(100% - 8rem); }
I figured it out. It is the inherit default layout settings. First turn that off and then enter the desired width.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, theme twenty twelve" }
How to prevent sending auto emails for specific actions in wordpress How to prevent sending auto emails for specific actions in wordpress, i have a function that generate password for users, only after the admin accept the user application create_user_password($subscription->ID), //this function calls wp_update_user Wordpress sends a message about a (password change action), how to prevent this ONLY if this method was triggered by an admin
If you look in the documentation of `wp_update_user()` you will see that it uses two filters: * `send_password_change_email` * `send_email_change_email` Simply from the names I would guess if you return `false` in `send_password_change_email` it should work. So something along the lines of: function create_user_password($id) { // other code add_filter('send_password_change_email', '__return_false'); wp_update_user(...); remove_filter('send_password_change_email', '__return_false'); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "email" }
Get posts for which a custom field is not present, with get_posts I'd like to get all posts for which the custom field `hidden` is NOT present. This does not work: $postsForSitemap = get_posts(array( 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => array('post', 'page'), 'order' => 'DESC', 'meta_key' => 'hidden', 'meta_compare' => '!=') ); because `meta_compare` is about the `meta_value`, not the key. I haven't found in the documentation < how to get all posts that _don't have_ a specific custom field. How to do this?
You could use `NOT EXISTS` as the value for comparem, you could also check for empty value if thats relevant This code only checks if `hidden` meta does not exists $postsForSitemap = get_posts([ 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => ['post', 'page'], 'order' => 'DESC', 'meta_key' => 'hidden', 'meta_compare' => 'NOT EXISTS' ]; This checks is `hidden` meta does not exists OR has no value $postsForSitemap = get_posts([ 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => ['post', 'page'], 'order' => 'DESC', 'meta_query' => [ 'relation' => 'OR', [ 'key' => 'hidden', 'compare' => 'NOT EXISTS', ], [ 'key' => 'hidden', 'value' => '' ] ] ];
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, custom field, get posts" }
Converting Y-m-d to a date with a Month name? So I can easily get today's date with: echo (date("Y-m-d")); The above outputs: 2021-12-06 How do I get 2021 December 06 from the above format? P.S. I will be storing 2021-12-06 into my database. Later I will want to convert this format into the example I gave above. Thanks for your help.
You can use createFromFormat to re-format your date. Like so: $date = DateTime::createFromFormat('Y-m-d', '2021-12-06'); echo $date->format('Y F d'); If you want your output to be anything other than "2021 December 06", please check PHP datetime formats for all available formatting options.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, date" }
How do I attach a page to a category similar to how we attach media to a post? Is it possible/how do I to attach a page to a category similar to how we attach media to a post? ps. I'm not asking how to assign a category to a page. update: I need to attach a specific page contents on top of the archive of a specific category archive.
No, media is attached to posts/pages using the `post_parent` column. This works because media is actually a post of type `attachment` in the database. Categories however are not posts, and the way you would attach them is by assigning the page to that category. This leads us to a contradiction, how do you attach a page to a category without attaching it to a category? I'm sure that your original problem is solvable but this is not the solution.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, pages" }
how to add display_name from the users table to this query how to add display_name from wordpress users table to this query thanks for the help SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro FROM wp_posts a LEFT JOIN wp_postmeta b ON a.ID = b.post_id LEFT JOIN wp_postmeta c ON a.ID = c.post_id WHERE b.meta_key = 'level' AND c.meta_key = '_post_main_intro'
You should be able to do something like this, by adding in another join, and selecting the `display_name` column from that joined table: SELECT a.post_title, b.meta_key, b.meta_value as level, c.meta_value as intro, u.display_name FROM wp_posts a LEFT JOIN wp_postmeta b ON a.ID = b.post_id LEFT JOIN wp_postmeta c ON a.ID = c.post_id LEFT JOIN wp_users u ON a.post_author = u.ID WHERE b.meta_key = 'level' AND c.meta_key = '_post_main_intro' Hopefully this works for you!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How to display tags with post_content I have this code to display the content of a specific post outside the loop (actually in the archive.php template file). How do I include the tags? <?php $my_id = 1576; $post_id_1576= get_post($my_id); $content = $post_id_1576->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?>
Simply use `get_the_tags($my_id)`, example : $posttags = get_the_tags($my_id); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ' '; } } Refering to WordPress codex
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags, post content" }
Use PHP code to create custom user roles. Call it once? I have the following PHP code in my wordpress site. I have noticed that when I disable the following code, those two user roles still exists both for current and new users. /* ------------------------------ ADD NEW CUSTOM ROLES ------------------------------ */ add_role('barber',_('Barber'),array('read' => true, 'edit_posts' => true)); add_role('barber_shop',_('Barber Shop'),array('read' => true, 'edit_posts' => true)); /* ---------------------------------------------------------------------------------- */ My question is, do I need to call this code once, or should I always keep it running? Will it cause any issue in the future?
Generally, you would call this code in a plugin activation hook or at the very least, `init`. The issue you _may_ run into is calling this code too early if it's outside any specific WordPress hooks which would cause issues. That being said, `add_role()` calls `WP_Roles::add_role()` and one of the first things it does is check if it's already defined via: if( empty( $role ) || isset( $this->roles[ $role ] ) ) { return; } WordPress saves roles in the options table and grabs those roles on instantiation. If the role is already set, it's just going to return early no harm, no foul.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles" }
How to use category slug to echo a page's content with the same slug How can I fit this category slug `<?php $term = get_queried_object(); echo $term->slug; ?>` into this page content `<?php $page = get_posts([ 'name' => 'slug-goes-here', 'post_type' => 'page' ]); if ( $page ){ echo $page[0]->post_content;} ?>`
Worked it out... <?php $term = get_queried_object(); ?> <?php $page = get_posts([ 'name' => $term->slug, 'post_type' => 'page' ]); if ( $page ){ echo $page[0]->post_content; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "terms" }
Display logged in user name and lastname on page I want to display the first an lastname of my users on a welcome site. I have some code in my functions.php that let me show the first name. How can I change the code to show both first and last? This is my code for the shortcode: function custom_shortcode_func() { ob_start(); $current_user = wp_get_current_user(); echo 'Willkommen ' . $current_user->user_firstname . '<br />'; $output = ob_get_clean(); return $output; } add_shortcode('current_user', 'custom_shortcode_func');
You can always do a `var_dump()` of `$current_user` to see what it contains. You'll see there is a similar property to `user_firstname`: `user_lastname`. You'll probably want a space between the first and last name, so a small edit should add the last name: function custom_shortcode_func() { ob_start(); $current_user = wp_get_current_user(); echo 'Willkommen ' . $current_user->user_firstname . ' ' . $current_user->user_lastname . '<br />'; $output = ob_get_clean(); return $output; } add_shortcode('current_user', 'custom_shortcode_func'); As you can see you're already getting the last name and other data, so the tweak just adds a space character and the last name.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, shortcode" }
Live Streaming with Wordpress? Does anyone know a working set up for a live streaming event delivered by a wordpress page? There should be 500 participants. I have no idea, what I need to consider and which technological set up neccessary to do this. YouTube / Zoom is not an option, because the event should be delivered on an excklusive page with restricted accesss … Best and thank you.
You can use Jitsi, it’s open source and can be embedded/integrated as you require for member areas etc. Here’s an example plugin that uses it. I have no affiliation with Jitsi or the plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Add wordpress to only one domain in shared hosting with multiple domains I got a shared hosting plan with namecheap in which I'm hosting multiple domains. I want to use only one of this domains with wordpress. Can I just install Softaculous Wordpress on my cPanel with any worries. If yes, how can link the domain I want to wordpress? Will the other domains be affected by wordpress installation?
so from my experience as a WordPress developer, the only downside of the shared hosting is that that's all you got ( in terms of memory ). so if you install Wordpress from the official site and then upload it to the correct path ( let's say you have bought 3 domains: marinario.ko, marinario.com, marinario.it and the primary domain is marinario.com then inside public_html you can upload the zip of WordPress, if you want to create with WordPress one of the other domain then you have to upload it to public_html/marinario.ko lets say. then you can unzip it and move all the files directly to the folder. then you have to create a DB with a user. you can go then to marinario.com ( if you have uploaded it to public_html ) and enter all the data it wants. if you have any problem with hhtps you can add a redirect rule inside cPanel. I hope I have helped you :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hosting, shared hosting" }
Does the WordPress core software handle bounces on system email? The WordPress core sends a number of system emails, such as for password changes and for form plugins that use the WordPress core. If any of those emails bounce, does the WordPress core receive and handle them?
The quick answer: no. At least not out of the box. The bouncing email goes to the mail server and if there is no mailbox, catch-all or redirect address set, it will just bounce. You would need to connect WordPress to via pop3 or IMAP to receive emails. There is at least one plugin for using WordPress as a mail client. I am not sure how it works, so I don't know secure it is and how it (potentially) impacts WordPress performance.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "email" }
is $wpdb->get_results() safe enough #### original question if I use the get_results() functions is this safe enough from mysql injection attacks? global $wpdb; $wpdb->get_results("select * from tableA where B = C"); Or should this have some kind of prepare first? What's the best practice? How should we do it in our present time December 2021 ? #### update so I should use this instead? global $wpdb; $my_variable = "sometext"; $prep = $wpdb->prepare("select * from tableA where B = %s", $my_variable); $wpdb->query($prep);
You have to always use $wpdb->prepare() before $wpdb->query() or $wpdb->get_results() if your queries depend on dynamic variables
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "database" }
How to limit the number of images displayed in the media window? I have a lot of images in my website, so when I open `wp-admin/upload.php` the server slow down. Would be possible to display only 50 images per time? I saw there is this similar question, but it works only for the "set featured image" popup. I would like to apply the limit also to the `upload.php` window. How can I achieve that? Kind regards
maybe this other similar question (with a good answer) can help you. Change default screen option value for media items per page (in media library) And the filter to use is : function my_edit_media_per_page(){ $media_per_page = 200; //or whatever you want return $media_per_page; } add_filter( 'upload_per_page', 'my_edit_media_per_page', 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, uploads, media library" }
Using WP_Mail on MacOS 12 (Monterey - M1) On a brand new Macbook running Monterey (M1), as PHP was removed by Apple on OS 12, I have removed all "AMP" preinstalled by Apple and installed HomeBrew "AMP" (with PHP 7.4), which is running perfectly. Now, as I have setup Wordpress for testing purposes, I am attempting to use Wordpress WP_Mail function, which relies on PHPMailer, which in turn uses PHP Mail command. The latter relies on system specific libraries, and I am bit confused about configuring the correct facility, Mail, SendMail, Mailsend.... Digging the Internet, once upon a time you would achieve this through Postfix or eventually setting up an email account in the System settings for Mail.app , which I would like to avoid, as I only use web mail on browser and hate to have an email client accessing my account......... In conclusion, on a Monterey M1 machine, Homebrew "AMP" scenario, is there a way to allow PHPMailer to work, avoiding using Mail.app account?
Hi I put this function on the functions.php or in a plugin and works for me everywhere, on localhost or in any server. just need to change the strings to your email smtp settings. Only with gmail I could not make it work so far, all the other ones I try it works perfectly. // Overriding wp smtp email to send smtp emails (no spam emails) if (! function_exists('email_sender')){ add_action('phpmailer_init','email_sender'); function email_sender($mail){ $mail->SetFrom('[email protected]', 'thenameIwant to appear on the emails sended'); $mail->Host = 'smtp-mail.outlook.com'; $mail->Port = 587; $mail->SMTPAuth = true; $mail->SMTPSecure = 'STARTTLS'; $mail->Username = '[email protected]'; $mail->Password = 'mypassword'; $mail->IsSMTP(); } } then email should work like a charm! I normally use `wp_mail()` to do it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp mail, smtp" }
Automatic translation with different domains per languages? I would like to know if there is a plugin to make automatic translations with one different domain by language for the same project. For example : car.co.uk for the English voiture.fr for the French coche.es for the Spanish etc. And still have an automatic translation : If I create a new article in French on voiture.fr, there also an automatic creation and translation on the English version (car.co.uk) and on the Spanish version (coche.es) without any human actions? I know I can’t do this with Weglot (only one domain) so I’m searching an alternative… Thanks a lot for your answers!
I believe you can do this with WPML. Keep in mind that it's a paid add-on and I have not tested it myself. Check out their page here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "translation" }
How do I activate my child theme, as I do not see it in developer tools I uploaded a child theme from Astra, but the css or javascript does not display, but I was told to look if it is activated. I have looked in developer tools, and I do not see anything about a child theme there. Would anybody know, how I could activate it, if that is the problem. Thanks
You can generate your Astra child theme from here. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, child theme" }
If you have multiple dynamic blocks with a post loop on a page, how do you avoid duplicates from inside the render_callback function? I'm building dynamic blocks to customize the blog index into more of a magazine style layout, featured posts, categories, other content, all mixed together. My dynamic blocks are able to render a loop and post content just fine, but I cannot pass a list of IDs from the render_callback block function to itself when it displays multiple times on the same page, leading to duplicate posts in this block when used in various places on a page. If you have multiple dynamic blocks rendering a get_posts loop, how do you pass a list of IDs to the next instance to avoid duplicates?
In PHP I recall these ways 1. Static variables 2. Class properties 3. Databases, Files, Memory (might be flushed though) to preserve a state, in a hook's callback, that is called multiple times in WordPress and in the order I would consider using myself but it depends on the context (eg WP transients, that store data that expires, can use memory for speedy recalling and database as a fallback). Global variables might also be listed at the bottom (usually not recommended) and closure tricks closer to the top.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
Disable lazy loading on specific images Wordpress adds lazy loading on all images. Lighthouse recommends disabling lazy loading on images in above the folder. I would like to figure out how to disable it only on images that I call with wp_get_attachment_image_src in my templates, so that I can control exactly which LCP images to remove lazy load. Lighthouse documentation:
You can manage WordPress lazy loading with the `loading` parameter. Below code echo's your image without using the lazy load function. echo wp_get_attachment_image( $image, $size, false, [ 'class' => 'your-class-here', 'loading' => 'eager' ] );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "images, performance" }
splitting the URL using jQuery **Can i get the help of you guys as i want i can do it with url** I need to split the URL. and use last element as job_id, And then pass "jkdbsbd45JubJKAAASSYT" as job_Id. URL: Need to create this URL as below. Need: **Thanx in advance**
Not really a WordPress related question but you could do this // creates a object from the array, one of the properies (search) contains the query let url = new URL(' // will create a object of all availalble query properites const urlSearchParams = new URLSearchParams(url.search); const params = Object.fromEntries(urlSearchParams.entries()); // remove ? and everything after from url url = url.href.substring(0, url.href.indexOf('?')); // url + params.job_id is the final url, did a console.log so you could see it in the devtools console console.log(url + params.job_id);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "ajax, javascript, jquery, jquery ui" }
Trying to run Javascript on AJAX call I am trying to change the classes for the "View cart" button after adding an item to the cart. What I tried to do is to hook into the "woocommerce_ajax_added_to_cart" action and insert my Javascript as below but this Breaks the AJAX call. I honestly don't know if I am using the correct hook: function set_button_classes() { echo "<script>document.getElementByClassName('added_to_cart wc-forward').classList.add('ct-cart-item', 'ct-offcanvas-trigger');</script>"; } add_action( 'woocommerce_ajax_added_to_cart', 'set_button_classes', 10, 1 ); Any pointers would be really appreciated.
Found an answer on here. It does work but I am having timing issues I think. They are unrelated to the question though so I will mark the below as the answer. Thanks all. add_action( 'wp_footer', 'trigger_for_ajax_add_to_cart' ); function trigger_for_ajax_add_to_cart() { ?> <script type="text/javascript"> (function($){ $('body').on( 'added_to_cart', function(){ // Testing output on browser JS console console.log('added_to_cart'); // Your code goes here }); })(jQuery); </script> <?php }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, ajax, javascript" }
Detect if a block has been deleted I’m currently working on a slider block for the block editor. While I use custom buttons to add a slide (which is a block), I can detect when a new block has been added to tell the slider script to refresh in order to take note of the newly created block (which acts as slide). However, if I want to use the regular "delete block" action from the block's toolbar menu, I cannot find out how to detect that. I was already digging into the code and came to the conclusion that I had to detect when the action gets dispatched. However, I'm quite new to React and thus don't know how to detect the `removeBlock` dispatch action. I thought about subscribing to the store's change but I cannot figure out which store to subscribe on: const unsubscribe = subscribe( () => { console.log( store.getState().lastAction ); // which store? } ); Is this the correct way or is there something easier?
Maybe you will find this snippet helpful. I'm still searching for a better way to do this but as far as I can tell blocks are not aware of their own deletion. Instead we have to monitor the blocks from above. If you have a parent block type that has children, you can subscribe to core/block-editor and use getBlocks() to check the length of children and if the new length is lower than the old length then you have caught a deletion. const getBlockList = () => wp.data.select( 'core/block-editor' ).getBlocks(); let blockList = getBlockList(); wp.data.subscribe( () => { const newBlockList = getBlockList(); if ( newBlockList.length < blockList.length ) { console.log( 'A block was removed!!' ); } blockList = newBlockList; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor" }
How to change the link address from internal to external Look at the line below It now reads the file (script.js) from the same folder I want to replace the link to another site for example: ` wp_register_script( 'post_publisher_js', plugins_url('script.js', __FILE__), array( 'jquery' ), "1.0.2" );
Just replace `plugins_url('script.js', __FILE__)` with `'
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
I have a snippet to redirect all users to a maintenance page. How do I exclude users with admin role? I have a snippet that redirects all users to a maintenance page. How can I tweak it to All users except admin users? <?php add_action( 'template_redirect', function() { if ( is_page( 4848 ) ) { return; } wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) ); //wp_redirect( esc_url_raw( home_url( 'index.php?page_id=4848' ) ) ); exit; } );
I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, maintenance" }
Iterate over get_post_meta() result I have WordPress code like below. function get_preselect_values() { $volunteers = get_post_meta($_POST['element_id'], "volunteers", false); $users = array(); foreach ($volunteers as $volunteer) { foreach ($volunteer as $volun) { $users = $volun['ID']; } } echo json_encode($users); die; } add_action('wp_ajax_get_preselect_values', 'get_preselect_values'); add_action('wp_ajax_nopriv_get_preselect_values', 'get_preselect_values'); I am getting only the **First** value. How can I get all values ?
You're clobbering the value in the `$users` array with every iteration of the `foreach` loop. To add a new item to an array, you should use `$users[] = {...}`, not `$users = {...}`. function get_preselect_values() { $volunteers = get_post_meta($_POST['element_id'], "volunteers", false); $users = array(); foreach ($volunteers as $volunteer) { foreach ($volunteer as $volun) { $users[] = $volun['ID']; } } echo json_encode($users); die; } add_action('wp_ajax_get_preselect_values', 'get_preselect_values'); add_action('wp_ajax_nopriv_get_preselect_values', 'get_preselect_values');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "get posts" }
Will get_bloginfo('url') return URL with backslash? Based on my test, get_bloginfo('url') will not return backslash, so it will return URL like this: In this post What is difference between get_bloginfo('url') and get_site_url()?, it is said get_bloginfo('url') calls home_url(). And, in this post < it is said home_url() will return URL with backslash. So, I am confused. Anyway, I want to find a function to return URL **with** backslash.
The Codex example for home_url() says you want `home_url( '/' )` to get the blog's URL with a trailing slash. Alternatively you could use `trailingslashit( home_url() )`. That may be safer if your site's home option somehow ends up stored with a trailing slash, since it looks like get_home_url() assumes it isn't, but that ought not happen.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "urls" }
How to cut off question mark in url with functions.php I use directive .htaccess <IfModule mod_rewrite.c> RewriteCond %{QUERY_STRING} !^$ RewriteCond %{QUERY_STRING} !(^|&)appId= RewriteCond %{QUERY_STRING} !(^|&)q= RewriteRule ^(.+?)\.html$ [L,R=301] </IfModule> The problem would be solved if this `RewriteCond %{QUERY_STRING} !^$` replace with this `RewriteCond %{THE_REQUEST} \?` But this directive does **not work** on the Litespeed server. That's for sure, I contacted the developers of this server. How to cut (redirect) to a link without a question mark **via** function.php? example: if open **website.com/post-name.html?** >>>redirect>>> **website.com/post-name.html** Sorry for my English.
Try this, which uses the `parse_request` hook: (you can add other conditions, e.g. check whether `$wp->query_vars['name']` is not empty, if you want to) add_action( 'parse_request', 'wpse_400900_parse_request', 1 ); function wpse_400900_parse_request( $wp ) { // Redirect if the URL ends with a ? like if ( ! empty( $_SERVER['REQUEST_URI'] ) && ltrim( $_SERVER['REQUEST_URI'], '/' ) === "{$wp->request}?" ) { wp_redirect( home_url( $wp->request ) ); exit; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions" }
Edit post & page option does not display on latest wordpress I am not able to edit the WordPress default posts/pages from front-end. I have tried to deactivate all plugins, check/uncheck toolbar option(from profile) and also wp_footer() function in the file. But no luck any suggestion?
I have found the issue and resolved with below code. function menu_shapespace_node_landearth($wp_admin_bar) { $wp_admin_bar->remove_menu('edit'); } //add_action('admin_bar_menu', 'menu_shapespace_node_landearth', 999);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, themes, pages, wp admin, links" }
If Post Published Date or Modified Date is 1 Year or Older, Display Notice on Post Page I need a way to inform visitors if the post published date **or** modified date is older than 1 year and if so, display a message on the post page. I have added an code to my `content-single.php` file, but without the desired results in terms of checking against both published and updated time. **Example:** if (strtotime($post->post_date) < strtotime('-1 year')){ echo 'Old Post'; } else { echo 'Not Old Post'; } Any ideas as I'm in the dark here..
Right now you're just checking for the post date. You'll need to check for 'post_modified' aswell. You can find the complete post-object here: < You can modify the check to look something like this: if (strtotime($post->post_date) < strtotime('-1 year') && strtorime($post->post_modified) < strtotime('-1 year')){ echo 'Old Post'; } else { echo 'Not Old Post'; } That should check for both.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, posts, date, date time" }
How to rename custom table name programatically in wordpress? in db there are custom table name like wp_wpdf_docs and want to change table name to wp_ccdm_docs as i am using $oldtable_name = $wpdb->prefix . "wpfd_docs"; $newtable_name = $wpdb->prefix . "ccdm_docs"; $rename= $wpdb->query("RENAME TABLE ".$oldtable_name ." TO " .$newtable_name); is it right process?
Yes, you can use the `query` function to rename tables. global $wpdb; $oldTable = $wpdb->prefix . "wpfd_docs"; $newTable = $wpdb->prefix . "ccdm_docs"; $renameOk = $wpdb->query("RENAME TABLE " . $oldTable . " TO " . $newTable); if( $renameOk ) { echo 'All good'; }else{ echo 'Failed to rename table. Last DB error: ' . $wpdb->last_error; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database" }
read excel file in the dasboard programmatically To read a excel file inside wordpress, is there any function available, or we should build all using php?
> To read a excel file inside wordpress, is there any function available WordPress does not provide functions for reading spreadsheets. PHP provides functions for reading CSV files via `fgetcsv` etc, but these are for `.csv` files. If you want to open an `xls` or `xlsx` file in code, and read its contents, you will need to find a PHP library for this, or implement the code yourself. A quick search of libraries on packagist reveals multiple pages of results for the word "excel". Keep in mind that what you are asking if not a WordPress question, but a generic PHP question, you don't have to limit yourself to just WordPress to solve this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "dashboard" }