text
stringlengths
12
210k
meta
dict
Q: Changing login url I've been following this guide on how to change your login url : https://www.malcare.com/blog/change-wordpress-login-url/ However, upon adding the logout, login and lost password hooks, I've noticed that I cannot log out anymore. Whenever I log out, it just redirects me to /wp-admin without logging me out. How can I fix these issues? A: I think the article's logout hook is wrong on two or three counts: * *it needs ?action=logout, similar to the lost password link *it needs a generated nonce too *it doesn't respect the $redirect argument. Here's a new version based on the current wp_logout_url() code: add_filter( 'logout_url', 'my_logout_page', 10, 2 ); function my_logout_page( $logout_url, $redirect ) { $args = array(); if ( ! empty( $redirect ) ) { $args['redirect_to'] = urlencode( $redirect ); } $logout_url = add_query_arg( $args, site_url( 'my-secret-login.php?action=logout', 'login' ) ); $logout_url = wp_nonce_url( $logout_url, 'log-out' ); return $logout_url; }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in using 'admin_enqueue_scripts' action through a class I'm trying to separate plugin structure files by using the Best Practice method on wordpress org Best Practice. in plugins\plugin_name\public\index1.php there's the class for enqueue script <?php class Public_script { function __construct() { // get current admin screen, or null $screen = get_current_screen(); // verify admin screen object // enqueue only for specific post types // enqueue script wp_enqueue_script('wporg_meta_box_script', plugin_dir_url(__FILE__) . 'public/js/main.js', ['jquery']); // localize script, create a custom js object wp_localize_script( 'wporg_meta_box_script', 'wporg_meta_box_obj', [ 'url' => admin_url('admin-ajax.php'), ] ); wp_localize_script( 'wporg_meta_box_script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'we_value' => 1234) ); wp_register_style('wpdocsPluginStylesheet', plugins_url('public/css/style.css', __FILE__)); wp_enqueue_style('wpdocsPluginStylesheet'); } } on the main dir of the plugin plugins\plugin_name\index.php I'm tring to execute this action (Also trued with public static function) it prints this error Fatal error: Uncaught Error: Class "Public_script" not found in it's working normally if every function in one file add_action('admin_enqueue_scripts', $js_scripts = new Public_script()); A: There are several problems here: Problem 1: plugin_dir_url In a comment you mentioned using this code to load the file the class is in: define("Plugin_root", plugin_dir_url(FILE)); include_once(Plugin_root . 'public/index1.php'); This results in this value being used in include_once: include_once( 'http://example.com/wp-content/plugin/public/index1.php` ); Which is why you're getting PHP fatal errors when you try to use the class. It's very likely if you try to look at your PHP error log you'll see messages like this: PHP Warning include_once Failed opening '....' for inclusion Instead use plugin_dir_path when using require or include. Or better yet, make it work anywhere with: require_once __DIR_ . '/public/index1.php'; Since this class needs to be included, why not use require_once instead? Problem 2: Code is in the Constructor Code in the constructor runs the moment the object is created, so if you do this: add_action('admin_enqueue_scripts', $js_scripts = new Public_script()); It's the same thing as this: $js_scripts = new Public_script() add_action('admin_enqueue_scripts', $js_scripts ); Which is far too early, and results in a broken add_action instead do work in a class method/function. $js_scripts = new Public_script(); add_action('admin_enqueue_scripts', [ $js_scripts, 'your_new_do_enqueing_function' ] ); Constructors are for receiving initial variables and doing any initial setup the object needs to be able to function as an object. Aka dependency injection and initial values. You shouldn't do work as it makes the object very difficult to write unit tests for, reduces performance, and can cause problems like this one. Even better, doing it in a more OOP way you would call add_action inside the class, or in an init function: public function run() : void { add_action( 'admin_enqueue_scripts', [ $this, 'your_new_do_enqueing_function' ] ); } $js_scripts = new Public_script() $js_scripts->run(); The run function can then call all of the add_action and add_filter calls. This is similar to the boilerplate you referenced. You might see some people call add_action in the constructor, and while this works, it's not ideal as there's no way to create the object without also hooking everything in, and no way to let the object do stuff before that happens, e.g. if you wanted to check something first or enable a flag. It would all have to be done in the constructor, and you'd need to know everything before you create the object which makes things difficult if you need information that's only available after a certain hook, e.g. the is_archive() or is_single type functions Note that while classes and OOP are useful, nothing you've done here is actually object oriented programming, and there's been a misunderstanding of the WP documentation. WP isn't recommending using a class, it's recommending classes as a solution to PHP v5.2 not supporting namespaces. So for this, you could just as easily use functions and it would use less memory, run a tiny bit faster, and be much easier to understand. This is not to say that you should never use classes, they're a tool, and have a time and a place. If you actually wanted to do something that was object oriented, you'd have built a class that you could create multiple objects with, that wraps commonly used steps to make life easier. E.g. something used like this: $a = new AdminAsset( 'js/admin.js' ); $b = new AdminAsset( 'js/admin.css' ); $a->enqueue(); $b->enqueue(); Now we have an actual object that has internal state, and wraps up all the code needed to attach to the admin enqueue hook, figure out the path and URL of the file, register and enqueue it, etc. This example isn't possible with plain functions, AdminAsset has internal state, and you can have more than one of them. Likewise you could pass it additional parameters for inline assets, or create an extra function so you could so stuff like $a->add_inline_data( ... ), or functions such as is_enqueued, etc. You shouldn't force everything into OO and use classes for everything, that's a common mistake! Use OOP and classes where it has its benefits and makes sense, there is such a thing as bad OOP, and bad classes ( e.g. look at the google clean code talks on singletons, a notorious anti-pattern that unfortunately is very popular in WP agencies and plugin code ). Also take a look at the difference between pure and impure functions, sometimes a function can be far superior at certain tasks to everything else if it's written in a particular way I would also be sure to keep to WP Coding standards, so use a filename that contains the name of the class, use { on the same line not a newline, and add spaces inside parenthesis e.g. test( $var ) not test($var)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I get a 404 error on my custom post type archive pagination? When I try to set up pagination on my custom post type archive page I get a 404 if I click on the next page. The first page works fine. Any idea what I'm doing wrong? <?php get_header(); ?> <div class="archive-header"> <h1> Tesxt </div> <?php $loop = new WP_Query( array( 'post_type' => 'jobs', 'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1, 'posts_per_page' => 2 ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div <?php post_class(); ?>> <article> <div class="ort"> <?php $ort = get_field('ort'); if( $ort ): ?> <h4><?php echo esc_html( $ort->name ); ?></h4> <?php endif; ?> </div> </article> </div> <?php endwhile; $total_pages = $loop->max_num_pages; if ($total_pages > 1){ $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $loop->max_num_pages ) ); } wp_reset_postdata(); endif; get_footer(); ?> A: Why Does It Happen? It's because the number of pages in your second WP_Query is large the number of pages in the main query. So if there are 8 jobs, that's 4 pages in your custom query, and 1 page in the main query. So when you go to page 2 there is no page 2 in the main query resulting in a 404. This isn't a problem when using pre_get_posts which modifies the main query instead of creating a second one. A Solution If you remove the custom WP_Query you can revert to a standard main post loop, and standard pagination. Then, to enforce the 2 jobs per page requirement, you can use pre_get_posts to filter the main query before it goes to the database and add posts_per_page: // Lets modify the parameters on the main query // whenever you create a WP_Query this runs, including the main query! ( aka $q ) add_action( 'pre_get_posts', 'only_2_jobs_per_page' ); function only_2_jobs_per_page( \WP_Query $q ) : void { // we only want to change the frontend job post archives if ( is_admin() || ! $q->is_main_query() || ! is_post_type_archive( 'jobs' ) ) { return; } // we only want 2 jobs per page: $q->set( 'posts_per_page', 2 ); } With that your pagination will work without any of the weird hacks needed for a custom WP_Query, your code is simpler, and it'll be twice as fast! This means that this code: $loop = new WP_Query( array( 'post_type' => 'jobs', 'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1, 'posts_per_page' => 2 ) ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> Becomes: if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> And this code: $total_pages = $loop->max_num_pages; if ($total_pages > 1){ $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $loop->max_num_pages ) ); } wp_reset_postdata(); Becomes just: echo paginate_links();
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: after refresh the id that shows correct in first time click, changes to 1 I made a like post type for another post type called recipe that user can toggle for like and getting back the like. I have to get the latest like id of specific single recipe when cliked on in data-like attr. first of all when user click to the heart button it passes true id and makes a new like post with the same id and if I click again on it; likes remove and remove the like post. But if I refresh the page after like a recipe and whant to remove it , I can't! and when I use inspect for watching the ID that it must show on data-like it changes to 1. the js are correct as I know. I just share the query and the front codes of single-recipe.php if it helps. Thanks. <?php while (have_posts()) { the_post(); $likeCount = new WP_Query(array( 'post_type' => 'like', 'meta_query' => array( array( 'key' => 'liked_recipe_ID', 'compare' => '=', 'value' => get_the_ID() ) ) )); $exitStatus = 'no'; // a query for if the user liked the current recipe make data-exist to yes if (is_user_logged_in()) { $existQuery = new WP_Query(array( 'author' => get_current_user_id(), 'post_type' => 'like', 'meta_query' => array( array( 'key' => 'liked_recipe_ID', 'compare' => '=', 'value' => get_the_ID() ) ) )); if ($existQuery->found_posts) { $exitStatus = 'yes'; } } ?> <div class="like-box" data-like="<?php echo isset($existQuery->posts[0]->ID); ?>" data-exist="<?php echo $exitStatus; ?>" data-recipeID="<?php the_ID(); ?>"> <span class="like-box__heart heart-hollow"> <img src="<?php echo get_theme_file_uri() ?>/assets/images/heart-hollow.svg" alt=""> </span> <span class="like-box__heart heart-filled"> <img src="<?php echo get_theme_file_uri() ?>/assets/images/heart-filled.svg" alt=""> </span> <span class="like-count"><?php echo $likeCount->found_posts; ?></span> </div> A: It's because you're not outputting the ID into data-like: data-like="<?php echo isset($existQuery->posts[0]->ID); ?>" You are outputting whether the ID isset(), which is true, which is being turned into 1. You need to output the actual ID: data-like="<?php echo isset( $existQuery->posts[0]->ID ) ? esc_attr( $existQuery->posts[0]->ID ) : ''; ?>"
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: admin_enqueue_scripts using hook_suffix vs GET page My menu code: add_action('admin_menu', 'waf_admin_menu'); function waf_admin_menu(){ add_menu_page('WordPress Audio Filter', 'WordPress Audio Filter', WAF_CAPABILITY, 'waf_settings', 'waf_settings_page', plugins_url('assets/menu.png', __FILE__)); add_submenu_page('waf_settings', __('WordPress Audio Filter', WAF_TEXTDOMAIN), esc_html__('Global settings', WAF_TEXTDOMAIN), WAF_CAPABILITY, 'waf_settings'); add_submenu_page('waf_settings', esc_html__('WordPress Audio Filter', WAF_TEXTDOMAIN), esc_html__('Player manager', WAF_TEXTDOMAIN), WAF_CAPABILITY, 'waf_player_manager', 'waf_player_manager_page'); } I am using following code to detect page and enqueue appropriate assets for my plugin pages: add_action('admin_enqueue_scripts', 'my_admin_enqueue_scripts'); function my_admin_enqueue_scripts( $hook_suffix ) { switch ( $hook_suffix ) { case get_plugin_page_hookname( 'waf_settings', 'waf_settings' ): break; case get_plugin_page_hookname( 'waf_player_manager', 'waf_settings' ): break; } } Is this the same as using $_GET['page']? (without $hook_suffix) function my_admin_enqueue_scripts() { $page = isset($_GET['page']) ? $_GET['page'] : null; if($page && $page == 'waf_settings'){ } else if($page && $page == 'waf_player_manager')){ } }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to restrict the number of media uploads (photos) per user? I've got a community site using BuddyPress and Paid Memberships Pro where I'd like to restrict the number of files a free user can upload. I've seen it's possible as MediaPress has a paid addon, but I don't use MediaPress or rtMedia in my themes. Does anyone know of any functions to hook into that can get the counts of number of media files uploaded for the current user that I could use to limit their number of uploads? Thanks
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using a variable in page permalink I'm trying to alter some of my pages permalink by adding a variable in the permalink, it works for changing the permalink, but the link gets 404 error. My page permalink: https://example.com/top_in_YEAR_NAME My function: add_filter('page_link', function($link) { return str_replace('YEAR_NAME', '2023', $link); }); As I said, the permalink changes from YEAR_NAME to 2023, but the link gets 404 error. Is there something missing? A: As I said, the permalink changes from YEAR_NAME to 2023, but the link gets 404 error Yes, and it's because the post slug no longer matched the value in the database (in the wp_posts table, column post_name), hence the permalink URL became invalid and WordPress displayed a 404 error page. So you need to add a rewrite rule for handling the year value which replaces the TOP_NAME in the slug. Here's an example you can try, and you can change the ^top_in_2023 with ^top_in_\d{4} instead so that it matches any 4-digit year: add_action( 'init', function() { add_rewrite_rule( '^top_in_2023', // for Pages, the query var is pagename 'index.php?pagename=top_in_YEAR_NAME', 'top' ); } ); Remember to flush the rewrite rules, by simply visiting the Permalink Settings admin page.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: To perform the requested action, WordPress needs to access your web server Estoy intentando instalar un tema en WordPress pero al hacerlo me sale esto, y no se que hacer, si por favor de pueden ayudar, gracias. A: if you want to skip this popup on the every action (like plugin or theme activation) you can go to wp-config.php file and paste the code define('FS_METHOD','direct'); define("FTP_HOST", "<server>");//for eg.localhost define("FTP_USER", "<wordpress admin username>"); define("FTP_PASS", "<wordpress admin password>"); It works for me please try.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change a subsite Admin role of a WordPress Multisite after 24 hours registering please I am trying to change WordPress multisite users' role after registration. So a new user can register and create a subsite and after 24 hours the users' role changes to the subscriber role. The reason I am doing this is to make sure they submit a KYC/Means of Identification on or before 24 hours of creating the subsite. I tried with the code below, but having issues implementing the time. Please I will appreciate all contributions and support to this topic. function woo_admin_to_editor($blog_id, $user_id) { switch_to_blog($blog_id); $user = new WP_User($user_id); if ($user->exists()) { $user->set_role('subscriber'); } restore_current_blog(); } add_action( 'wpmu_new_blog', 'woo_admin_to_editor', 10, 2 ); A: You probably want the built-in cron scheduler. You've got two options: either * *set up a one-off job to downgrade the user 24 hours after registering using wp_schedule_single_event() *instead set up a daily job with wp_schedule_event() to check all blogs for users without KYC data and deactivate them if necessary. You should probably change your code above so that it checks for KYC data (stored in user meta? or a post on the site?) and also sends the user an email notification of the change too. Note that WordPress cron events only run when there's web traffic. If you have lots of traffic then that should be fine: else they'll get delayed until the next web request to the site. You might want to set up the system task scheduler to trigger cron events.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress nav Walker - Bootstrap 5.2.3 - submenu not opening I'm trying to integrate WordPress Nav Walker with a two level dropdown, so: URL -URL2 --URL2 --URL23 I am using this code: wp_nav_menu(array( 'theme_location' => 'main-menu', 'container' => false, 'menu_class' => '', 'fallback_cb' => '__return_false', 'items_wrap' => '<ul id="%1$s" class="navbar-nav me-auto mb-2 mb-md-0 %2$s">%3$s</ul>', 'depth' => 0, 'walker' => new bootstrap_5_wp_nav_menu_walker() )); And this for the nav-walker: class bootstrap_5_wp_nav_menu_walker extends Walker_Nav_menu { private $current_item; private $dropdown_menu_alignment_values = [ 'dropdown-menu-start', 'dropdown-menu-end', 'dropdown-menu-sm-start', 'dropdown-menu-sm-end', 'dropdown-menu-md-start', 'dropdown-menu-md-end', 'dropdown-menu-lg-start', 'dropdown-menu-lg-end', 'dropdown-menu-xl-start', 'dropdown-menu-xl-end', 'dropdown-menu-xxl-start', 'dropdown-menu-xxl-end' ]; function start_lvl(&$output, $depth = 0, $args = null) { $dropdown_menu_class[] = ''; foreach($this->current_item->classes as $class) { if(in_array($class, $this->dropdown_menu_alignment_values)) { $dropdown_menu_class[] = $class; } } $indent = str_repeat("\t", $depth); $submenu = ($depth > 0) ? ' sub-menu' : ''; $output .= "\n$indent<ul class=\"dropdown-menu$submenu " . esc_attr(implode(" ",$dropdown_menu_class)) . " depth_$depth\">\n"; } function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) { $this->current_item = $item; $indent = ($depth) ? str_repeat("\t", $depth) : ''; $li_attributes = ''; $class_names = $value = ''; $classes = empty($item->classes) ? array() : (array) $item->classes; $classes[] = ($args->walker->has_children) ? 'dropdown' : ''; $classes[] = 'nav-item'; $classes[] = 'nav-item-' . $item->ID; if ($depth && $args->walker->has_children) { $classes[] = 'dropdown-menu dropdown-menu-end'; } $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args)); $class_names = ' class="' . esc_attr($class_names) . '"'; $id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args); $id = strlen($id) ? ' id="' . esc_attr($id) . '"' : ''; $output .= $indent . '<li ' . $id . $value . $class_names . $li_attributes . '>'; $attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '"' : ''; $attributes .= !empty($item->target) ? ' target="' . esc_attr($item->target) . '"' : ''; $attributes .= !empty($item->xfn) ? ' rel="' . esc_attr($item->xfn) . '"' : ''; $attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) . '"' : ''; $active_class = ($item->current || $item->current_item_ancestor || in_array("current_page_parent", $item->classes, true) || in_array("current-post-ancestor", $item->classes, true)) ? 'active' : ''; $nav_link_class = ( $depth > 0 ) ? 'dropdown-item ' : 'nav-link '; $attributes .= ( $args->walker->has_children ) ? ' class="'. $nav_link_class . $active_class . ' dropdown-toggle" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"' : ' class="'. $nav_link_class . $active_class . '"'; $item_output = $args->before; $item_output .= '<a' . $attributes . '>'; $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args); } } // register a new menu register_nav_menu('main-menu', 'Main menu'); Now I can get the menu to show up. On mobile even to open up. However, I can't get any of the sublevel menu items to show. My problem is I don't know what to look for. Can't exactly figure out if it is related to css, the walker, or bootstrap in general. For my menu items with sub-menu, I can see that the aria-dropdown is visible. If I click on them and inspect, I see the following three parameters flashing, like their classes should update, but they don't change: "nav-link dropdown-toggle" aria-expanded="false" and the ul under it containing the sub menu also flashes: "dropdown-menu depth_0" So nothing changes and I don't receive any errors. Any suggestions are appreciated. A: Managed to fix. Bootstrap.js was loaded in footer, causing an issue in the layout. Also, bs nav walker does no work with multilevel nesting. (I had to remove nested items from 2nd level, and the menu started working)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading newest dependency javascript module file in functions.php Continuing from this question: I have scripts enqueued in functions.php file so scripts load only on certain pages (I cut most of them in code below): add_action( 'template_redirect', 'plugin_is_page' ); function plugin_is_page() { if ( is_search() ) { wp_enqueue_script('ads-search', get_template_directory_uri() . '/js/ads-search.js', array( 'ads' ), $timestamp = filemtime( plugin_dir_path( __FILE__ ) . '/js/ads-search.js' ), true); } } Now, each of them uses dependency ads.js file witch contains array of objects (ads) and functions to display them. In files like ads-search.js, I only call said functions on search results page. I need to load latest version of each file every time (every time it changes). For now it is enqueued like this, with banners.js file it loads on every single page. function my_custom_theme_scripts() { $ads_version = filemtime( get_stylesheet_directory() . '/js/ads.js' ); $banners_version = filemtime( get_stylesheet_directory() . '/js/ads-banners.js' ); wp_enqueue_script( 'ads', get_stylesheet_directory_uri() . '/js/ads.js', array(), $ads_version, true ); wp_enqueue_script( 'ads-banners', get_stylesheet_directory_uri() . '/js/ads-banners.js', array( 'ads' ), $banners_version, true ); } add_action( 'wp_enqueue_scripts', 'my_custom_theme_scripts' ); So how do I use functions coded in dependency ads.js file across all my scripts like ads-banners.js or ads-search.js? Importing them wont work even if I load scripts as modules, because then I would need to include version in import line and doing just import { selectADS, sidebarADS, mobileADS } from "./ads.js"; won't work. All functions are coded in the same way, example one: export async function selectADS(adNumber, element, adsArray) { let usedNum = []; let i = 0; while (1) { var randomNum = Math.floor(Math.random() * adsArray.length); if (!usedNum.includes(randomNum)) { let link = document.createElement("a"); link.setAttribute("href", adsArray[randomNum].link); link.setAttribute("target", "_blank"); let ad = document.createElement("img"); ad.setAttribute("alt", adsArray[randomNum].alt); ad.setAttribute("src", adsArray[randomNum].src); element.appendChild(link); link.appendChild(ad); usedNum.push(randomNum); i++; if (i == adNumber) break; } } } When I try to call selectADS in another file it throws function is not defined error. So, how can I enqueue modules in WordPress, so that live changes to ads.js file in loaded properly without error? A: The problem Import statement like: import { export1 } from "./module-name.js"; is called static import declaration. Dynamic query string (to force load the latest file) cannot be used in static import declarations. So, to solve this problem, you'll have to choose one of the following four options: * *Remove export and import statements from all the JavaScript files and enqueue them as non-module JavaScript. *Don't enqueue ads.js in WordPress, only pass version number of ads.js file as a JavaScript global variable with wp_add_inline_script() function to the page, and dynamically import ads.js as a module from banners.js and ads-search.js. *Enqueue ads.js as a module, pass version number of ads.js file as a JavaScript global variable with wp_add_inline_script() function to the page, enqueue banners.js and ads-search.js as non-module JavaScript (with ads.js in the dependency array), and dynamically import ads.js as a module from banners.js and ads-search.js. This is slightly different from option-2 and may have some benefits depending on implementation. *Use a bundler like Rollup or Webpack and build a single minified script using a file watcher and enqueue the build minified JavaScript file in WordPress as a non-module JavaScript file. I'd recommend this method, but would not explain it here as it out of the scope of this question. Option-1: Make all JS files non-module Just remove export and import statements from all the JavaScript files, like below: // in ads.js // removed the export declaration async function selectADS(adNumber, element, adsArray) { let usedNum = []; let i = 0; while (1) { var randomNum = Math.floor(Math.random() * adsArray.length); if (!usedNum.includes(randomNum)) { let link = document.createElement("a"); link.setAttribute("href", adsArray[randomNum].link); link.setAttribute("target", "_blank"); let ad = document.createElement("img"); ad.setAttribute("alt", adsArray[randomNum].alt); ad.setAttribute("src", adsArray[randomNum].src); element.appendChild(link); link.appendChild(ad); usedNum.push(randomNum); i++; if (i == adNumber) break; } } } // in banners.js // call selectADS function normally, no import declaration selectADS(); Then in the WordPress end, enqueue them in my_custom_theme_scripts() as you've written in the question. Option-2: pass ads.js version to JS & dynamically import ads.js If for some reason you have to keep the export declaration in ads.js, and still want to import the latest file in banners.js and ads-search.js, you'll need to make some changes in WordPress enqueue code and in the JavaScript code of banners.js and ads-search.js. For example, your my_custom_theme_scripts() function can be like this: function my_custom_theme_scripts() { $ads_version = filemtime( get_stylesheet_directory() . '/js/ads.js' ); $banners_version = filemtime( get_stylesheet_directory() . '/js/banners.js' ); wp_enqueue_script( 'banners', get_stylesheet_directory_uri() . '/js/banners.js', array(), $banners_version, true ); wp_add_inline_script( 'banners', 'const My_Custom_Ads_Version = "' . $ads_version . '";', 'before' ); } In this case, ads.js file can be like before with export declaration, and banners.js file can dynamically import it like below: (async () => { if( typeof My_Custom_Ads_Version !== 'undefined' ) { const adsModule = await import( `./ads.js?ver=${My_Custom_Ads_Version}` ); const selectADS = adsModule.selectADS; selectADS(); } })(); You'll have to make similar changes to ads-search.js. After that your code will work. Remember, in this case export declarations can be like before (in ads.js), but the import statements in banners.js and ads-search.js should be changed from static import declaration to dynamic import statements as shown in the code above. Option-3: Enqueue ads.js as a module, pass ads.js version to JS & dynamically import ads.js This option is very similar to option-2 above. However, option-2 imports ads.js in runtime. So if an implementation wants to delay the execution of ads.js module objects, but still wants to load the ads.js module with page load, then this implementation will be preferable. To do this, you'll have to first hook into script_loader_tag filter, so that WordPress adds type="module" in <script> tag. Following is an example WordPress code that implements it: add_filter( 'script_loader_tag', 'my_custom_module_support', PHP_INT_MAX, 2 ); function my_custom_module_support( $tag, $handle ) { if( strpos( $handle, 'my_custom_module_' ) === 0 ) { if( current_theme_supports( 'html5', 'script' ) ) { return substr_replace( $tag, '<script type="module"', strpos( $tag, '<script' ), 7 ); } else { return substr_replace( $tag, 'module', strpos( $tag, 'text/javascript' ), 15 ); } } return $tag; } function my_custom_theme_scripts() { $ads_version = filemtime( get_stylesheet_directory() . '/js/ads.js' ); $banners_version = filemtime( get_stylesheet_directory() . '/js/banners.js' ); // we are loading ads.js as a module. // my_custom_module_support() function checks any handle // that begins with "my_custom_module_" and adds type="modle" // to print it as a ES6 module script wp_enqueue_script( 'my_custom_module_ads', get_stylesheet_directory_uri() . '/js/ads.js', array(), $ads_version, true ); wp_add_inline_script( 'my_custom_module_ads', 'const My_Custom_Ads_Version = "' . $ads_version . '";' ); wp_enqueue_script( 'banners', get_stylesheet_directory_uri() . '/js/banners.js', array( 'my_custom_module_ads' ), $banners_version, true ); } add_action( 'wp_enqueue_scripts', 'my_custom_theme_scripts' ); With this option as well, ads.js file can be like before with export declaration, and banners.js and ads-search.js can dynamically import from ads.js as shown in option-2 above. However, with this option, the browser will load ads.js module file before it is imported dynamically in banners.js. So when the dynamic import is performed, the browser will just use the already loaded file. In most cases this is not significant. However, it can be significant when you perform the dynamic import on an event like below code (especially if ads.js file takes significant time to load): // sample ads.js code console.log( 'ads.js loaded:START' ); export async function selectADS( adNumber, element, adsArray ) { console.log( 'ads.js as a module loaded' ); }; console.log( 'ads.js loaded:END' ); // banners.js code console.log( 'banners.js load:START' ); let clicked = false; document.addEventListener( 'click', async (event) => { if( ! clicked && typeof My_Custom_Ads_Version !== 'undefined' ) { const adsModule = await import( `./ads.js?ver=${My_Custom_Ads_Version}` ); const selectADS = adsModule.selectADS; selectADS(); } clicked = true; }); console.log( 'banners.js load:END' ); With this implementation, if the ads.js file is significantly large and it's only dynamically imported on an event, code becomes simpler without having to wait for the imported file. However, this is not the most significant advantage, because you can rewrite that JS code to still import early. More significant advantage of this implementation is if you use a caching system or a bundler that watches changes in HTML code. With this option it's easier to handle such scenario as opposed to option-2 (because with option-2 adj.js is not visible from HTML).
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: With full-site-editing menus, how do I create a non-linking top-level menu item with linking sub-pages I did this all the time pre-full-site-editing, back when we all built menus under Appearance. But without the Menu option under Appearance anymore, how do I do this? Is it only possible by way of a home-rolled function in functions.php or in javascript? I tried a function under add_filter( 'wp_nav_menu_items', 'delink_menu_item', 10, 2 ); but there were no $items or $args. Does FSE use a new function or filter? I could do this with jQuery, but not my favorite approach. Thoughts? A: The new FSE editor uses a new filter, if you want to hook into that you can do it in two ways: By hooking the individual block rendering: add_filter( 'render_block_core/navigation-link', 'test_render_navigation_link', 10, 3); function test_render_navigation_link($block_content, $block) { $attributes = $block["attrs"]; // string replace the href if you want, by checking the content of $attributes return $block_content; } or by hooking the prerender for the entire navigational menu: add_filter( 'block_core_navigation_render_inner_blocks', 'replace_nav_blockitem_href'); function replace_nav_blockitem_href( $items ) { // Loop through the items (they are nested) foreach ($items as $key => $item) { //recursive loop through $item->inner_blocks //once you have found your item then set the attribute url to empty $item->parsed_block["attrs"]["url"] = null; } return $items; } The rendering of the navigation item will not output the href if the url is empty, this can be seen in the source code of the rendering: https://github.com/WordPress/wordpress-develop/blob/0cb8475c0d07d23893b1d73d755eda5f12024585/src/wp-includes/blocks/navigation-link.php#L173 This is the line where the first filter is called: https://github.com/WordPress/wordpress-develop/blob/28f10e4af559c9b4dbbd1768feff0bae575d5e78/src/wp-includes/class-wp-block.php#L306 This is the line where the second filter is called: https://github.com/WordPress/wordpress-develop/blob/0cb8475c0d07d23893b1d73d755eda5f12024585/src/wp-includes/blocks/navigation.php#L512 A: In the end it was too easy to turn to jQuery. I saved it to a .js file, enqueued it, now good to go: var $j = jQuery.noConflict(); $j(function() { //remove link from top-level menu items $j('ul.wp-block-page-list li.has-child > a').removeAttr('href'); });
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Plugin to transfer new/updated files from media library in "/wp-content/uploads/" between prod environment and preprod environment? I'm looking for a WordPress plugin that transfer data from a prod environment to a preprod environnement, but only the files that are new or updated in the /wp-content/uploads/ folder. Something that do it in one click once configured, and where I can planned it every week for example. I found "Migrate Guru" which seems free but it transfers everything from one environment to another instead of just the content of /wp-content/uploads/ folder from my understanding. Then I found WP Migrate with its feature "media library migrations" which is exactly what I'm looking for but does anyone know an alternative that is cheaper/free? (I'm looking for something that do it automatically and doesn't require to generate a file in order to transfer it, I don't know if it's possible)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: theme.json should be in the child theme folder when using xxxx.json style located in the styles folder? I'm making a child theme of TT3. I'm using a json style in my child theme located in a styles named folder. Do I have to have a copy of TT3 theme.json in my child theme ? A: Short answer: No Long answer: The child themes theme.json will simply use the TT3 theme.json values if a specific value is not found. So you can make a new theme.json file only with the specific values needed for the child theme. An excellent writeup is available here: https://kinsta.com/blog/twenty-twenty-two-theme/#extending-twenty-twentytwo-with-a-child-theme
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Per-Day booking with customer-supplied start time using Woocommerce Bookings I am using WooCommerce Bookings (https://woocommerce.com/products/woocommerce-bookings/) to offer rentals of equipment on my website. The rentals must be "per day", so that we have time to retrieve the equipment and service it/clean it for the next renter. This can be set up using the "Fixed Blocks of 1 Days" setting. However, I also need to ask the customer for their desired start time for the date they are choosing. For example, I want them to be able to pick up the equipment any time between 10am and 6pm, in one hour increments. I can get those increments added to the front-end select options if I change to "Fixed Blocks of 1 Hours" and set the Store Availability "Time Range" settings accordingly, but this then allows one customer to select "Friday February 17 at 10am" and another customer to select "Friday February 17 at 11am". I need it to be so that if a customer selects "Friday February 17 at 10am", no other customer can choose any other time on Friday February 17. Does anyone know if there is a recipe of settings for it to function in this way? If not, is there another booking plugin that would meet those needs? I have considered adding an attribute/field to collect their desired start time, but I don't think that will be compatible with the plugin's Google Calendar integration. If I use the "Days" instead of the "Hours" setting, then the rental is added to Google Calendar as an "All Day" event, instead of adding it at a specific time. A: Yes, you can achieve this functionality with WooCommerce Bookings. Here's how you can set it up: * *Set the Bookable product duration to "Fixed Blocks of 1 day" under Booking duration. *Set the minimum and maximum block duration to 1 day. *Set the Booking window to the number of days in advance customers can make a reservation. *Under Availability, select "Time Slots" and set the "Time slot calculus" to "Customer defined". *Set the time range to 10am to 6pm, with 1-hour time slots. *Under Resources, add a resource for each equipment item available for rent. *Under Persons, set "Enable person types" to "Yes" and create a person type called "Renter". *Set the minimum and maximum persons to 1 and 1, respectively. *Under Costs, set the cost per day for each equipment item. *Under Booking meta, add a custom field for "Desired Start Time" and set it to display on the checkout page. With these settings, customers can select the day they want to rent the equipment and choose a start time between 10am and 6pm. Once a start time is selected, that time slot will no longer be available for other customers to book. Regarding the Google Calendar integration, the booking will appear on the calendar at the start time selected by the customer. However, the end time will be calculated based on the duration of the booking (which is set to 1 day in this case). If you need to include the end time on the Google Calendar event, you may need to look into customizing the integration or using a different booking plugin that better meets your needs.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The Best Multilanguage Plugin supporting the FSE Background I have been managing Wordpress sites (and multisite sites) for more than a decade and a half now, and for some reason this is the first time I really had to look into running WordPress in a multilanguage setup. The project is for a small advisory business where all employees will probably edit some or all of the website at some point, in both the two starter languages. The most important for me is simplicity of editing, integration into the FSE (as the site has just been rebuilt on top of the twenty twenty-three theme) and Woocommerce support. Also we want to support having the languages on different domains, ie. sample.de, and sample.us For each language it is not wanted that the design of the pages change, only the text. However it is expected that there will be lots of small changes all the time, rephrasing something in one language or fixing small mistakes in the other. Investigation status I have looked into the following existing multi language plugins and have found issues with all of them: * *WPML - the Rome of all search results for Wordpress multilanguage. * *It is string (or full page) based, which means any small change in the primary language will invalidate all translations (or design changes will only affect one language). *It does not have great interface (i.e. support for the FSE sucks) *TranslatePress - the pretty one. * *It is also string based *WPGlobal * *It does not support FSE *While it is not string (replacement based) it saves the content inside the text and filters it on the output, its a clever trick and could be a fine solution (they could steal some of the ideas from below to support FSE) *If plugin is deactivated all text will be messed up, and show all translations. Question Am I missing something completely obvious (another plugin or setting on the above plugins) A: Proposed solution - a new plugin A new plugin built around the blocks and possibilities of the block editor. Having translations done within the FSE / Block Editor. The description below will focus on the translations of the Block items, because solving non-block based items is probably really easy since all multilanguage plugins already do it. Technical overview * *Block attributes will contain references to translations *Translations will contain the full block content and it will be the choice of the editor if they want to translate blocks with children or only the lowest level. *When rendering blocks the correct translated item will be fetched from the translation table. *In order to speed things up we should hook into a general page hook just before individual block rendering, fetch all block translate ids, get all translations in a single query (for the currently selected language), store them in a memory variable and use that variable when rendering the blocks - that will cause only a single extra SQL lookup per page/post *This will also mean if the plugin is deactivated all content will continue to work without any cleaning necessary Sample block Block content <!-- wp:paragraph {"translation":{"id": "idofdatabaseitem", "temp" : { "currentlanguage": "de", "pageid": 123}}} --> <p class="_text_highlighted">This is the currently displayed language</p> <!-- /wp:paragraph --> Issues that needs to be addressed * *We must hook the onload/onpublish/onsave of the FSE to make sure as possible that the stored content of a post is the base language (for page rendering it should not matter as we will just get the content from the database) however we want to make sure that the editor has a consistent content. *We must hook the FSE in order to load the correct block content for the selected editing language. It is possible to hook into existing block editors like this (https://mariecomet.fr/en/2021/12/14/adding-options-controls-existing-gutenberg-block/) *We must hook copy/paste for copy paste operations in the same page as we want to duplicate translations and not link them to the old ones *We must hook copy/paste or page duplicate or maybe better make sure to keep track of which page ID a translated block belongs to (so in the translations table keep ID, page_ID, content) so we can detect when a block is a copy from another page and we can duplicate the translations. Next Step * *Do you think this is possible? *Should we do this together? *Other questions or comments? A: You have already looked into some of the most popular multilingual plugins for WordPress, and you have rightly pointed out some of their limitations. Here are a few more options you could consider: Polylang: This is a popular multilingual plugin that has been around for a long time. It allows you to create a multilingual website with posts, pages, custom post types, and taxonomies. You can translate the content or have separate content for each language. Polylang also supports WooCommerce, and you can have different currencies and prices for each language. It has a user-friendly interface, and it is compatible with the block editor (Gutenberg). Polylang also allows you to use different domains for each language. Weglot: Weglot is a cloud-based multilingual plugin that uses machine translation to translate your website. It is easy to set up, and you can have a multilingual website in a matter of minutes. Weglot also supports WooCommerce, and you can have different currencies and prices for each language. You can translate the content manually, edit the machine translation, or hire professional translators. Weglot has a user-friendly interface and works well with the block editor (Gutenberg). It also allows you to use different domains for each language. MultilingualPress: This is another popular multilingual plugin that allows you to create a multilingual website with separate content for each language. MultilingualPress uses a network of WordPress installations to create a multilingual website, which means that each language has its own WordPress site. This allows you to have complete control over the content for each language. MultilingualPress also supports WooCommerce, and you can have different currencies and prices for each language. It has a user-friendly interface and is compatible with the block editor (Gutenberg). MultilingualPress also allows you to use different domains for each language. It's important to note that all of these plugins have their pros and cons, and you should choose the one that best fits your needs and preferences. It's also important to thoroughly test any multilingual plugin before using it on a live site to make sure it meets your requirements.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set the title of a custom post automatically by using info from custom fields? I've set up a CPT via a plugin, including custom fields for first and last name, so I'd like to automatically make the post title "First Name + ' ' + Last Name". This post almost got me there: How To Set Custom Post Type Title Without Supports But my version (adapted code below) creates a title called "Array Array". add_filter( 'save_post_practitioners', 'hexagon_practitioner_set_title', 10, 3 ); function hexagon_practitioner_set_title ( $post_id, $post, $update ){ //This temporarily removes filter to prevent infinite loops remove_filter( 'save_post_practitioners', __FUNCTION__ ); //get first and last name meta $first = get_metadata( 'first_name', $post_id ); //meta for first name $last = get_metadata( 'last_name', $post_id ); //meta for last name $title = $first . ' ' . $last; //update title wp_update_post( array( 'ID'=>$post_id, 'post_title'=>$title ) ); //redo filter add_filter( 'save_post_practitioners', __FUNCTION__, 10, 3 ); } I've delved into the functions involved but there seem to be many competing solutions that aren't quite what I'm looking for. What am I getting wrong? Thanks! A: The issue with your code is that the get_metadata() function returns an array of values, not a single value. So when you concatenate $first and $last variables in this line $title = $first . ' ' . $last;, you are actually concatenating two arrays, which results in the "Array Array" title. To fix this, you can use the get_post_meta() function instead of get_metadata() to retrieve the first and last name values as follows: $first = get_post_meta( $post_id, 'first_name', true ); //meta for first name $last = get_post_meta( $post_id, 'last_name', true ); //meta for last name The third parameter true in the get_post_meta() function specifies that you want to retrieve a single value instead of an array of values. Here's the updated code: add_filter( 'save_post_practitioners', 'hexagon_practitioner_set_title', 10, 3 ); function hexagon_practitioner_set_title ( $post_id, $post, $update ){ //This temporarily removes filter to prevent infinite loops remove_filter( 'save_post_practitioners', __FUNCTION__ ); //get first and last name meta $first = get_post_meta( $post_id, 'first_name', true ); //meta for first name $last = get_post_meta( $post_id, 'last_name', true ); //meta for last name $title = $first . ' ' . $last; //update title wp_update_post( array( 'ID'=>$post_id, 'post_title'=>$title ) ); //redo filter add_filter( 'save_post_practitioners', __FUNCTION__, 10, 3 ); } This should set the post title to "First Name Last Name" as you intended. A: Try setting the 'single' parameter to true. It's the 4th parameter and defaults to false which returns an array, and thus you got Array Array because you did not set that parameter (to true). Additionally, you incorrectly used get_metadata() and received either an empty array or an array of all metadata (first_name, last_name, etc.) for the specific post. See the documentation for the correct syntax, where the 1st parameter is actually the meta type and not the meta key/name: https://developer.wordpress.org/reference/functions/get_metadata/ So in your case, the meta type is post, and the correct syntax is: $first = get_metadata( 'post', $post_id, 'first_name', true ); $last = get_metadata( 'post', $post_id, 'last_name', true );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Restore posts, but only posts that exist in my database backup This is my situation. On 1 Jan 2023 I took a backup on my entire Wordpress database. Let's say that backup contains 100 posts. Fast forward to today, 14 Feb, and I now have say 125 posts in my Wordpress installation. If I want to restore/over-write the contents of those original 100 posts as at 1 Jan, how do I do that while keeping the 25 "new" posts untouched? Obviously all the images I uploaded in the interim will still be on the server too. It's literally just replacing the post body (i.e. no other meta data, not even the titles) of those 100 original posts using the 1 Jan backup. A: You can import the old wp_posts table in your current database with different table name, query and loop through it then update the current wp_posts post_content column from the old table where the ID matches. Here's an example SQL which you can directly do inside phpMyAdmin (this updates everything in single query) UPDATE wp_posts SET post_content = ( SELECT post_content FROM temporary_old_wp_posts_backup_table_name WHERE `temporary_old_wp_posts_backup_table_name`.`ID` = `wp_posts`.`ID` LIMIT 1 ) /* just making sure the ID exists on old post table ID*/ WHERE EXISTS( SELECT 1 FROM temporary_old_wp_posts_backup_table_name WHERE `temporary_old_wp_posts_backup_table_name`.`ID` = `wp_posts`.`ID` ) /* probably need a filter to only update post_type = post*/ AND post_type = 'post' Another options is to export the wp_posts from the back-up to a CSV file, loop and read each row and do the same as above (update the post_content of the current post table if ID matches with the id on your csv rows) Remember to back-up your current database before playing with it. You can also export and import your current database in a new wp install which you can play before running it on live database.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yoasts plugin sitemap not detecting correct category URL format My client wants the following URL: https://example.com/category-name So for that, I added . in the Category base under Settings > Permalinks and now my Category URL looks like how the client wants it: https://example.com/category-name/ However, the category sitemap generated by Yoasts shows like this: https://example.com/./category-name/ How can I resolve this? Google isn't crawling the above category URLs and I'm assuming this is the reason for it. I'm getting "Sitemaps: No referring sitemaps detected" on Google Search Console. A: Adding a . may be a bad idea. This issue may be causing Google to not crawl your category URLs, which can result in the "Sitemaps: No referring sitemaps detected" message you're seeing in Google Search Console. It's important to note that any changes to your permalink structure can impact your website's SEO, so make sure to test everything thoroughly and set up proper redirects if necessary.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any performance difference between duplicating composer packages among multiple plugins and not doing it? How can I avoid it? The whole point of PHP Composer is to handle dependencies in a clean way, so that developers don't need to care about duplication, updates, and instantiating the necessary classes when needed. But there is a case within WordPress, in which I don't understand what goes on with the part that corresponds to duplication. Let's say there are multiple WordPress plugins which require a certain package (for example the Stripe SDK)... I effectively have duplicated copies of the Stripe SDK, since it will live in each plugin's vendor folder. I guess, that's the only way to go about it, for plugins published in the directory. But I wonder how this affects the site performance and if there is anything I can do for my own plugins that I don't host on the WP directory (and hence I know I have to deal with dependencies myself). Note that I am not talking about this: Multiple versions using composer I am specifically talking about the described scenario within the WordPress environment, and if there is anything I could do to avoid having duplicates, like for example create a third plugin whose only job is to load the Stripe SDK, would that make sense? A: There are no performance issues with duplicating composer packages. If you look at the file vendor/composer/autoload_classmap.php, you will see lines like these: <?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', 'Codeception\\Exception\\ConnectionException' => $vendorDir . '/codeception/module-webdriver/src/Codeception/Exception/ConnectionException.php', ... Being loaded during composer activation, this film establishes a mapping of namespaces to certain folders. A similar meaning has the file vendor/composer/autoload_psr4.php. Now let us look at the situation when two plugins (A and B) have the same packages (Stripe SDK, for instance). When plugin A is loaded, the composer establishes the mapping of the Stripe SDK namespace to a folder in plugin A. During the loading of plugin B, its class mapping of the SDK is ignored, and plugin B uses Stripe SDK from plugin A. Plugins are loaded in alphabetic order, so SDK from plugin A will always be used when both plugins are active. If you deactivate plugin A, SDK from plugin B will be used in B. This causes an evident problem if plugins A and B have different SDK versions. If B tends to use a higher SDK version and tries to use a method which does not exist in an older version (which is in A), it will cause a fatal error. To avoid this possibility, some very advanced packages, like Action Scheduler by Automattic, have a dedicated code allowing to load a small portion of the package from all plugins and later, on a hook, determine the highest available version of Action Scheduler and load it. But from the performance point of view, class autoloading has no issues. SDK is loaded only once, and we have no excessive memory consumption. You can check it by the following mu-plugin: <?php use Symfony\Polyfill\Php80\Php80; function my_autoload_test() { if ( ! class_exists( Php80::class ) ) { return; } $php80 = new Php80(); $reflector = new ReflectionClass( $php80 ); error_log( $reflector->getFileName() ); } add_action( 'init', 'my_autoload_test' ); Install and activate two well-known plugins: BackWPup and WooCommerce. Both use the same package, symfony/polyfill-php80. The code above logs where the class Php80 is used from. When both plugins are active, we have a path like ...\wp-content\plugins\backwpup\vendor\symfony\polyfill-php80\Php80.php. When we deactivate BackWPup, we have a path like ...\wp-content\plugins\woocommerce\vendor\symfony\polyfill-php80\Php80.php. Composer is a great tool to load packages only once and prevent memory bloating.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PayPal button not showing and cannot retrieve order error in PayPal I am having a big issue and I tried everything best to solve this issue but unfortunelyy I cannot. I need you guys to help me to solve this issue I have enable the woo commerce in my client website, but I am facing problem in checkout page since the payment option are not working as per the need. I have created a custom theme and enabled woo commerce in there. I am using a woo commerce PayPal plugin but, the PayPal button are not displaying in my site and also logo are not there. Did I messed up something or where do I did wrong ? page I need help is https://www.ghdcollection.com/ Normally a PayPal button will be like this but i am getting this Also I am getting this error in my console,
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quick Edit on taxonomy names results in error If I press Quick Edit to the terms, inside a category or taxonomy I get a 0 as a result. You can look screenshot here: // Register custom taxonomy - Marker categories. function markerCategories() { $labels = array( 'name' => _x( 'Category', 'Taxonomy General Name', 'guten' ), 'singular_name' => _x( 'Category', 'Taxonomy Singular Name', 'guten' ), 'menu_name' => __( 'Category', 'guten' ), 'all_items' => __( 'All categories', 'guten' ), 'parent_item' => __( 'Parent category', 'guten' ), 'parent_item_colon' => __( 'Parent category:', 'guten' ), 'new_item_name' => __( 'New category name', 'guten' ), 'add_new_item' => __( 'Add category', 'guten' ), 'edit_item' => __( 'Edit category', 'guten' ), 'update_item' => __( 'Update category', 'guten' ), 'separate_items_with_commas' => __( 'Separate categories with commas', 'guten' ), 'search_items' => __( 'Search category', 'guten' ), 'add_or_remove_items' => __( 'Add or remove category', 'guten' ), 'choose_from_most_used' => __( 'Choose from the most used categories', 'guten' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); register_taxonomy( 'markerCategories', 'googleMapMarkers_customPostType', $args ); } add_action( 'init', 'markerCategories', 0 );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable the Code Editor in Gutenberg? While there already are similar questions around this topic I have yet to find anything about disabling the Code editor in Gutenberg permanently, for all users: Using Gutenberg is a must, so I'm not looking for solutions regarding the classic editor or alternative editor plugins. A code snippet that disables the editor would be much welcomed (I don't want to use a UI-only option). If this can't be achieved through hooks in the backend, I would also accept solutions that only affect the front end (since the backend receives HTML regardless of the editor used). Using display: none to hide the option would be one way to do it but I'd prefer a more permanent solution. The main reason for this is for security. I have already disabled many blocks and the patterns. I have already tried returning false on wp_code_editor_settings but that did not do anything to the Gutenberg editor.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why am I not able to login to the admin After the login credentials are submitted, the login page is retained. There is no invalid username or password message. The URL changed from wp-admin to wp-login.php with the querystrings. The console on the browser inspector says The Cookie has been rejected because it is already expired.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Woocommerce - add tracking code to another email template I'm using the "WooCommerce UPS Shipping Plugin with Print Label" plugin to process my orders. The plugin provides the tracking code to the customer as long as I set the order status to "completed" (the tracking code is inserted directly into the order completed email and sent to the customer). I'd like to provide the tracking code based on another order status, like "shipped", making the "completed" as the last step, but there's no way to do that through the plugin settings. By contacting the support, I got this: Can someone please help me to write this code?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom post type REST api 404: Updating failed. No route was found matching the URL and request method I have registered a new post type as: $this->sconfig= ['post_type'=> 'event', 'slug'=>'events']; add_action('init', array($this, 'register_event_posttype')); and function register_event_posttype() { //unregister_post_type($this->sconfig['post_type']); $args= [ 'labels' => [ 'name' => __('Events'), 'singular_name' => __('Event')], 'supports' => ['title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields', 'comments', 'revisions', 'post-formats'], 'query_var' => true, 'show_ui' => true, 'show_in_menu'=> true, 'show_in_nav_menus'=> true, 'exclude_from_search'=> false, 'capability_type' => 'post', 'public' => true, 'publicly_queryable' => true, 'has_archive' => true, 'hierarchical' => false, 'rewrite' => array('slug' => $this->sconfig['slug']), 'taxonomies' => array('category', 'post_tag'), 'rest_base' => $this->sconfig['slug'], 'show_in_rest' => true, //'rest_controller_class' => 'WP_REST_Posts_Controller' ]; register_post_type($this->sconfig['post_type'], $args); } Now this url (http://localhost/install05/wp-json/wp/v2/events/114?_locale=user) gives a 404 status with output (triggered when trying to save draft custom post): {"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}} Note: I have some custom meta fields associated with this post type and they are appearing fine in the add/edit page. What I tried so far (without results): #1: Unregistering and registering the custom post type and flushing the rewrite rules (re-saving the permalink structure) #2: Changing to this (in case of conflict): $this->sconfig= ['post_type'=> 'my-event', 'slug'=>'my-events']; #3: Defining the custom route: function rest_route_for_events($route, $post) { if($post->post_type === $this->sconfig['post_type'] ) { $route = '/wp/v2/'.$this->sconfig['slug'].'/' . $post->ID; } return $route; } add_filter('rest_route_for_post', array($this, 'rest_route_for_events'), 10, 2); Thanks for reading this far and some more for giving some thoughts over it :). A: The registration code was called inside the is_admin(). Moving the code outside solved the issue. /*if(is_admin()) {*/ $this->sconfig= ['post_type'=> 'event', 'slug'=>'events']; add_action('init', array($this, 'register_event_posttype')); /*}*/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Limit total tags in the_content I am using the_content to display content in a custom theme, but I am running into an issue. Right now, I have some JS code that removes the <br> tags and replaces them with </p><p> tags, so each line is a new paragraph: const d = Array.from(document.querySelectorAll('.content__main')); for (let e of d) { let old = e.innerHTML; e.innerHTML = ''; for (let line of old.split("\n")) { let cleaned = line.replace(/<\/?[^>]+(>|$)/g, "").trim(); if (cleaned !== '') { let newE = document.createElement('p') newE.innerHTML = cleaned; e.appendChild(newE); } } } I have the_content in a slider and it's working great! The issue I am facing is setting a limit on it. So, I found: https://wplancer.com/how-to-limit-content-in-wordpress/ which allows me to limit the_content without using the get_the_content approach, that way my existing JS script will continue to work and my HTML tags do not get stripped. This works, however, it sometimes breaks in the middle of a sentence because it filters based on the amount of words: function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') { $content = get_the_content($more_link_text, $stripteaser, $more_file); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); $content = strip_tags($content); if (strlen($_GET['p']) > 0) { echo ""; echo $content; echo " "."Read More →"; echo ""; } else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) { $content = substr($content, 0, $espacio); $content = $content; echo ""; echo $content; echo "..."; echo "".$more_link_text." "; echo ""; } else { echo ""; echo $content; echo " "."Read More → "; echo ""; } } But I was hoping, there would be a way to filter this by the amount of P tags. The HTML looks like: <p>Test</p> <p>Frog</p> <p>Duck</p> So, I was thinking I could specify a number like 2 and it would show Test and Frog completely (everything in that P tag) - then exclude duck and put a Read More link there. I have seen lots of tutorials that limit the amount of characters or the amount of words, but I haven't found anything that would limit the amount of P tags. Can anyone point me in the right direction? Thanks, Josh A: I was looking into this because all of the text was not showing on my slider, and the slider had a height set with overflow: hidden. I didn't think there was a simpler solution than to create a filter for the_content until I stumbled across this one... It's a css solution :-) All I am doing is using nth-child to display the first five items, then hide the rest: #main p:nth-child(1n+6) { display: none; } This is a great solution, because I can use media queries to change the amount I show based on screen size, that way I don't have to have one magic number and it'll look good on large or small screens. Hopefully this helps someone else trying to do the same thing. Thanks, Josh
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a wordpress function restrict public email id for registration like as is_email() I am trying to implement user registration only from the work email not with public emails like Gmail, yahoo, outlook, etc user registration will be through only with a business email I am able to implement a valid email but not work email restriction. if (!is_email($signup_email)) { echo json_encode(array('signedup' => false, 'message' => __('Invalid Email!', 'piperegistration'))); exit(); } if (email_exists($signup_email)) { echo json_encode(array('signedup' => false, 'message' => __('Email already exists!', 'piperegistration'))); exit(); } if (6 > strlen($signup_pass)) { echo json_encode(array('signedup' => false, 'message' => __('Password too short. Please enter at least 6 characters!', 'piperegistration'))); exit(); } I am still in the learning phase so please help me out A: If you're wanting to ensure that the email address contains the "work email" domain, you might be able to use the is_email filter (using the null context will make sure this is the last check in the is_email() function). Let's assume your work emails are all of the form [email protected]. add_filter( 'is_email', 'wpse_413882_check_domain', 10, 3 ); /** * Checks to make sure we're using a work email address. * * @param string|boolean $is_email The email address, or false. * @param string $email The email address to check. * @param string|null $context What context we're checking. We want `null`. * @return string|boolean The email address, or false on failure. */ function wpse_413882_check_domain( $is_email, $email, $context ) { if null !== $context { return $is_email; } if ( false === strpos( '@example.com', $email ) ) { // We're not using a work email address. Fail the test. return false; } return $is_email; }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: taxonomy-{term}.php terms pagination returning 404 after a certain page So my taxonomy-movies.php terms pagination returns 404 after a certain page, I've been sitting on this for like 3 days and still can't get answers from related question... So to give you guys some context, I'm showing/displaying all the category terms from Posts (Posts -> Category) in my taxonomy-movies.php with pagination. Terms with Pagination in short, so I'm not using WP_QUERY or anything of sort, I'm using get_terms() or WP_Term_Query to get all the category from Posts (Posts -> Category). The code below is how I get all the terms of category $term = get_queried_object(); $terms_paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $terms_per_page = get_field('acf_posts_per_page', $term); // is set to 2 $terms_args = array( 'taxonomy' => 'category', 'hide_empty' => false, 'number' => $terms_per_page, 'offset' => ($terms_paged - 1) * $terms_per_page, ); $terms = get_terms( $terms_args ); // returns 22 result // insert foreach loop of `$terms` here And here's my terms paginations code (see code below) $total_terms = wp_count_terms( 'category', array( // returns int 22 'hide_empty' => false, ) ); $total_terms_pages = ceil( $total_terms / $terms_per_page ); // returns 11 $big = 999999999; $terms_pagination = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => 'pages/%#%', // I've changed the pagination slug from page to pages separately in my functions.php so this `pages` works. 'type' => 'array', 'total' => $total_terms_pages, // total terms page == 11 'current' => max( 1, $terms_paged ), 'prev_text' => 'prev', 'next_text' => 'next', ) ); // insert foreach loop of `$terms_pagination` here the two part code I posted above is all working, pagination links are redirecting me correctly, but after a certain page let's say there's a total of 11 pagination, pages/1 to pages/7 is working just fine, and pages/8 to pages/11 returns 404. and when I added this code to debug global $wp_query; echo print_r($wp_query); die(); I saw that my taxonomy-movies.php is ignoring my get_terms() for the pagination and it uses WP_QUERY to retrieve CPT movies which is weird since I don't use any WP_QUERY in my taxonomy-movies.php. This was the result of print_r($wp_query) in pages/7 [request] => SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND (wp_term_relationships.term_taxonomy_id IN (114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,365,401)) AND ((wp_posts.post_type = 'movies' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private'))) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 12, 2 [posts] => Array (2) [post_count] => 2 [current_post] => -1 [in_the_loop] => [found_posts] => 14 [max_num_pages] => 7 [max_num_comment_pages] => 0 [is_single] => [is_preview] => [is_page] => [is_archive] => 1 So now I find the culprit, but I don't know how to fix it, so I guess my question all along was how can I overwrite this WP_QUERY result or ignore it so it'll not follow the max_num_pages of the taxonomy-movies.php. I tried manually changing max_num_pages to 11 and still didn't work, tried using pre_get_posts() & pre_get_terms() and still didn't work. So this was lengthy apologies in advance, I hope it does make sense.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP_query shortcode inside acf Repeater breaks the repeater loop I have a shortcode that lists CPTs and works great everywhere but if I use the shortcode in an ACF repeater the reapeater stops repeating right after the shortcode. I tried reseting postdata in various way in the shortcode, but nothing has worked yet. Appreciate any guidance. <section id="consumer_resources-list" class="padding-top-1"> <div class="container"> <ul class="accordion margin-bottom-0" data-accordion role="tablist" data-allow-all-closed="true"> <?php while (have_rows('field_61134ad5cf0b3')): the_row(); ?> <li class="accordion-item" data-accordion-item > <a href="#" class="accordion-title h5 margin-0"><?= get_sub_field('field_61134b21cf0b4') ?></a> <div class="accordion-content margin-horizontal-1" data-tab-content> <div class="inner-content"> <?= get_sub_field('field_61134b4bcf0b5') ?> </div> </div> </li> <?php endwhile; ?> </ul> </div> </section> This is the shortcode in function.php add_shortcode( 'list_webinars', 'getting_webinars' ); function getting_webinars($atts, $content = null) { ob_start(); extract(shortcode_atts(array( 'language' => 'spanish', 'webinarcat' => '', ), $atts)); $futureposts = new WP_Query(array( 'post_type' => 'webinar', 'posts_per_page' => -1, //'tax_query' => array( 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'webinar_categories', 'field' => 'slug', 'terms' =>$webinarcat, ), array( 'taxonomy' => 'webinar_categories', 'field' => 'slug', 'terms' =>$language, ) ), 'meta_key' => 'webinar_date', 'meta_value' => date('Ymd', strtotime('-1 day')), 'orderby' => 'meta_value', 'order' => 'ASC', 'meta_compare' => '>', )); if ($futureposts-> have_posts()){ $retour='<ul class="events-list" style="list-style:none;">'; while ( $futureposts->have_posts() ) : $futureposts->the_post(); $retour .= '<li class=" ' . implode (' ', get_post_class( 'individualWebinar' ) ). '">'; $retour.= '<span class="event-title-webinar"><a href="' . get_field('field_627d909680aac') . '" target="_blank"> ' . ucfirst($language) . '-'; $dateTime = strtotime(get_field('field_627d84f3648f2')); $retour .= date('l, F j, Y', $dateTime) . ' '; $retour .= '@ '. get_field( "field_627eeb2af6475" ) . ' MST - Register Here >></a></span> </li> '; endwhile; $retour .= '</ul>'; return $retour; } else { return '<strong>No upcoming events are currently on the calendar.</strong>'; } wp_reset_postdata(); return ob_get_clean(); } A: Change the end to proper syntax, endwhile; $retour .= '</ul>'; wp_reset_postdata(); return $retour; } else { return '<strong>No upcoming events are currently on the calendar.</strong>'; } return ob_get_clean(); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where did I put this one line of css? So I'm a bit lost. There are so many places to tuck away custom css between the WordPress customizer and Elementor Pro, and I added some css to style a couple little recurring anchor tags in a file sharing list, but now I can't remember where I put it and can't find it. I have looked in every place I can think of. I know now that I can put all of my additional css in the theme file (I created a child theme for that reason) but that doesn't help me now to find that one darn line of code to edit it. I did use the page source and found the css I added but where is the source file located so I can edit it? I am completely self taught through various resources and prerecorded classes online so I don't know what I don't know. I am pretty good with working in WordPress but I am new to editing the file itself rather than using custom code on individual pages via a plugin. A: You can use the Developer Inspector (usually F9 in your browser) to bring up the page data. Right click where you see the CSS being used, and use the developer panel to click on the CSS code (you should be on the Inspector tab). Over in the right side of that developer area you should see the various CSS styles. And to the right of that, the Computed CSS. Click on one of the items in the Computed area. You should see the file and line number where that value came from. Example below. See the CSS for the 'border-top-right-radius' came from 'stacks.css' in line 8. The screenshot is from the FireFox Developer screens. There are many tutorials on how to use this that you can find on the googles/bings/ducks.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React Material UI and WordPress Admin Area I am creating a plugin that uses a React App to run inside the admin section of WordPress, and this app uses React Material UI (MUI) as well. Everything is great, until I started to use "form" components (such as TextField) and this is when load-styles.php started to interfere with the outcome of those files. After further investigation, it appears like load-styles.php is taking precedence over the styles generated by the MUI as you can see in the picture below: So, I tried different solutions First, I tried disabling the styles as described here and here but this causes ALL styles for the admin area to disappear, which is not good. I only do not want the form styles to be disabled Then I tried to enqueue and reset the styles I wanted to target by giving them the !important keyword, just like this: input { padding: 0 !important; line-height: normal !important; min-height: 0 !important; box-shadow: none !important; border: medium none currentColor !important; border-radius: 0 !important; background-color: transparent !important; color: inherit !important; } But this would cause a problem, because now the default MUI styles are also overridden (because !important works on them as well), causing the look to be all messed up. Then, I tried many other solutions, all of them revolve around styling components, but just like above, they end up messing up MUI default styling Moreover, Someone had a similar problem but no answer to him/her yet, and the suggestion in the comments to use <CssBaseline /> did not solve anything. So, the way I am thinking is as follows: * *Is there a way to make the MUI inline styles take precedense over load-styles.php? *If not, is there a way to disable parts of the load-styles.php ? *If not, how do I style the admin area using React MUI? Thanks you. A: The fundamental issue is that MUI is probably not meant to be used in an environment where there are already styles like this. It's supposed to be the base layer. The WordPress admin has its own styles and it's highly unusual to try and use a completely different UI framework inside of it. These types of conflicts are inevitable when you try to use 3rd-party UI frameworks inside the WordPress admin, which was not designed to support them. The same issues occur when people try to use Bootstrap in the WordPress admin. Is there a way to make the MUI inline styles take precedense over load-styles.php? The styles in your screenshot are inline styles, so they are already loading after load-styles.php. The reason they're not taking precedence is because the load-styles.php rules have a higher specificity. To make your styles take precedence you'd need to increase the specificity of the selectors used by MUI. Whether MUI has tools for that is something you would need to ask them or their community. If not, is there a way to disable parts of the load-styles.php ? load-styles.php is just outputting all the styles that have been enqueued with wp_enqeueue_style() in the admin. You can dequeue them with wp_dequeue_style() but you'll need to know the handle used to register the style. Tools like Query Monitor can give you a list of what stylesheets are enqueued, and their handles. The problem is that the styles you want to remove are probably in a stylesheet with many styles that you don't want to remove, and removing them will probably break parts of the WordPress admin that you still need. If not, how do I style the admin area using React MUI? This probably isn't a supported use-case for MUI. If it is they should be able to help. If it isn't then your options are limited: * *Increase the specificity of MUI selectors, if that's even possible. *Add your own stylesheet that corrects any broken visuals caused by the conflict. If MUI uses dynamically generated class names, this will be difficult. A: I have similar issue when I was working on Rect part of the plugin. It finally worked for me, with CSS code included via admin_enqueue_scripts https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/ I put my object inside div, with custom name, and then I referred to for example input like this: <div class="my_div"> <form class="my_div__form"> <input type="text" class="my_div__input" /> </form> </div> and with that code I used this CSS: .my_div .my_div__input { // Styles here } I used BEM formatting and SCSS, but this is not relevant, and you can achieve this without those. If you do not have power over structure of the elements, I'm not sure if this is possible without !important, at least I was not able to find other solution.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Weird Javascript:void(0) code in my website Hello i am bit newbiew of coding but very well expirienced with WP. I am having this website (www.kefaloniataxiservice.gr) there is this kind in my website (INSPECT CODE) that according to Lightspeed is conflicting the SEO of my page. i tried to find with VS Code this code but couldnt find it, even trying only w-header-show got me to some CSS and JS code that if i deleted it nothing changed. Also i tried to download my DB from PhpMyAdmin and search the entire DB with VS Code aswell but couldnt find anything, any luck? Notice: Μένου means Menu. <a class="w-header-show" href="javascript:void(0);"><span>Μενού</span></a> <div class="w-header-overlay"></div> <script>```
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sorting Users page admin column with ACF field I have a CPT called Companies. I created an ACF relationship field called user_company that gets displayed in the Users profile page. When a user registers, I have to go in and assign them to a company. I added the ACF field to the Users page admin column but I am unable to sort it. It currently sorts based on post_id and I have no idea how to sort it by post_title. Here is the code I have so far: // Add columns and data to Users admin page add_filter( 'manage_users_columns', 'manage_users_columns_new_columns' ); function manage_users_columns_new_columns( $columns ) { $columns['user_comp any'] = 'User Company'; return $columns; } add_filter( 'manage_users_custom_column', 'manage_users_custom_column_new_columns', 10, 3 ); function manage_users_custom_column_new_columns( $value, $column_name, $user_id ) { if ( $column_name == 'user_company' ) { $user_company = get_field('user_company', 'user_' . $user_id); $user_company_post = get_post($user_company); if( isset( $user_company_post ) ){ return $user_company_post->post_title; } else { return '-'; } } return $value; } // ACF/save_post to save title of User Company as another meta_value function save_user_company_name ( $post_id ) { $user_company_id = get_field( 'user_company', $post_id ); if ( $user_company_id ) { update_post_meta( $post_id, 'user_company_name', get_post_field( 'post_title', $user_company_id ) ); } } add_action( 'acf/save_post', 'save_user_company_name', 20 ); // Sort columns on Users admin page add_filter( 'manage_users_sortable_columns', 'register_sortable_columns_custom', 10, 1 ); function register_sortable_columns_custom( $columns ) { $columns['user_company'] = 'user_company'; return $columns; } add_action( 'pre_get_users', 'pre_get_users_sort_columns_custom' ); function pre_get_users_sort_columns_custom( $query ) { if ( $query->get( 'orderby' ) == 'user_company' ) { // Currently sorts by post ID vs post title. Will need to add additional code: https://support.advancedcustomfields.com/forums/topic/admin-column-a-z-sorting-for-object-field/ $query->set( 'orderby', 'meta_value' ); $query->set( 'meta_key', 'user_company_name' ); } } I added the acf/save_post portion based on answers I have found online but I don't know how that works. I tried saving each Company posts as well as the Users assigned to a company. But when I try to sort on the admin page, everything blanks out. I'm not sure how to get this to work. A: You can use the "pre_user_query" filter hook to modify the query that retrieves the users. Here's an example code that how to sort the Users page admin column with an ACF field named. function sort_users_by_acf_field( $query ) { if ( ! is_admin() ) { return; } if ( isset( $query->query_vars['orderby'] ) && 'user_company_name' === $query->query_vars['orderby'] ) { $query->query_vars['meta_key'] = 'user_company_name'; $query->query_vars['orderby'] = 'meta_value'; } } add_action('pre_user_query','sort_users_by_acf_field'); Hope this will help!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Woocommerce: Price per multiple of quantities I have a Woocommerce shop in Wordpress that sells a product available in quantities (meters) of either each (1 of), or in boxes (packs) of 6. Currently the quantity is set up as a variable option, so at the moment the user can only buy as eaches or in boxes of 6. Individually the product costs $10 each, or $8each in a box of 6 ($48 per box). I would like to make this simpler so the user only needs to enter in how many they want (as individual unit), and then the backend can calculate the price based on that, taking into account how many multiples of 6 there are and any remainder be calculated at the $10 rate. Or this possible within Woocommerce? Or is there a plugin/extension that can achieve this?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generate / attach Image srcsets from ACF Image Field I currently have an ACF save post action that takes an image and assigns it to be the featured image. One problem I am having is displaying the srcsets. <img src="<?php echo esc_url( $img_src ); ?>" srcset="<?php echo esc_attr( $img_srcset ); ?>" sizes="(max-width: 100vw)" alt="<?php echo $image['alt']; ?>" title="<?php echo $image['alt']; ?>" /> add_action('acf/save_post', 'my_acf_save_post_image'); function my_acf_save_post_image( $post_id ) { $posttype = get_post_type($post_id); $wistia_image_url = get_field('image', $post_id); $wistia_video_url = get_field('wistia', false, false); if (($posttype == 'post' && !empty($wistia_image_url)) && empty($wistia_video_url) ) { $img_src = wp_get_attachment_image_url( $wistia_image_url['id'], 'mobile-large' ); // Define attachment metadata $attach_data = wp_generate_attachment_metadata( $wistia_image_url['id'], $img_src ); // Assign metadata to attachment wp_update_attachment_metadata( $wistia_image_url['id'], $attach_data ); #Not working. First parameter has to be the actual image file from what I've read? wp_image_add_srcset_and_sizes($wistia_image_url, $attach_data, $wistia_image_url['id']); // And finally assign featured image to post set_post_thumbnail( $post_id, $wistia_image_url['id'] ); } } I understand that the get_field of an image element will return sizes that has all the sizes, but individually. Is there a way to assign those sizes into the srcset of an attachment so when I use wp_get_attachment_image_srcset, it would pull the srcset in one go rather than setting them all individually?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display gutenberg editor in a view In a custom plugin, i display the content from a post in an editor like this wp_editor( $content, $editor_id ); but when the content is done with gutenberg , i want to display the gutenberg editor and not the classic editor. How can i do this ? Thanks Stéphane A: I'm not sure i completely understand what you want to do... you want to use the block editor on an admin page of your page, but then use it to edit the content of an existing post? I'm not quite sure if this can work as you intended. However, there IS an experimental way to include a seperate instance of the block editor on an admin page. Please use this tutorial on the wordpress developer portal to create this. Happy Coding!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WHEN woocommerce ORDER PLACED Successfully then send order in json Format on third party API add_action( 'wp_ajax_api_request_ajax_function', 'api_request_ajax_function' ); function api_request_ajax_function() { $order_id = $_POST['order_id']; $order_json_data = get_post_meta( $order_id, '_order_json_data', true ); if(!empty($order_json_data)) { $response = wp_remote_post( 'https://jsonplaceholder.typicode.com/posts', $data ); if($response['success']) { update_post_meta($order_id, 'send_api_request', 1); } update_post_meta($order_id, 'send_api_request', 1); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: add_rewrite_rule not working with custom variables I posted this in stackoverflow as well, so hope it's good to post here as well! I think this is my last problem to solve before everything clicks into place: I have a homepage with a custom plugin that sends some data to another page, I am building a theme for this website that works with the plugin. So in the theme functions.php I have added a function myvar($vars){ $vars[] = 'ep_year'; $vars[] = 'ep_name'; return $vars; } add_filter('query_vars','myvar'); works a charm, I can send those values over to a custom page with a custom template assigned. This has a permalink as follows: http://ngofwp.local/episode/ and when I send the data over it looks like so (permalinks are enabled): http://ngofwp.local/episode/?ep_year=2011&ep_name=silly_donkey I know I have to use an add_rewrite_rule so I've started coding that as follows: function custom_rewrite_rule() { add_rewrite_rule('^episode/([^/]*)/([^/]*)\.html$','?ep_year=$matches[1]&ep_name=$matches[2]','top'); } add_action('init', 'custom_rewrite_rule'); But now for the life of me I have no clue about the formulae to get it to work. I have read the regex rules and tested that particular rewrite on a site that helps you do that. What I'd like it to look like is this: http://ngofwp.local/episode/2011/silly_donkey.html The http://ngofwp.local/episode/ is given by wordpress's permalink setting and is a custom page in the templates folder (it displays correctly) What did I do wrong? A: What I suspect has happened is that you're using this to hide the ugly URL variables and turn them into pretty URLs via regex, and you've almost done that part correctly: ?ep_year=$matches[1]&ep_name=$matches[2] But nothing in that tells WordPress which page you wanted. How is it meant to know it should be the episode page? To fix this it will need to explicitly tell WP this, perhaps with something like this: ?ep_year=$matches[1]&ep_name=$matches[2]&pagename=episode Then on top of that, the regex maps to the wrong URL, ugly permalinks always take the form index.php followed by URL parameters. This is the reason why WP rewrite rules can't map URLs on to arbitrary files. So it needs to instead map to: index.php?ep_year=$matches[1]&ep_name=$matches[2]&pagename=episode The other issue it will have is that because it uses a custom page template the header tags will be set up for a singular piece of content, not an archive. This also means WP might decide to redirect to what it thinks is the canonical URL, and it also means everything under /episode has the canonical URL or /episode, which is true and correct. You might have intended this to be an archive of episodes with individual episodes accessible via a rewrite, but you've only built the appearance of such an archive. It will need to filter these to fix that. To truly do this correctly though, it needs a CPT for each episode, custom permalinks, and a filter to modify each episodes post URL to add the correct year. Note that for any of this to work: * *pretty permalinks have to be enabled in settings *you have to flush permalinks/rewrite rules whenever you change the rewrite rules, visiting the permalinks settings page is enough to do this *use get_query_var not $_GET in your template *your URL must match the regex, it should show as a match in WP debugging plugins too A: It looks like your add_rewrite_rule function is not quite correct. The first parameter should be the regular expression pattern that you want to match, and the second parameter should be the query string that you want to rewrite the URL to. Also, you don't need to include the file extension in the URL. Try updating your custom_rewrite_rule function to this: function custom_rewrite_rule() { add_rewrite_rule('^episode/([^/]*)/([^/]*)/?$','index.php?page_id=PAGE_ID&ep_year=$matches[1]&ep_name=$matches[2]','top'); } add_action('init', 'custom_rewrite_rule'); Replace PAGE_ID with the ID of the page that displays the custom template for your /episode/ URL. You can find the page ID by editing the page in WordPress and looking at the URL in your browser's address bar - it will be something like post.php?post=PAGE_ID&action=edit. This rule will match a URL like http://ngofwp.local/episode/2011/silly_donkey/ and rewrite it to http://ngofwp.local/index.php?page_id=PAGE_ID&ep_year=2011&ep_name=silly_donkey. After updating the functions.php file, you'll need to go to the WordPress dashboard Settings > Permalinks and click the "Save Changes" button to flush the rewrite rules cache and make your new rule active.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I produce multiple webpages with a different output based on one entry/Page/custom Page? My problem: I have a custom page format for events. Now I would like to get different outputs for each of these events. * *Normal webpage › for visitors *Custom look › for easy copy and paste to other platforms for seminars. My question Is it possible to design two templates with different URLs. So that I have the possibility to call these pages with custom templates/designs? A: Query string parameters are a helpful friend in this situation. It will allow you to keep the same single-$posttype.php file for both formats of the page. So if someone visits your page using the URL: https://yourwebsite.com/events They will see your normal webpage for visitors. But if someone uses the URL: https://yourwebsite.com/events?seminar=true They will see something completely different. This is accomplished by using the $_GET global variable provided by PHP. Documentation is here. So you could do the following using a single-event.php page (providing event is a post type): <?php $is_seminar = $_GET['seminar']; if ( $is_seminar === 'true' ) : ?> <h1>Custom look for seminars.</h1> <?php else : ?> <h1>Normal webpage</h1> <?php endif; Or if you want a little bit of a cleaner look to your URL, take a look at Get URL query string parameters using $_SERVER['QUERY_STRING']. Also see How can I make different page templates for one category? for another alternative solution using your post's meta info.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to put posts with some taxonomy on top of others in `pre_get_posts` The following tax_query returns only matched posts (with 'matchedstring' IN taxonomy array): function only_returns_matched_posts( $query ) { if( !$query->is_main_query() || is_admin() ) return; $taxquery = array( array( 'taxonomy' => 'mygroup', 'field' => 'slug', 'terms' => 'matchedstring', 'compare'=> 'IN' ) ); $query->set( 'tax_query', $taxquery ); } add_action( 'pre_get_posts', 'only_returns_matched_posts' ); I want the matched posts grouped at the top of the query with the other posts following. Is it possible to either: * *use this format with a orderby *do 2 separate queries and merge them *use a custom Group By SQL query EDIT I managed to merge 2 queries but I lose the menu_order when I apply post__in to keep the $queryA + $queryB order. Should I get ids differently than with $query->posts to keep original menu_order of the queries? function group_matched_posts_at_top( $query ) { // Check if this is the main query and not in the admin area if( !$query->is_main_query() || is_admin() ) return; // Get posts with matched taxonomy + posts without taxonomy $queryAparams = array( 'posts_per_page' => -1, 'post_type' => 'product', 'order_by' => 'menu_order', 'order' => 'ASC', 'fields' => 'ids', 'tax_query'=> array( 'relation' => 'OR', array( 'taxonomy' => 'pa_group', 'field' => 'slug', 'terms' => 'matchedstring', 'operator' => 'IN' ), array( 'taxonomy' => 'pa_group', 'operator' => 'NOT EXISTS' ) ) ); // Get posts with other taxonomies $queryBparams = array( 'posts_per_page' => -1, 'post_type' => 'product', 'order_by' => 'menu_order', 'order' => 'ASC', 'fields' => 'ids', 'tax_query'=> array( 'relation' => 'AND', array( 'taxonomy' => 'pa_group', 'field' => 'slug', 'terms' => 'matchedstring', 'operator' => 'NOT IN' ), array( 'taxonomy' => 'pa_group', 'operator' => 'EXISTS' ) ) ); $queryA = new WP_Query($queryAparams); $queryB = new WP_Query($queryBparams); // Merging ids $postIDs = array_merge($queryA->posts,$queryB->posts); if(!empty($postIDs)){ $query->set('post__in', $postIDs); $query->set('orderby', 'post__in'); } } add_action( 'woocommerce_product_query', 'group_matched_posts_at_top' ); EDIT2 I'll post my own answer. I had to actually remove the 'fields' => 'ids' parameters to keep the queries menu_order and pluck the ids after resorting them. A: You could try modifying the tax query to use the relation parameter and add a second clause that matches any post that does not have the matched string value in the meta array. See Taxonomy Parameters. EDIT: Thank you for pointing that out, Tom. You're correct, I've updated to reflect. function group_matched_posts_at_top( $query ) { // Check if this is the main query and not in the admin area if( !$query->is_main_query() || is_admin() ) return; // Define the tax query with two clauses (matched and not matched) $taxquery = array( 'relation' => 'OR', // Set the relation to OR to include posts that match either clause array( 'taxonomy' => 'mymeta', 'field' => 'slug', 'terms' => 'matchedstring', 'operator' => 'IN' // use the operator parameter to specify the comparison operator ), array( 'taxonomy' => 'mymeta', 'field' => 'slug', 'terms' => 'matchedstring', 'operator' => 'NOT IN' // use the operator parameter to specify the comparison operator ) ); // Set the tax query and meta key parameters for the query $query->set( 'tax_query', $taxquery ); $query->set( 'meta_key', 'mymeta' ); // Set the orderby parameter to sort by the value of the "mymeta" field in descending order (so that matched posts appear first), and then by date in descending order (so that the most recent posts appear first within each group). $query->set( 'orderby', array( 'meta_value' => 'DESC', 'date' => 'DESC' ) ); add_action( 'pre_get_posts', 'group_matched_posts_at_top' ); The main changes are as follows: * *I've used the "taxonomy" parameter to specify the taxonomy to query. *I've used the "operator" parameter instead of "compare" to specify the comparison operator (IN or NOT IN). *I've added the "field" parameter with a value of "slug" to specify that we're comparing the term slug (i.e., the term's "mymeta" field). These changes should make the query work with a term/taxonomy meta field, which was not supported by my earlier solution. A: I finally managed to do it by merging 2 queries. I'm using it with a woocommerce attribute but it can work with any taxonomy. function group_matched_posts_at_top( $query ) { // Modify the query only if it's the main query and it's a product archive page if ( !$query->is_main_query() || !(is_product_category() || is_shop()) || is_admin() ) { return; } // String to match $string_to_match = 'Whatever taxonomy'; // Query for products with matched taxonomy $query1 = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'order_by' => 'menu_order', 'order' => 'ASC', 'tax_query'=> array( 'relation' => 'OR', array( 'taxonomy' => 'pa_group', 'field' => 'name', 'terms' => $string_to_match, 'operator' => 'IN' ), array( 'taxonomy' => 'pa_group', 'operator' => 'NOT EXISTS' ) ) ) ); // Sorting first query before merging usort( $query1->posts, function( $a, $b ) { return $a->menu_order - $b->menu_order; } ); // Query for other products $query2 = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'order_by' => 'menu_order', 'order' => 'ASC', 'tax_query'=> array( 'relation' => 'AND', array( 'taxonomy' => 'pa_group', 'field' => 'name', 'terms' => $string_to_match, 'operator' => 'NOT IN' ), array( 'taxonomy' => 'pa_group', 'operator' => 'EXISTS' ) ) ) ); // Sorting second query before merging usort( $query2->posts, function( $a, $b ) { return $a->menu_order - $b->menu_order; } ); // Merge the results in the desired order $products = array_merge( $query1->posts, $query2->posts ); // Set the modified query results $query->set( 'posts_per_page', -1 ); $query->set( 'post__in', wp_list_pluck( $products, 'ID' ) ); // keep the order $query->set( 'orderby', 'post__in' ); } add_action( 'pre_get_posts', 'group_matched_posts_at_top' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble Finding Error Logs in wp-env New to wp-env, which is mostly a fantastic dev tool. { "plugins": ["./blinkwellness-mindbody"], "config": { "WP_DEBUG": true, "WP_DEBUG_LOG": true, "WP_DEBUG_DISPLAY": true, "SCRIPT_DEBUG": true }, "phpVersion": "8.1", "mappings": { "profileApp": "./profileApp" }, "env": { "development": { "themes": ["./customtheme"] }, "tests": { "config": { "KEY_1": false }, "port": 3300 } } } However, I am having trouble finding error logs. At the moment developing an Ajax feature, which started returning a 500 error. When running wp-env logs all, the result is: ...523db7a-tests-wordpress-1 | 172.21.0.1 - - \ [16/Feb/2023:13:23:27 +0000] "POST /wp-admin/admin-ajax.php \ HTTP/1.1" 500 484 "http://localhost:3300/schedule/" \ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \ (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Empty content in /var/log/apache2/error.log. Only wordpress debug log I'm finding on the server, /var/www/html/wp-content/debug.log, which only has some PHP Deprecated and other warnings in it. Any suggestions? UPDATE Went to another dev approach (Roots/Trellis, virtualbox), which runs Nginx and there indeed the relevant Fatal Error is listed in /var/log/nginx/debug.log. Where it gets thrown is: if ( WP_DEBUG ) { throw new \Exception( $err->getMessage() ); } So, maybe there's a different php log level between wp-env and the Trellis virtualbox configuration.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make multiple custom taxonomies sit under custom post type slug? I have a custom post type called resources which has been registered as so: register_post_type( 'Resources', theme_build_post_args( // $slug, $singular, $plural 'resources', 'Resource', 'Resources', array( 'menu_position' => 20, 'has_archive' => true, //'has_archive' => 'types', 'public' => true, 'supports' => array('title', 'revisions', 'thumbnail', 'editor', 'author'), 'taxonomies' => array('topics', 'types', 'industries'), 'rewrite' => array('slug' => 'resources/%types%') ) ) ); This post type has three taxonomies which have been registered like this: register_taxonomy( 'topics', 'topics', array( 'hierarchical' => true, 'label' => 'Topics', 'query_var' => true, 'show_admin_column' => true, 'publicly_queryable' => true, // 'rewrite' => array('slug' => 'resources') ) ); register_taxonomy( 'types', 'types', array( 'hierarchical' => true, 'label' => 'Types', 'query_var' => true, 'show_admin_column' => true, 'publicly_queryable' => true, // 'rewrite' => array('slug' => 'resources') ) ); register_taxonomy( 'industries', 'industries', array( 'hierarchical' => true, 'label' => 'Industry', 'query_var' => true, 'show_admin_column' => true, 'publicly_queryable' => true, // 'rewrite' => array('slug' => 'resources') ) ); Currently, when accessing a category defined in any taxonomy, the slug ignores /resources. For example, I have a type called Article. When accessing this page, it sits on /types/article/ when I need it to sit on /resources/types/article/. The same applies for topics and industries. Now I have seen approaches stating this should do the trick: 'rewrite' => array('slug' => 'resources/%types%') However, the above doesn't work for types, meaning types still do not sit under /resources, but also, I need this to occur for 3 taxonomies, rather than just 1 and I cannot rewrite slugs for 3 taxonomies. How do I go about this? A: You commented, "As far as I can see rewrite is only possible for one taxonomy?". So no, that's not true, it's possible for every taxonomy. Just remember that each taxonomy should have a unique rewrite slug, so that it does not conflict with other permalinks (for other taxonomies and for post types like post, page, etc.). So for instance, if the topics taxonomy uses topics as the rewrite slug, then your types and industries taxonomies need to use a different rewrite slug. (If you really must use/share the same slug, it's not impossible, but it's not in scope of this answer) Now if these are the permalink structures that you want: * */resources/topics/<term slug> for the topics taxonomy */resources/types/<term slug> for the types taxonomy */resources/industries/<term slug> for the industries taxonomy where an example permalink (URL) would look like this: * *https://example.com/resources/topics/security/ for a term with the slug security, in the topics taxonomy *https://example.com/resources/types/article/ for a term with the slug article, in the types taxonomy *https://example.com/resources/industries/accounting/ for a term with the slug accounting, in the industries taxonomy Then just set the rewrite slug for your taxonomy to resources/<taxonomy>, like so: (this is the actual code I tried & tested working with WordPress v6.1.1) function my_register_post_types() { register_post_type( 'resources', // post type name/slug array( 'public' => true, 'rewrite' => array( 'slug' => 'resources' ), 'labels' => array( 'name' => 'Resources', // other labels ), // other args ) ); } function my_register_taxonomies() { register_taxonomy( 'topics', // taxonomy name/slug 'resources', // attach to this post type array( 'public' => true, 'rewrite' => array( 'slug' => 'resources/topics' ), 'label' => 'Topics', 'hierarchical' => true, // other args ) ); register_taxonomy( 'types', // taxonomy name/slug 'resources', // attach to this post type array( 'public' => true, 'rewrite' => array( 'slug' => 'resources/types' ), 'label' => 'Types', 'hierarchical' => true, // other args ) ); register_taxonomy( 'industries', // taxonomy name/slug 'resources', // attach to this post type array( 'public' => true, 'rewrite' => array( 'slug' => 'resources/industries' ), 'label' => 'Industries', 'hierarchical' => true, // other args ) ); } However, you need to first register the taxonomies, and only after that, register your resources post type, if its rewrite slug is resources, which is the default value, or that the slug starts with resources/. Otherwise, your term permalinks would result in a 404 error page. :/ // Register the taxonomy first. add_action( 'init', 'my_register_taxonomies' ); // Then the post type. add_action( 'init', 'my_register_post_types' ); Also, be sure to flush the rewrite rules (i.e. re-save your permalinks), by simply visiting the Permalink Settings admin page.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple permalinks for a single post from custom field I'm looking for a way to add additional slugs for regular posts, so that a single post can be viewed from multiple urls. Example: the canonical post url would be: website.com/foo-bar but I want visitors to website.com/foobar and website.com/fb to see the same content at those urls. I know this can be achieved manually with any of the redirection plugins, but I am looking for a way to automate this. Based on this article, I tried the following, using a slug_aliases custom field on my posts: // Add custom query variable function alias-register_query_var( $vars ) { $vars[] = 'slug_alias'; return $vars; } add_filter( 'query_vars', 'alias-register_query_var' ); // Try to get the post with the queried custom field value and do the actual redirect (or throw an 404) function alias_redirect() { if( get_query_var( 'slug_alias' ) ) { $posts = get_posts([ 'post_type' => 'post', 'meta_key' => 'slug_aliases', 'meta_value' => get_query_var( 'slug_alias' ) ]); if($posts) { wp_redirect( get_permalink( $posts[0]->ID ) ); exit(); } else { global $wp_query; $wp_query->set_404(); status_header(404); } } } add_action( 'template_redirect', 'alias_redirect' ); // Redirect to the query URL if the URL matches the regex function alias_register_rewrite_rule() { add_rewrite_rule('^alias/(.*)/?', 'index.php?slug_alias=$matches[1]', 'top'); } add_action( 'init', 'alias_register_rewrite_rule' ); This works in as much as website.com/?slug_alias=foobar redirects to website.com/foo-bar, but I can't get the rewrite to work. I get a 404 for website.com/foobar Is this even the correct approach for this?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automatically compare date from custom post type with current date and change taxonomy based on a result? I have a local WordPress website installment. I have custom post type "tours" and a custom taxonomy connected to it called "active-past". This taxonomy has two terms "active1" and "past1". Connected to this custom post type I have a custom post field "datum_polaska" in a date format. I would like to be able to automatically change the term "active1" to "past1" if "datum_polaska" is older than the current date. How can I accomplish this? I want this to be checked for each post containing the term "active1" only once per day. It's important that the event is triggered automatically on a time base. I found this answer, but I don't get how to implement it for my case. I tinkered around with chatGPT (sorry if this insults someone here) and I got these two codes: function update_tour_status() { // Get all posts with the "active1" term $args = array( 'post_type' => 'tours', 'tax_query' => array( array( 'taxonomy' => 'active-past', 'field' => 'slug', 'terms' => 'active1' ) ), 'posts_per_page' => -1 // Retrieve all posts ); $query = new WP_Query($args); // Loop through each post and update the term if needed while ($query->have_posts()) { $query->the_post(); $datum_polaska = get_post_meta(get_the_ID(), 'datum_polaska', true); if ($datum_polaska && strtotime($datum_polaska) < time()) { wp_set_post_terms(get_the_ID(), 'past1', 'active-past', false); } } wp_reset_postdata(); } and this // Schedule the event to run every 5 minutes for testing purposes add_action('wp', 'my_custom_cronjob'); function my_custom_cronjob() { if (! wp_next_scheduled('update_tour_status')) { wp_schedule_event(time(), '5min', 'update_tour_status'); } } I tried using them as 2 separate code snippets but they don't do anything. Does anyone have any idea what's wrong with the code? Please bear in mind that I'm not a developer and that I barely understand the concepts in the code. If someone has a suggestion on how to deal with this in some other way I'm happy to hear it. A: This is pretty straight forward and easy to do with $wpdb and SQL statement the relationship between any post type (custom or not) and taxonomy term (custom or not ) are stored wp_term_relationships table which has object_id and term_id all you have to do is query the record that has the term_id for active1 term and update that to term_id of past1 term, if the postmeta value with meta key datum_polaska of the object_id is greater than the current time. Here is a function to do that (untested) function _update_tours_post_type_terms() { // Added additional condition to terminate the function when called many times per day $tsKey = '_update_tours_post_type_terms_last_run'; $lastRun = get_transient( $tsKey ); // get the transient data /* Un-comment the line below if you want to; * stop execution if the last time it was called is < 12 hour ( 12 hr = 43200 seconds ) */ //if ( $lastRun + 43200 > time() ) //return; global $wpdb; $activeTermID = 1; // set the active1 term ID $pastTermID = 2; // set the past1 term ID $currentDate = date('Y-m-d'); // get current date and make sure it matches the format you stored in postmeta /* Next code explains below per line -run update statement on term_relationships table on all rows matching all if condition below -set the term_taxonomy_id to $pastTermID -load the postmeta where meta post_id = object_id and meta_key is datum_polaska -if the current term_taxonomy_id value is $activeTermID -if datum_polaska is less than $currentDate */ $wpdb->query($wpdb->prepare(" UPDATE $wpdb->term_relationships tr SET tr.term_taxonomy_id = $pastTermID INNER JOIN $wpdb->postmeta dp ON dp.post_id = tr.object_id AND dp.meta_key = 'datum_polaska' WHERE tr.term_taxonomy_id = $activeTermID AND dp.meta_value < '$currentDate' ")); // Update transient to current time if the function runs set_transient( $tsKey, time() ); } and thats it, no need for query or looping, this just need the post type to to have the active1 term set while past1 should not be assign, otherwise it wont work as this simply update/replaces the record already present in the database. All you have to do is call that function in your wp_schedule_event Optional setting up cron from your server instead of using wordpress event scheduler You may also set-up a cron directly from your server that runs every day. all you have to do is set a url param and call the function when the param is present in the request. e.i add_action('init', function() { //terminate if update_tours_post_type_terms is not present in url parameter or if its value is not equal to 1 if ( !isset( $_REQUEST['update_tours_post_type_terms'] ) || !$_REQUEST['update_tours_post_type_terms'] === '1' ) return; _update_tours_post_type_terms(); }); Then you can simply open the URL to run that function https://yoursite.com/?update_tours_post_type_terms=1 and setup a daily cron on your server to ping that URL every day at 1AM 0 1 * * * wget -O - https://yoursite.com/?update_tours_post_type_terms=1 >/dev/null 2>&1 EDIT If you want to test the function, first make sure the code below is commented (I already edited the function above which disable those lines if ( $lastRun + 43200 > time() ) return; Second, you can implement the init hook above then simply open the example url I mentioned OR just hook the function direclty on init (this should not be done unless you are just testing) e.i. add_action('init', '_update_tours_post_type_terms'); then wherever you browse your site (front-end or back-end) that function will run, you can simply assign an active1 term with a past date meta, and it should update itself to past1 once you hit save
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display Featured image from custom post type category (custom taxonomy) wise I am creating a dynamic slider. I have set slider images in featured image. I want featured images according to category wise. Please help me with this. Thank you. <?php $cottage = new WP_Query( array( 'post_type' => 'cottage',//custom post type 'posts_per_page' => -1, 'order' => 'ASC', 'post_status' => 'publish', //'post__not_in' => array( get_the_ID() ), 'tax_query' => array( array ( 'taxonomy' => 'cottage',//custom taxonomy 'field' => 'slug', //type, id or slug 'terms' => array( 'lace-cottage ', 'lagoda-cottage', 'lamberg-cottage' )//categories ) ), ) ); while ( $cottage->have_posts() ) : $cottage->the_post();?> <div class="block-image-slider__slide"> <figure class="block-image-slider__image-wrapper"> <img width="1290" height="754" src="<?php the_post_thumbnail_url(); ?>" class="block-image-slider__image" alt="Tables with glasses and ocean view." loading="lazy" /> </figure> </div> <?php endwhile; wp_reset_postdata(); ?>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect, if post is saved manually or programmatically in save_post-hook I have a set of 1k posts which are regularly updated through an automated import. Each post is hashed so I can quickly detect, if I need to update a specific post or not, compared to the import file. (Hash is saved in a custom field.) From time to time, editors like to quickly fix things on various posts, so they log in, fix a typo or so, and update the post. In this case, I need the hash-value to be deleted so that with the next regular import from the import-file, this post is not skipped as the rule is: every edit must be in the import-file. So the import-file wins every time. And herein lies my problem! How can I detect that a user - and not my import script - is updating a post? Simply deleting the hash-value on save_post for sure is not enough as it would be triggered on programmatically saved posts, too. So what do I check for to make sure, it is an editor/a user who clicked on the update-button? Is checking for $_POST solid enough to detect a manual post-edit?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Product Search in search.php i make a custom product search in woocomerce search.php. but I am not getting correct product name,image, link. Although it worked fine with posts. Tell me what I need to change in my code so that I do not receive posts, but only products. Thank you <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $image = the_post_thumbnail(); if( !empty($image) ): $alt = $image['alt']; $size = 'medium'; $thumb = $image['sizes'][ $size ]; ?> <?php endif; ?> <?php the_post_thumbnail(); ?> <p class="title"><?php the_title(); ?></p> <a href="<?php the_permalink(); ?>" target="_blank">more</a> <?php endwhile; else: ?>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make posts under custom post type not generate a URL / post I have a custom post type called integrations, which is being used to host basic information for integrations. Here's how I've registered the post type: register_post_type( 'Integrations', theme_build_post_args( // $slug, $singular, $plural 'integrations', 'Integration', 'Integrations', array( 'menu_position' => 21, 'has_archive' => false, 'public' => false, 'hierarchical' => false, 'supports' => array('title', 'revisions'), 'taxonomies' => array('categories'), ) ) ); Now, I also have a page called "Integrations" which sits on /integrations. In order to make the archive page use the page template instead, I've used template_include: function custom_integrations_template( $template ) { if ( is_page( 'integrations' ) ) { $new_template = locate_template( array( 'integration-page-template.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; } add_filter( 'template_include', 'custom_integrations_template', 999 ); integration-page-template.php: <?php get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> <?php get_footer(); ?> Now, here's where my issues begin. Under the "Integrations" custom post type, I have a post called "TaxCalc", which sits on /integrations/taxcalc/. However, I also need to create a page, which will be a child of the "Integrations" page which sits on /integrations/taxcalc/. Currently, when I access /integrations/taxcalc/, it takes me to a blank page, which is the post version. Ideally, I do not want the posts under the "Integrations" post type to generate any URLs. To do this, I have tried 'publicly_queryable' => false, however, it does not do anything. How can I prevent a post type from generating URLs and would this cause any knock on effects? For example, prevent me from creating pages under the same slug? Edit (response to @Lewis) Thanks for the answer. I have added 'rewrite' => false, but the issue still remains. Below is an integration post and you can see the permalink in the screenshot too: When I go to that permalink /integrations/card-taxcalc/, it takes me to a page with just the header and footer. Ideally, this post shouldn't exist. Now, below is a screenshot of my TaxCalc page setup: As you can see, this page sits on /integrations/taxcalc/. However, when I go to this URL, it redirects me to /integrations/card-taxcalc/ Edit 2 theme_build_post_args: class theme_PTTaxArgBuilder{ /** * Options will be merged into these, as opposed to using * the standard WordPress defaults. * @var array */ public $postDefaults = array( 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => '' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'supports' => array( 'title', 'editor', 'author', 'excerpt', 'thumbnail' ), ); /** * Options will be merged into these, as opposed to using * the standard WordPress defaults. * @var array */ public $taxonomyDefaults = array( 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'update_count_callback' => '_update_post_term_count', 'query_var' => true, 'rewrite' => array( 'slug' => '' ), ); /** * Build the post types labels based solely on the capitalised * singular and plural form. * @param string $singular Singular & capitalised form for the post type, eg 'Post' * @param string $plural Plural & capitalised form for the post type, eg 'Posts' */ public function buildPostLabels( $singular = 'Post', $plural = 'Posts' ) { if($singular != 'Post' && $plural == 'Posts' ) { $plural = $singular . 's'; } $labels = array( 'name' => _x($plural, 'post type general name', 'lightbox'), 'singular_name' => _x($singular, 'post type singular name', 'lightbox'), 'menu_name' => _x($plural, 'admin menu', 'lightbox'), 'name_admin_bar' => _x($singular, 'add new on admin bar', 'lightbox'), 'add_new' => _x('Add New', $singular, 'lightbox'), 'add_new_item' => __('Add New ' . $singular, 'lightbox'), 'new_item' => __('New ' . $singular, 'lightbox'), 'edit_item' => __('Edit ' . $singular, 'lightbox'), 'view_item' => __('View ' . $singular, 'lightbox'), 'all_items' => __('All ' . $plural, 'lightbox'), 'search_items' => __('Search ' . $plural, 'lightbox'), 'parent_item_colon' => __('Parent ' . $plural . ':', 'lightbox'), 'not_found' => __('No ' . strtolower($plural) . ' found.', 'lightbox'), 'not_found_in_trash' => __('No ' . strtolower($plural) . ' found in Trash.', 'lightbox'), ); return $labels; } /** * Generate the complete arguments ready for post type creation, * including the URL slug and merging of new defaults above. * @param string $slug The URL slug for the post type, eg 'posts' * @param string $singular Singular & capitalised form for the post type, eg 'Post' * @param string $plural Plural & capitalised form for the post type, eg 'Posts' * @param array $args Additional arguments to override the defaults */ public function buildPostArgs( $slug, $singular = 'Post', $plural = 'Posts', $args = array() ) { $args = wp_parse_args($args, $this->postDefaults); $args['rewrite']['slug'] = $slug; $args['labels'] = $this->buildPostLabels($singular, $plural); return $args; } /** * Build the taxonomies labels based solely on the capitalised * singular and plural form. * @param string $singular Singular & capitalised form for the taxonomy, eg 'Category' * @param string $plural Plural & capitalised form for the taxonomy, eg 'Categories' */ public function buildTaxonomyLabels( $singular = 'Category', $plural = 'Categories' ) { if($singular != 'Category' && $plural == 'Categories' ) { $plural = $singular . 's'; } $labels = array( 'name' => _x($plural, 'taxonomy general name'), 'singular_name' => _x($singular, 'taxonomy singular name'), 'search_items' => __('Search ' . $plural), 'all_items' => __('All ' . $plural), 'parent_item' => __('Parent ' . $singular), 'parent_item_colon' => __('Parent ' . $singular . ':'), 'edit_item' => __('Edit ' . $singular), 'update_item' => __('Update ' . $singular), 'add_new_item' => __('Add New ' . $singular), 'new_item_name' => __('New ' . $singular . ' Name'), 'menu_name' => __($plural), // Tags 'popular_items' => __('Popular ' . $plural), 'separate_items_with_commas' => __('Separate ' . strtolower($plural) . ' with commas'), 'add_or_remove_items' => __('Add or remove ' . strtolower($plural)), 'choose_from_most_used' => __('Choose from the most used ' . strtolower($plural)), 'not_found' => __('No ' . strtolower($plural) . ' found.'), ); return $labels; } /** * Generate the complete arguments ready for taxonomy creation, * including the URL slug and merging of new defaults above. * @param string $slug The URL slug for the taxonomy, eg 'category' * @param string $singular Singular & capitalised form for the taxonomy, eg 'Category' * @param string $plural Plural & capitalised form for the taxonomy, eg 'Categories' * @param array $args Additional arguments to override the defaults */ public function buildTaxonomyArgs( $slug, $singular = 'Category', $plural = 'Categories', $args = array() ) { $args = wp_parse_args($args, $this->taxonomyDefaults); $args['rewrite']['slug'] = $slug; $args['labels'] = $this->buildTaxonomyLabels($singular, $plural); return $args; } } /** * These public functions exist as procedural functions to keep in style * with WordPress theme development. */ function theme_build_post_args( $slug, $singular = 'Post', $plural = 'Posts', $args = array() ) { $builder = new theme_PTTaxArgBuilder; return $builder->buildPostArgs($slug, $singular, $plural, $args); } A: Looking at the class and function you're using, this method is a little problematic: public function buildPostArgs( $slug, $singular = 'Post', $plural = 'Posts', $args = array() ) { $args = wp_parse_args($args, $this->postDefaults); $args['rewrite']['slug'] = $slug; $args['labels'] = $this->buildPostLabels($singular, $plural); return $args; } If we ignore your problem, $args['rewrite']['slug'] is going to generate a PHP warning if you set rewrite to false for trying to use it as an array. So if we separate out the call into a variable like this: $args = theme_build_post_args( // $slug, $singular, $plural 'integrations', 'Integration', 'Integrations', [ 'menu_position' => 21, 'hierarchical' => false, 'supports' => array('title', 'revisions'), 'taxonomies' => array('categories'), ] ); register_post_type( 'Integrations', $args ); We can now overwrite what your helper did, e.g. $args = theme_build_post_args( // $slug, $singular, $plural 'integrations', 'Integration', 'Integrations', [ 'menu_position' => 21, 'hierarchical' => false, 'supports' => array('title', 'revisions'), 'taxonomies' => array('categories'), ] ); $args['public'] = false; ... etc ... register_post_type( 'Integrations', $args ); In particular look at what it defines in $postDefaults and override those specifically to match what you want. You might also want to ditch the function and just use the label setup parts to simplify things: $builder = new theme_PTTaxArgBuilder; $args = [ 'labels' => $builder->buildPostLabels( 'Integration', 'Integrations' ), 'menu_position' => 21, 'hierarchical' => false, 'supports' => array('title', 'revisions'), 'taxonomies' => array('categories'), 'public' => false, 'show_ui' => true, ]; register_post_type( 'Integrations', $args );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending GravityForms to custom HTML I am in need of some way to get a standard WordPress page/form to send some data to a custom page that has been created from raw html/JavaScript. The custom page works great within WordPress right now by just putting it in a folder with a file manager plugin. But its previous functionality on a non-WordPress site would accept basic html form data on submit that would pre-fill some of the fields and streamline the page's functionality. I'm open to a variety of solutions, but I am new to WordPress. Do I need to use something other than GravityForms? Is there a simple way to get my custom html/css/javascript folder converted to WordPress and maintain the complex javascript functionality and strict CSS attributes? I don't even know how to access or modify any custom code outside of the standard admin GUI on the website. I still need to keep the functionality of automatically storing user input for all fields on a WordPress form to the website that admins can access through the GUI. This is not a contact form, its just to store user information while triggering the creation of a complex image using a small portion of the text the user filled out.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting the MySQL database My SQL file has been deleted and I don't have a backup of it, if my WP file exists, how can I create a database for it? Thank you in advance for your help
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wordpress site name by url query string Can we have multiple Domains on one wordpress site by DNS Only? Without Multisite, would like to use URL Query omly A: If you own the domains, and their name servers are pointed to your hosting place's name servers, then you can add each domain (via hosting process) and point it to the same folder. That should allow example.com and domain.com to have the same content, while retaining the domains in the address bar. You might have problems with image URLs, though, so you might need a few htaccess commands to fix that.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display notice in block editor after wp_insert_post_data hook I have a custom post type which checks and validates some (custom) meta fields added with it upon publishing. I am using wp_insert_post_data for the purpose: public function __construct() { $this->sconfig= ['post_type'=> 'event', 'slug'=>'events']; add_filter('wp_insert_post_data', array($this, 'validate_event_meta'), 99, 2); add_filter('post_updated_messages', array($this, 'event_save_update_msg'), 10, 1); //add_action('admin_notices', array($this, 'event_save_update_msg')); } function validate_event_meta($postData, $postArray) { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $postData; } if (array_key_exists('post_type', $postData) && $postData['post_type'] === $this->sconfig['post_type']) { if (array_key_exists('post_status', $postData) && $postData['post_status'] === 'publish') { $valstat = $this->get_meta_posted_vals(); /* $valstat['stat'] is 0 or 1 depending on validation success $valstat['log'] has the error message */ if ($valstat['stat'] == 0) { $postData['post_status'] = 'draft'; set_transient(get_current_user_id() . '_event8273_add_notice', 'ERROR: ' . $valstat['log']); add_filter('redirect_post_location', array($this, 'alter_event_save_redirect'), 99); } } } return $postData; } function alter_event_save_redirect($location) { remove_filter('redirect_post_location', __FUNCTION__, 99); $location = remove_query_arg('message', $location); $location = add_query_arg('message', 99, $location); return $location; } function event_save_update_msg($messages) { $message = get_transient(get_current_user_id() . '_event8273_add_notice'); if ($message) { delete_transient(get_current_user_id() . '_event8273_add_notice'); //echo $message; //$messages['post'][99] = $message; $messages[$this->sconfig['post_type']][99] = $message; } return $messages; } Though the validation system is working correctly, I cannot display any notices on the error. Each time the code encounters invalid meta value during 'publish', it reverts the post into 'draft' status and the 'Draft Saved Preview' message pops up. Upon some research, I have found that the block editor uses javascript to display custom notices. But what I cannot understand is how to call the javascript function (file already enqueued in admin) after the validation from wp_insert_post_data. function event_save_alert(errmsg) { ( function ( wp ) { wp.data.dispatch( 'core/notices' ).createNotice( 'error', // Can be one of: success, info, warning, error. errmsg, // Text string to display. { isDismissible: true, // Whether the user can dismiss the notice. // Any actions the user can perform. actions: [ { url: '#', label: 'View post', }, ], } ); } )( window.wp ); } Any kind of help is appreciated. Thanks for reading this far and giving it a thought. A: what I cannot understand is how to call the javascript function (file already enqueued in admin) after the validation from wp_insert_post_data You can use the same approach that Gutenberg uses for saving meta boxes (or custom fields), which you can find here on GitHub. It basically uses wp.data.subscribe() to listen to changes in the editor's state (e.g. whether the editor is saving or autosaving the current post) and after the post is saved (but not autosaved), the meta boxes will be saved. As for the PHP part, you can just store the error in a cookie and read its value using the window.wpCookies API, which is a custom JavaScript cookie API written by WordPress. So for example, I used the following when testing: * *PHP: setcookie( 'event8273_add_notice', 'ERROR: A test error ' . time(), 0, '/' ); *JS: wpCookies.get( 'event8273_add_notice' ) And for checking for and displaying the error, I used this: ( () => { const editor = wp.data.select( 'core/editor' ); // Name of the cookie which contains the error message. const cookieName = 'event8273_add_notice'; // Set the initial state. let wasSavingPost = editor.isSavingPost(); let wasAutosavingPost = editor.isAutosavingPost(); wp.data.subscribe( () => { const isSavingPost = editor.isSavingPost(); const isAutosavingPost = editor.isAutosavingPost(); // Display the error on save completion, except for autosaves. const shouldDisplayNotice = wasSavingPost && ! wasAutosavingPost && ! isSavingPost && // If its status is draft, then maybe there was an error. ( 'draft' === editor.getEditedPostAttribute( 'status' ) ); // Save current state for next inspection. wasSavingPost = isSavingPost; wasAutosavingPost = isAutosavingPost; if ( shouldDisplayNotice ) { const error = wpCookies.get( cookieName ); // If there was an error, display it as a notice, and then remove // the cookie. if ( error ) { event_save_alert( error ); wpCookies.remove( cookieName, '/' ); } } } ); } )(); So just copy that and paste it into your JS file, after your custom event_save_alert() function. * *Make sure that the script's dependencies contain wp-data, utils and wp-edit-post. *You should also load the script only on the post editing screen for your post type. E.g. add_action( 'enqueue_block_editor_assets', function () { if ( is_admin() && 'event' === get_current_screen()->id ) { wp_enqueue_script( 'your-handle', plugins_url( 'path/to/file.js', __FILE__ ), array( 'wp-data', 'utils', 'wp-edit-post' ) ); } } ); A: Since the notice is not a regular one, making a custom javascript notice would be easier. For simplicity, I use the alert() method to show it. /location/our_custom_script.js: const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); if urlParams.get('message') == 99 { alert("Wrong Meta!"); //or anything else } Then we use enqueue_block_editor_assets hook: function our_custom_error() { wp_enqueue_script( 'our_custom_error', plugins_url('/location/our_custom_scripts.js', __FILE__) ); } add_action('enqueue_block_editor_assets', 'our_custom_error'); It's not pretty, but it works, I hope... ps: To make it similar to the real deal, I guess we can copy the original notice style. But I personally would style this kind of error in different manner than the usual notice.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Allow HTML in product attributes and variation for WooCommerce I want to add TM to the name of attribute and a variation in woocommerce but it ended up a plain text. How can I do apply HTML there?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Full site editing templates folder vs block-templates I have a modified Bedrock installation that moves the theme folder outside of the wp-content folder (and the normal app folder for Bedrock). In this setup, the app folder has a data folder that is the new wp-content and outside of it I have the plugins, mu-plugins and themes. This setup has worked for normal themes, but with an FSE theme, the template directory is not working. Normally within the theme folder, you can have a templates folder or block-templates folder (the last one will is deprecated, but still works). When I open the editor, I get a message that the front page template is not found. But if I add that using the gutenberg plugin, it reveals the actual problem (shown in the image below). For some reason the name of the template is the full path of the repo. On my laptop, the repo is called wp so the web is the web root folder. If I rename the templates folder to block-templates it seems to work fine, but I do not want to do that since that one will be depricated (and I cannot influence Twenty Twenty-Three). Is there a filter or setting that I am missing? A: After some more checking, I found the issue. The repo I was setting up, was a template that will be used by other sites, so I saved it in a folder called templates (Full path: /Users/bas/git/work/templates/wp). In the wp-includes/block-template-utils.php the name/slug of the template is decided with the following code. $template_slug = substr( $template_file, // Starting position of slug. strpos($template_file, $template_base_path . DIRECTORY_SEPARATOR) + 1 + strlen($template_base_path), // Subtract ending '.html'. -5 ); $template_base_path is templates in the Twenty-TwentyThree theme, so it split it on the first occurrence of templates which was a lot earlier in the string (see the full path). If I moved my repo to /Users/bas/git/work/template/wp it all works since the string is splitted correctly.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the dynamic number after the last "/" of external url i want to grab the last dynamic numbers of an external url. I m not good in php, can someone help? https://data.aboss.com/v1/agency/1001/101010/events/xxxxxx $url = https://data.aboss.com/v1/agency/1001/101010/events/; $value = substr($url, strrpos($url, '/') + 1); value="<?php echo $value; ?>" result should be xxxxxx.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove slug from CPT correctly? Im trying to remove slug from my Custom Post Types. I've added 'rewrite' => array( 'slug' => '/' ) and based on this post https://wordpress.stackexchange.com/a/144356/116847 I've added: add_action( 'pre_get_posts', 'wpse_include_my_post_type_in_query' ); function wpse_include_my_post_type_in_query( $query ) { // Only noop the main query if ( ! $query->is_main_query() ) return; // Only noop our very specific rewrite rule match if ( 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) return; // Include my post type in the query if ( ! empty( $query->query['name'] ) ) $query->set( 'post_type', array( 'post', 'page', 'physio_methods', 'treatment' ) ); } add_action( 'parse_query', 'wpse_parse_query' ); function wpse_parse_query( $wp_query ) { if( get_page_by_path($wp_query->query_vars['name']) ) { $wp_query->is_single = false; $wp_query->is_page = true; } } otherwise, posts was mixed with pages and gets 404. But now, I have problem with posts categories - link to category display post, not the archive page. I need to fully remove slug from my CPT. Is there any good (no plugin) solution for that? Thanks! A: This is a two-step process. First, you need to remove the slug from the default URL. (use a unique slug while registering the CPT). function wpse413969_remove_cpt_slug( $post_link, $post ) { if ( $post->post_type == 'YOUR_CPT' && $post->post_status == 'publish') { $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); } return $post_link; } add_filter( 'post_type_link', 'wpse413969_remove_cpt_slug', 10, 2 ); Then include your CPT in main query. function wpse413969_add_cpt_names_to_main_query( $query ) { // Return if this is not the main query. if ( ! $query->is_main_query() ) { return; } // Return if this query doesn't match our very specific rewrite rule. if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) { return; } // Return if we're not querying based on the post name. if ( empty( $query->query['name'] ) ) { return; } // Add CPT to the list of post types WP will include when it queries based on the post name. $query->set( 'post_type', array( 'post', 'page', 'YOUR_CPT' ) ); } add_action( 'pre_get_posts', 'wpse413969_add_cpt_names_to_main_query' ); This, IMHO, is a bad practice. There are some good reasons why WordPress includes the slug in CPTs. To avoid conflict with default post and pages, always use unique slugs for your CPT posts.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: uploading image to wordpress site with javascript fetch function failed I tried to turn an html div element into an png image than I want upload this image in my wordpress site . I wrote following codes, But it is showing image upload failed. Can You find where is wrong. Any help to correct this code appreciated. // Capture the div element as a PNG image function convertDivToImage() { html2canvas(document.querySelector("#wgr")).then(canvas => { const imageData = canvas.toDataURL("image/png"); // Set the Content-Type header let headers = new Headers(); headers.append("Content-Type", "image/png"); // Set the authorization header const authHeader = "Basic " + btoa("username:password"); // Upload the image to the WordPress site using the REST API return fetch("/wp-json/wp/v2/media", { method: "POST", headers: { "Content-Type": "image/png", "Authorization": authHeader}, body: JSON.stringify({ file: imageData, "Content-Disposition": `attachment; filename="wgr_image.png"` }) }) .then(response => { if (!response.ok) { throw new Error("Failed to upload image"); } return response.json(); })
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress plugin that can show google images for a keyword/page title? I am trying to build a celebrity gallery sort of site, where the pages are basically list of celebrity pages with their images. I wanted a plugin that I can use to automatically fetch/show images from the internet for that celebrity's name. For example, if the celebrity is Ryan Reynolds, the page when opened would automatically show images of him from google without me manually adding the images. Can someone please help me know if there are any plugins for this or code that I can use for this?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Audio/Video files doesn't want to be played on directorist plugin listings Simply i have directorist plugin which allows me to create listings, The problem is when i try to add Audio/Video in the litings from the media library or even outside of the website it doesn't want to be played. on the other hand if i added the same Audio/video to a regular wordpress post it works just fine. i have tried to troubleshoot for any plugins conflicts, i only activated the directorist plugin and tried but the same problem still exist, does anybody knows what might be causing the problem. here is a linnk to one of my listings https://doclures.com/directory/east-gippsland-sportfishing/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Woocommerce admin order email customize - remove product short description I am currently trying to remove the short description from the product from the admin email (new order). I have already used the search but can't really find a suitable solution. Maybe you have another idea. I took a screenshot for better understanding ;)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter the URL of thumbnail size in the Media Grid and admin pages I need to filter the URL of the thumbnails in the Media Grid (or any admin pages) by getting the original image URL and adding some URL parameters to generate the thumbnail on the cloud using the AWS Serverless Image Handler. Suppose I have this original image URL: https://cdn.example.com/2023/02/20/1234567890-original.jpg And I don't have any sizes metadata stored in DB for that image. I need to find the proper hook where I can return something like this URL for the thumbnails in the Media Grid or any image displayed on the admin pages: https://cdn.example.com/2023/02/20/1234567890-original.jpg?size=240x240 I'm planning here to avoid storing any thumbnail sizes in the attachment metadata in DB, and then generating any needed size on the fly using the mentioned library. Is there any proper hook that is being triggered before returning the thumbnail size URL?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom slugs with dates & IDs on Custom Post Type Trying to do something with the rewrite argument on custom post types. I'm after 2 different things here for 2 different custom post types. 1: Slugs which look like this post-name-year-month-day So the URL will be something like .com/post-type-1-slug/post-name-year-month-day 2: More or less the same but with the ID post-name-id So the URL will be something like .com/post-type-2-slug/post-name-id I'm sure this is pretty easy to do A: Yes, it's not hard to do that. * *Just register your post type and enable rewriting for that post type, i.e. set rewrite to true. *Once registered, modify its permalink structure like so: global $wp_rewrite; $wp_rewrite->extra_permastructs['<post type>']['struct'] = '<your structure here>'; *Use the post_type_link filter to replace rewrite tags like %post_id% in the permalink URL. If you need to use custom rewrite tags like %post_date% in the permalink structure, you can add the custom tags using add_rewrite_tag(), after you set the structure. *Remember to flush the rewrite rules (i.e. re-save your permalinks) every time you changed the rewrite args, including when you simply set rewrite to true or false. You can programmatically flush the rules using flush_rewrite_rules(), however, it should only be used when necessary, e.g. upon plugin activation. As for the non-programmatic way, simply visit the Permalink Settings admin page without having to click the "save" button. Working examples for you * *This is for the structure post-type-1-slug/post-name-year-month-day where a sample URL might look like https://example.com/type1/hello-world-2023-02-20/, and I'm using a custom rewrite tag %post_date% for the year-month-day part. (It's up to you if you'd rather use multiple tags, e.g. %year%, %monthnum%, and %day%) add_action( 'init', 'my_register_type1_cpt' ); function my_register_type1_cpt() { register_post_type( 'type1', [ 'public' => true, 'label' => 'Type 1', 'rewrite' => true, // other args ] ); global $wp_rewrite; $wp_rewrite->extra_permastructs['type1']['struct'] = 'type1/%type1%-%post_date%'; // Add a structure tag for dates in either of these form: 2023-02-20 or 2023-2-20. add_rewrite_tag( '%post_date%', '(\d{4}-\d{1,2}-\d{1,2})' ); // If you use %year%, %monthnum%, %day% and/or %post_id%, then those are core // structure tags in WordPress, hence you do not need to add them manually. // However, you still need to manually replace them in the permalink URL! } add_filter( 'post_type_link', 'my_type1_post_type_link', 10, 2 ); function my_type1_post_type_link( $post_link, $post ) { if ( $post && 'type1' === $post->post_type ) { $post_date = wp_date( 'Y-m-d', strtotime( $post->post_date ) ); return str_replace( '%post_date%', $post_date, $post_link ); } return $post_link; } *This is for the structure post-type-2-slug/post-name-id where a sample URL might look like https://example.com/type2/hello-world-123/ with 123 being the post ID. add_action( 'init', 'my_register_type2_cpt' ); function my_register_type2_cpt() { register_post_type( 'type2', [ 'public' => true, 'label' => 'Type 2', 'rewrite' => true, // other args ] ); global $wp_rewrite; $wp_rewrite->extra_permastructs['type2']['struct'] = 'type2/%type2%-%post_id%'; } add_filter( 'post_type_link', 'my_type2_post_type_link', 10, 2 ); function my_type2_post_type_link( $post_link, $post ) { if ( $post && 'type2' === $post->post_type ) { return str_replace( '%post_id%', $post->ID, $post_link ); } return $post_link; } Note: %type1% and %type2% are the post name/slug and you don't need to replace it manually, i.e. WordPress will do that for you.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress: New user role which is ONLY allowed to manage media I would like to have a new user role (or restrict a role which is already available from Wordpress) which can only manage media (upload, delete pictures etc.) in the wordpress backend - every other possibility in the wordpress backend is not allowed and not visible. Used user role editor without success A: The add_role function should give you what you're looking for. Here's an example of using it to add a new role that allows the user to upload and delete media: function wpse413985_add_role(){ /* Check if the role already exists, since we don't need to add it again every time the site loads. */ if ( !get_role( 'wpse413985_media_manager' ) ){ add_role( 'wpse413985_media_manager', __( 'Media Manager', 'wpse413985-textdomain' ), array( 'upload_files' => true, 'delete_posts' => true )); } } add_action( 'init', "wpse413985_add_role" ); A user with the 'media manager' role in this example will see a link to the media library but none of the other admin screens. The delete posts capability is necessary to delete pictures because media files count as 'posts' in wordpress. The user won't be able to delete regular posts because they can't visit that part of the admin. This function would go in a theme's functions.php. However, you could also put it in a plugin. In that case, instead of hooking to the init action, you could use register_activation_hook. That would eliminate the need for the conditional.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to get product_id with $package['contents'][0]['product_id'] Manually creating a custom plugin database: CREATE TABLE wp_pppzpc_shipping_rates ( id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, product_id INT(11) NOT NULL, country_code VARCHAR(2) NOT NULL, zone_id INT(11) NOT NULL, shipping_rate DECIMAL(10,2) NOT NULL, PRIMARY KEY (id) ); I then populate the database like so: INSERT INTO wp_pppzpc_shipping_rates (product_id, country_code, zone_id, shipping_rate) VALUES (29303, "AU", 1, 255.95); PHP in /wp-content/plugins/my-plugin: function get_pppzpc_shipping_rate( $product_id, $country_code, $zone_id ) { global $wpdb; $table_name = $wpdb->prefix . 'pppzpc_shipping_rates'; $query = $wpdb->prepare( "SELECT shipping_rate FROM $table_name WHERE product_id = %d AND country_code = %s AND zone_id = %d", $product_id, $country_code, $zone_id ); $result = $wpdb->get_var( $query ); return $result ? $result : false; } add_filter( 'woocommerce_package_rates', 'pppzpc_modify_shipping_rates', 10, 2 ); function pppzpc_modify_shipping_rates( $rates, $package ) { foreach ( $rates as $rate_key => $rate ) { if ( $rate->method_id == 'flat_rate' ) { $product_id = $package['contents'][0]['product_id']; $country_code = $package['destination']['country']; $zone_id = WC_Shipping_Zones::get_zone_matching_package( $package )->get_id(); $shipping_rate = get_pppzpc_shipping_rate( $product_id, $country_code, $zone_id ); if ( $shipping_rate ) { $rates[$rate_key]->cost = $shipping_rate; } } } return $rates; } Woocommerce does not appear to use my custom shipping rate in cart and checkout contexts. It fails somehow. For debugging, I add into pppzpc_modify_shipping_rates(): error_log( print_r( compact( 'product_id', 'country_code', 'zone_id' ), true ) ); which gives ( [product_id] => [country_code] => AU [zone_id] => 1 ) suggesting that product is not being obtained successfully. It appears I am unable to get the $product_id of the current product with $product_id = $package['contents'][0]['product_id']; Please explain why this is failing and advise a solution.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: if get_post_meta do something I use this to show custom product number field: <div class="phone-num"> Phone: <?php echo get_post_meta(get_the_ID(), '_custom_product_number_field', true); ?> </div> How should nothing be displayed if the field is empty? A: If you mean you don't want the <div class="phone-num"> to appear at all, here's how: <?php $phone_number = get_post_meta(get_the_ID(), '_custom_product_number_field', true ); if ( ! empty( $phone_number ) ) : ?> <div class="phone-num"> Phone: <?php echo $phone_number; ?> </div> <?php endif; ?>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a page to a menu while creating a new page or editing a page? Is there a good plugin out there for adding a page to a menu while creating the page or, while editing a page, moving its associated menu item to a different part of the menu? Ideally I'd like to be able to place the page in the menu with the same kind of precision as on the menu admin page. A: OK, this plugin still seems to work well with WP 6.1.1: https://wordpress.org/plugins/auto-subpage-menu/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CPT template is not being automatically used single post pages I created a plugin and added a custom post type to the plugin. I then created a template using the hierarchy single-{custom-post-type}.php. So my cpt slug is wppro-events and the single post template is called single-wppro-events.php. I also added to the top of the template file the comment section below but my post template is not being used for the cpt. Any idea why it is not being used. Also page attributes on the edit page isn't showing the option to change the template either. Astra is the theme I am using. Any idea why this isn't working? /* Template Name: Layout One Template Post Type: wppro-events */ I also tried the below code but still didn't work: /* Filter the single_template with our custom function*/ add_filter('single_template', 'my_custom_template'); function my_custom_template($single) { global $post; /* Checks for single template by post type */ if ( $post->post_type == 'Event Items' ) { if ( file_exists( PLUGIN_PATH . '/single-wppro-events.php' ) ) { return PLUGIN_PATH . '/single-wppro-events.php'; } } return $single; } Additional Information Requested Register CPT code function wppro_register_events_post_type() { $labels = array( 'name' => __( 'Events', 'wppro' ), 'singular_name' => __( 'Event', 'wppro' ), 'add_new' => __( 'Add New Event', 'wppro' ), 'add_new_item' => __( 'Add New Event', 'wppro' ), 'edit_item' => __( 'Edit Event', 'wppro' ), 'new_item' => __( 'New Event', 'wppro' ), 'view_item' => __( 'View Event', 'wppro' ), 'search_items' => __( 'Search Events', 'wppro' ), 'not_found' => __( 'No events found', 'wppro' ), 'not_found_in_trash' => __( 'No events found in trash', 'wppro' ), ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => 'wppro-events' ), 'menu_position' => 20, 'menu_icon' => 'dashicons-calendar', 'supports' => array( 'title', 'editor', 'thumbnail' ), ); register_post_type( 'wppro-events', $args ); } add_action( 'init', 'wppro_register_events_post_type' ); The plugin is a standalone one in wp-contents/plugins. I put the template file in the plugin's root directory. A: A few points. * *Custom template files for single posts (not pages) within plugin directory normally needs an action filter, so, you must use it in your case. *Page templates are different then custom templates for any custom or built-in post type. To have page templates under Attributes etc. or in Astra, you need files like page-template1.php or page-template2.php having template header comments. Note that these are page templates, not post templates. In your case, to let the WP automatically pick your custom template for a custom post type from within your plugin directory, keep using the template action filter that you are already using. *In your template filter, you are matching post_type which is right, however, the value for it is wrong. Change Event Items to wppro-events in the action filter in line if ( $post->post_type == 'Event Items' ) and then check. *Still seeing old template? Flush the permalinks by saving permalinks for once under Admin Dashboard > Settings > Permalinks and then check again. Let me know how it goes.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Please Help Me, How to Fix PHP Error Undefined Array Key "srcset" please help me, my website notice error Message. On error.log notice Undefined Array Key "srcset" This is my code on WordPress, and i'am use PHP Version 8.0. function my_plugin_filter_attachment_webp( $attr ) { global $webp; if ( ! is_singular( array( 'post', 'page' ) ) && ! ( is_home() || is_tag() || is_category() || is_tax() ) || ( true !== $webp ) || ( is_admin() ) ) {return $attr; } else { $attr['src'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['src'] ); $attr['src'] = str_replace( array( '.jpg' ), '.jpg.webp', $attr['src'] ); $attr['src'] = str_replace( array( '.png' ), '.png.webp', $attr['src'] ); $attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] ); $attr['srcset'] = str_replace( array( '.jpg' ), '.jpg.webp', $attr['srcset'] ); $attr['srcset'] = str_replace( array( '.png' ), '.png.webp', $attr['srcset'] ); return $attr; } } add_filter( 'wp_get_attachment_image_attributes', 'my_plugin_filter_attachment_webp', 10, 1 ); How to fix, my dear friend? A: Latest versions of PHP get mad if you try to reference array parameters that don't exist. It's a 'warning' type error, so the page will still load. You need to test for existence of an array parameter before you reference it. So instead of $attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] ); Put those array references in an IF statement if (isset($attr['srcset']) { $attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] ); } That will eliminate that warning message. You will have to do similar to all array elements that may not exist. You also do something like this: $attr['srcset'] = ($attr['srcset']) ? str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] ) : ""; Which will set that array element to blank if it doesn't exist, so you won't have to test for it the next time you use it.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: $wpdb->prepare referencing a const without a coding guideline warning I have defined my database table names as constants in a base class and use them throughout my code. protected const MAP_KEY_TABLE = 'eds_map_keys'; If I use them like this I get a warning to use place holders. $keys = $wpdb->get_results( 'SELECT * FROM ' . self::MAP_KEY_TABLE . ' WHERE key_type = "map_key"', OBJECT ); $mapkey = $keys[0]->key_value; if I use place holders like this: $keys = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %1s WHERE key_type = "geo_key";', self::MAP_KEY_TABLE ), OBJECT ); // db call ok. $map_key_geo = $keys[0]->key_value; I get a warning that: "message": "Complex placeholders used for values in the query string in $wpdb->prepare() will NOT be quoted automagically. Found: %1s." As suggested in a comment I tried $1$s but the warning still persists. WP Version 6.1.1, PHP Version 8.0.18, PHP_CodeSniffer version 3.7.1 I don't know if the guidelines are version specific but they were installed like this. composer require --dev wp-coding-standards/wpcs composer require --dev dealerdirect/phpcodesniffer-composer-installer I'd really like to get rid of the messages about coding style but have been stuck on this one for a while. Any suggestions greatly appreciated. A: I'd really like to get rid of the messages about coding style Despite not recommended, you can ignore/whitelist warnings and errors for a line or block of code using special PHPCS/WPCS comments which you can find here: * *Ignoring Parts of a File *Whitelisting code which flags errors Working examples: ( Note: WordPress accepts all these syntaxes without giving any errors/warnings, however, it's WPCS which does not accept them ) * *This uses // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared to ignore this error: "Use placeholders and $wpdb->prepare(); found ..." $keys = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 'SELECT * FROM ' . self::MAP_KEY_TABLE . ' WHERE key_type = "map_key"', OBJECT ); *This uses // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder to ignore this warning: "Complex placeholders used for values in the query string in $wpdb->prepare() will NOT be quoted automagically. Found: ..." (see also lines 25-27 there) $keys = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder 'SELECT * FROM %1$s WHERE key_type = "map_key"', self::MAP_KEY_TABLE ), OBJECT ); *This uses // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared to ignore this error: "Use placeholders and $wpdb->prepare(); found interpolated variable ..." $table = self::MAP_KEY_TABLE; $keys = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT * FROM $table WHERE key_type = 'map_key'", OBJECT ); A better solution, or a trick, which does not result in those warnings/errors * *Add the table name as a property in the global $wpdb object, i.e. $wpdb->eds_map_keys = self::MAP_KEY_TABLE;. *Then use that in your SQL commands, e.g. FROM $wpdb->eds_map_keys. This works because WPCS allows $wpdb->. (Otherwise, you would not be able to use $wpdb->posts, $wpdb->postmeta, $wpdb->terms, etc. which references the core tables in WordPress) However, note that $this->eds_map_keys (which could be a private property) or $some_other_object->eds_map_keys will not work, i.e. not accepted by WPCS. Additional Notes regarding the first parameter for $wpdb->prepare() * *The documentation stated that "for compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes added by this function, so should be passed with appropriate quotes around them". And unfortunately, at the time of writing, WPCS will not accept them when used for table names, e.g. FROM %1$s or FROM `%1$s` will result in the UnquotedComplexPlaceholder error. *The correct argument swapping format is %<number>$s (note the $) and not %<number>s. So as I commented, you should use %1$s instead of %1s. See the PHP manual for more details.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Permalink settings are stuck on https, will not update to http One of my sites, which use to be https, has been changed to http, but the permalink setting on the WP dashboard still says https:// and will not revert to http. The SSL certificate has been revoked & removed (Letscrypt/ Nginx server). The site's nginx config confirms this, only port 80 is listed. The following have been checked: * *Under General settings, the Wordpress & Site url have been changed to http *When that didn't work I added the following to wp-config define('WP_HOME','http://example.com'); define('WP_SITEURL','http://example.com'); define( 'WP_CONTENT_URL', 'http://example.com/wp-content' ); then I added following to the themes function.php define( 'WP_HOME', 'http://example.com' ); define( 'WP_SITEURL', 'http://example.com' ); Still no joy. I ran a search & replace https with http on the DB, again no change. I can load the site if I paste the url with http into the address bar, but clicking any link on the site reverts to https. I can only assume there's a borked setting somewhere in the DB, but I can't find it. Any help on this perplexing problem would be appreciated.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add Custom Taxonomy Terms as CSS Classes for CPT Posts in an Elementor Loop Item Template * *I have an Elementor Loop Item Template that is used to display posts from a custom post type called "Project Photos." *I want the ability to filter the results based on the following 4 different taxonomies: * *application *fence-type *fence-style *privacy-level *the filter (css/jquery from JCwebTECH on YouTube) would be in the form of buttons that select the divs that have the css class associated with the custom taxonomy terms. *the Elementor div that needs targeting I believe is: <div class="elementor-element elementor-element-ee4ea21 e-con-boxed e-con" data-id="ee4ea21" data-element_type="container"> *Is there a way to add a function or filter to my function.php file that could grab all the taxonomy term slugs (no spaces) that a post has associated with it, and insert them into the div mentioned above as css classes? Here is an example page: https://androscogginfence.com/our-work/ OR - If you have other suggestions on how to best filter custom post types by multiple custom taxonomy terms, within an Elementor page, Id love to hear it. :) Thanks! :)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding a function in a class from the Wordpress plugin Elementor Pro about Product Upsells I would like to find a way to override the following file in the plugin Elementor Pro for wordpress to add an "else" in "protected function render()". I want to be able to display a message when there is no upsell available in my carrousel from element pro. <?php namespace ElementorPro\Modules\Woocommerce\Widgets; use Elementor\Controls_Manager; use Elementor\Core\Kits\Documents\Tabs\Global_Colors; use Elementor\Core\Kits\Documents\Tabs\Global_Typography; use Elementor\Group_Control_Typography; if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } class Product_Upsell extends Products_Base { public function get_name() { return 'woocommerce-product-upsell'; } public function get_title() { return esc_html__( 'Upsells', 'elementor-pro' ); } public function get_icon() { return 'eicon-product-upsell'; } public function get_keywords() { return [ 'woocommerce', 'shop', 'store', 'upsell', 'product' ]; } protected function register_controls() { $this->start_controls_section( 'section_upsell_content', [ 'label' => esc_html__( 'Upsells', 'elementor-pro' ), ] ); $this->add_columns_responsive_control(); $this->add_control( 'orderby', [ 'label' => esc_html__( 'Order By', 'elementor-pro' ), 'type' => Controls_Manager::SELECT, 'default' => 'date', 'options' => [ 'date' => esc_html__( 'Date', 'elementor-pro' ), 'title' => esc_html__( 'Title', 'elementor-pro' ), 'price' => esc_html__( 'Price', 'elementor-pro' ), 'popularity' => esc_html__( 'Popularity', 'elementor-pro' ), 'rating' => esc_html__( 'Rating', 'elementor-pro' ), 'rand' => esc_html__( 'Random', 'elementor-pro' ), 'menu_order' => esc_html__( 'Menu Order', 'elementor-pro' ), ], ] ); $this->add_control( 'order', [ 'label' => esc_html__( 'Order', 'elementor-pro' ), 'type' => Controls_Manager::SELECT, 'default' => 'desc', 'options' => [ 'asc' => esc_html__( 'ASC', 'elementor-pro' ), 'desc' => esc_html__( 'DESC', 'elementor-pro' ), ], ] ); $this->end_controls_section(); parent::register_controls(); $this->start_injection( [ 'at' => 'before', 'of' => 'section_design_box', ] ); $this->start_controls_section( 'section_heading_style', [ 'label' => esc_html__( 'Heading', 'elementor-pro' ), 'tab' => Controls_Manager::TAB_STYLE, ] ); $this->add_control( 'show_heading', [ 'label' => esc_html__( 'Heading', 'elementor-pro' ), 'type' => Controls_Manager::SWITCHER, 'label_off' => esc_html__( 'Hide', 'elementor-pro' ), 'label_on' => esc_html__( 'Show', 'elementor-pro' ), 'default' => 'yes', 'return_value' => 'yes', 'prefix_class' => 'show-heading-', ] ); $this->add_control( 'heading_color', [ 'label' => esc_html__( 'Color', 'elementor-pro' ), 'type' => Controls_Manager::COLOR, 'global' => [ 'default' => Global_Colors::COLOR_PRIMARY, ], 'selectors' => [ '{{WRAPPER}}.elementor-wc-products .products > h2' => 'color: {{VALUE}}', ], 'condition' => [ 'show_heading!' => '', ], ] ); $this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'heading_typography', 'global' => [ 'default' => Global_Typography::TYPOGRAPHY_PRIMARY, ], 'selector' => '{{WRAPPER}}.elementor-wc-products .products > h2', 'condition' => [ 'show_heading!' => '', ], ] ); $this->add_responsive_control( 'heading_text_align', [ 'label' => esc_html__( 'Text Align', 'elementor-pro' ), 'type' => Controls_Manager::CHOOSE, 'options' => [ 'left' => [ 'title' => esc_html__( 'Left', 'elementor-pro' ), 'icon' => 'eicon-text-align-left', ], 'center' => [ 'title' => esc_html__( 'Center', 'elementor-pro' ), 'icon' => 'eicon-text-align-center', ], 'right' => [ 'title' => esc_html__( 'Right', 'elementor-pro' ), 'icon' => 'eicon-text-align-right', ], ], 'selectors' => [ '{{WRAPPER}}.elementor-wc-products .products > h2' => 'text-align: {{VALUE}}', ], 'condition' => [ 'show_heading!' => '', ], ] ); $this->add_responsive_control( 'heading_spacing', [ 'label' => esc_html__( 'Spacing', 'elementor-pro' ), 'type' => Controls_Manager::SLIDER, 'size_units' => [ 'px', 'em' ], 'selectors' => [ '{{WRAPPER}}.elementor-wc-products .products > h2' => 'margin-bottom: {{SIZE}}{{UNIT}}', ], 'condition' => [ 'show_heading!' => '', ], ] ); $this->end_controls_section(); $this->end_injection(); } protected function render() { $settings = $this->get_settings_for_display(); // Add a wrapper class to the Add to Cart & View Items elements if the automically_align_buttons switch has been selected. if ( 'yes' === $settings['automatically_align_buttons'] ) { add_filter( 'woocommerce_loop_add_to_cart_link', [ $this, 'add_to_cart_wrapper' ], 10, 1 ); } $limit = '-1'; $columns = 4; $orderby = 'rand'; $order = 'desc'; if ( ! empty( $settings['columns'] ) ) { $columns = $settings['columns']; } if ( ! empty( $settings['orderby'] ) ) { $orderby = $settings['orderby']; } if ( ! empty( $settings['order'] ) ) { $order = $settings['order']; } ob_start(); woocommerce_upsell_display( sanitize_text_field( $limit ), sanitize_text_field( $columns ), sanitize_text_field( $orderby ), sanitize_text_field( $order ) ); $upsells_html = ob_get_clean(); if ( $upsells_html ) { $upsells_html = str_replace( '<ul class="products', '<ul class="products elementor-grid', $upsells_html ); // PHPCS - Doesn't need to be escaped since it's a WooCommerce template, and 3rd party plugins might hook into it. echo $upsells_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } ///////// The code I want to add /////// else { echo "no product available"; } ///////// The code I want to add /////// if ( 'yes' === $settings['automatically_align_buttons'] ) { remove_filter( 'woocommerce_loop_add_to_cart_link', [ $this, 'add_to_cart_wrapper' ] ); } } public function render_plain_content() {} public function get_group_name() { return 'woocommerce'; } } I tried many things but with no success. For example, put the same file in child theme with same path or calling it with the namespace. I can't use the filters and I have no idea how to do it properly. Right now it is working but if I update the plugin I loose the modification.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Create LastMod and Update Date Only on Taxonomy Category and Tags Please help me, How to make Lastmod and Update Date on manually Sitemap on Taxonomy Category and Tags. I made a manual Sitemap in WordPress, but I'm confused about adding a special Lastmod to the Taxonomy and not to the Post. Please friends, help me, I hope the knowledge you have and have will be of use to me and many people.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove Edit Attachment Button in Wordpress Mediathek -> see Screenshot i would like to remove the button via css or hook, thanks for your help!!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can we change user profiles into a custom post type? im currently using beaver builder for my wordpress website. I like to Query and display my list of users just like custom type post. Is there any way we change change the database of wp users into a custom type post so I can display my authors just like a custom type post? Thanks.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wordpress rest api authentication failed I wanted to upload an canvas element as image to wordpress with rest api, i found following error, "rest_cannot_create" data : {status: 401} message : "Sorry, you are not allowed to create posts as this user." [[Prototype]] : Object <pre><canvas id="myCanvas" width="200" height="200"></canvas> <button onclick="uploadImage()">Upload Image</button></pre> <script> function uploadImage() { var canvas = document.getElementById("myCanvas"); var dataURL = canvas.toDataURL("image/png"); var blobBin = atob(dataURL.split(',')[1]); var array = []; for(var i = 0; i < blobBin.length; i++) { array.push(blobBin.charCodeAt(i)); } var file=new Blob([new Uint8Array(array)], {type: 'image/png'}); var formData = new FormData(); formData.append("file", file); fetch('/wp-json/wp/v2/media', { headers: { 'Authorization': 'Basic ' + btoa('safa75:Pass2333') }, method: 'POST', body: formData }) .then(function(response) { return response.json(); }) .then(function(data) { console.log(data); // Log the response data to the console }) .catch(function(error) { console.error(error); // Log any errors to the console }); } window.addEventListener("load", function() { // Draw on the canvas element var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, 150, 75); }); </script> `
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when loading Dashboard When I login, I see a white page with the Error report: TypeError thrown array_pop(): Argument #1 ($array) must be of type array, null given I think that is sicne I updated PHP to version 8. The error only comes on wp-admin/index.php When I go to the Homepage after the Error message I see all posibilities of Wordpress so that I can work with the backend. I can make updates, create and edith pages,... only the Dashboard does not work. I have tryed with PHP 8.0, 8.1, 8.2 The Version of Wordpress is the newest 6.1.1
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't seem to check off a category checkbox with jquery? I've got the following simple jquery test script to test if I can check off a category box in the right sidebar when creating a new post: jQuery(document).ready(function($) { console.log('js file loaded'); // Check the "Public" checkbox by default $('#inspector-checkbox-control-4').prop('checked', true); }); I get the console message but the box is never checked. I have the correct id. This probably has something to do with load order. I'm loadig the jquery from a plugin with: function pu_my_plugin_scripts() { wp_enqueue_script( 'my-plugin-script', plugins_url( './js/my-plugin-script.js', __FILE__ ), array( 'jquery' ), null, true ); } add_action( 'admin_enqueue_scripts', 'pu_my_plugin_scripts' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I prevent a user from selecting exactly one of two (not both or none) categories on a post? I have Categories A, B, C, D and E. When creating a post, I want the user to be able to check of either A or B, but not one or both and 0 or more other categories. And I want Category A to be checked by default when they open the page if this is a new post. If it's an existing post, the categories should reflect the existing categories. I initially tried pulling this off with some jQuery but ran into some serious roadblocks. I'd prefer to allow the user to get immediate feedback and allow them to see categories A/B toggle themselves on an off. But I don't know react. Not sure if I have any good options besides writing some PHP code on the save_post hook and sending back an error if the user fails to select either Category A or B, or neither, or both.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to do WooCommerce Specific products checkout from cart In WooCommerce is there a way to checkout only specific items from the cart, leaving other items as is in the cart (like marketplace concept) ?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use inline callable for hooks and filters I created a WordPress plugin and I've used inline callable function for some hooks and filters, like this: add_action( "init", function(){ // some codes } ); now I want to publish my plugin into WordPress repository but I'm not sure it is ok because actions and filters cannot be removed when we use anonymous functions. Now I want to know if WordPress accept my plugin or not and is it better to use named functions instead? A: When developing a WordPress Plugin that uses custom do_action and apply_filters it's always better to use a callback function. They don't explicitly say that you aren't allowed to use anonymous functions but whenever you can, and when it's appropriate, use a callback. From the plugin development docs about actions Create a callback function First, create a callback function. This function will be run when the action it is hooked to is run. The callback function is just like a normal function: it should be prefixed, and it should be in functions.php or somewhere callable. The parameters it should accept will be defined by the action you are hooking to; most hooks are well-defined, so review the hooks docs to see what parameters the action you have selected will pass to your function. That being said, if you have some internal logic that relies on do_action/apply_filters that you don't want the user to mess with, then use an anonymous function. It's your plugin, and it's up to you how much control and extensibility you want to provide your developer users. Same goes for when you're using add_action/add_filter. If you're using it on your own actions and filters and you don't want users to mess with them, use anonymous function. But if you use it with built in actions/filters you might consider using a callback so users can decide if they want it or maybe modify it.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove escalation mark (!) at the end of the URLs in WordPress? I'm getting an escalation mark (!) at the end of the URLs in WordPress. And it is changing the page layout to a blog layout. Don't know why it is happening. Getting like https://www.example.com/usefull-software! but the original URL is like https://www.example.com/usefull-software How to solve this one? Thank You.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: WP Permission still set to Not Writable after I change the permission for the whole folder and files I have change permission via FTP but still not working Need help!!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how should i get products based on tags in woocommerce i want to write a shortcode to get or filter products by tags. for example, i want to get all products that have both 'male' and 'sport' tags. i don't want to separately find product that have 'male' and then find products have 'sport'. all product that have both tags should be shown and if a product hasnt one or all of them should be ignored. i have written this: function woo_products_by_tags_shortcode( $atts, $content = null ) { // Get attribuets extract(shortcode_atts(array( "tags" => '' ), $atts)); ob_start(); // Define Query Arguments $args = array( 'post_type' => 'product', 'product_tag' => $tags ); // Create the new query $loop = new WP_Query( $args ); // Get products number $product_count = $loop->post_count; // If results if( $product_count > 0 ) : // Start the loop while ( $loop->have_posts() ) : $loop->the_post(); global $product; global $post; echo "<div class='products_item'>"; if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.$woocommerce->plugin_url().'/assets/images/placeholder.png" alt="" width="'.$woocommerce->get_image_size('shop_catalog_image_width').'px" height="'.$woocommerce->get_image_size('shop_catalog_image_height').'px" />'; echo "<h2 class='product_title'><a href='".get_post_permalink()."'>" . $thePostID = $post->post_title. "</a></h2>"; echo "</div>"; endwhile; wp_reset_query(); endif; // endif $product_count > 0 return ob_get_clean(); } add_shortcode("woo_products_by_tags", "woo_products_by_tags_shortcode"); in above code i have two problems: 1- if $tag is null all products would be return 2- all products that have at least one the tags would be returned but i want to show products that have all tags
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: redirect site links form joomla to WordPress I own an old site based on joomla, and I'm planning to build a new site (from the ground up) with WordPress (and Elementor). What is the best way to redirect the existing site links without losing SEO? The existing site is based on a subdomain that I want to redirect to the root URL, and other pages that need to be routed manually (individually). But many pages that I would like to simply be redirected to the home page (or another page) without getting a 404 error. A: When you migrate your site from Joomla to WordPress, it is essential to ensure that you do not lose the SEO value of your existing site. One of the critical steps in this process is to redirect your old site's URLs to the corresponding pages on your new site. To redirect your existing site links without losing SEO, follow these steps: 1- Create a backup of your Joomla site. 2- Set up your new WordPress site with the Elementor page builder. 3- Install and activate the "Redirection" plugin in WordPress. This plugin will help you manage and create redirects on your site. 4- Set up a 301 permanent redirect for the subdomain of your old site to the root URL of your new site. This redirect will ensure that your users and search engines are directed to your new site's home page. You can set up this redirect using the Redirection plugin by creating a new rule and selecting the "Regex" option. Then, add the following rule: Source URL: ^subdomain.oldsite.com/(.*)$ Target URL: https://www.newsite.com/$1 Match: Regex For other pages that need to be routed manually, create new redirects using the Redirection plugin. For example, if you had an old page on your Joomla site with the URL "oldsite.com/page1" that you want to redirect to "newsite.com/new-page," create a new rule in the Redirection plugin with the following settings: Source URL: /page1 Target URL: https://www.newsite.com/new-page Match: URL only For pages that you want to redirect to the home page or another page without receiving a 404 error, create a new rule in the Redirection plugin with the following settings: Source URL: /old-page Target URL: https://www.newsite.com/ Match: URL only By following these steps, you can ensure that your site is fully redirected without losing SEO value. Make sure to test all your redirects before going live to ensure that everything works correctly. Good luck!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gutenberg core/file add style support in js/ json I try add style support for file block in gutenberg. my code work for UL/li list: wp.blocks.registerBlockStyle('core/list', { name: 'blue-circle', label: 'Blue Circle', }); I try add: wp.blocks.registerBlockStyle('core/file', { name: 'test-inline', label: 'test-inline', }); no work for file block. Anyone know how I can add support for file block? on the core HTML block? Thanks!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: custom REST endpoints and application passwords I have created a number of RESTful endpoints via a plugin. To date I have only accessed them from the host site. However I would like to access these endpoints from a sub-domaine(2ed Wordpress installation). An application password appears to be a good way to set up authentication for accessing these endpoints in my application. However I can not find any documentation as to how to modify my 'permission_callback' to recognize application passwords. A: If you want to use application passwords to authenticate requests to your RESTful endpoints, you can modify your permission_callback function to check for the presence and validity of an application password instead of a user's credentials. To do this, you can use the wp_check_application_passwords function, which was introduced in WordPress 5.6. This function takes an application password and a user ID (or a username) and returns a WP_Error object if the password is invalid or expired, or an array with information about the password if it's valid. Here's an example of how you could modify your permission_callback function to use application passwords: function my_rest_permission_callback( $request ) { $app_password = $request->get_header( 'X-WP-Application-Password' ); if ( empty( $app_password ) ) { return new WP_Error( 'rest_forbidden', __( 'Authentication required.' ), array( 'status' => 401 ) ); } $user_id = get_current_user_id(); // or get the user ID from the request data $result = wp_check_application_passwords( $user_id, $app_password ); if ( is_wp_error( $result ) ) { return new WP_Error( 'rest_forbidden', $result->get_error_message(), array( 'status' => 403 ) ); } // Here you can do additional checks or data processing based on the password information // ... return true; // Access granted } In this example, the permission_callback function retrieves the X-WP-Application-Password header from the request, which should contain the application password provided by the client. If the header is empty, the function returns a 401 Unauthorized error. The function then calls wp_check_application_passwords with the current user ID and the application password, and checks if the result is an error. If so, the function returns a 403 Forbidden error with the message from the WP_Error object. Otherwise, the function assumes that the password is valid and returns true to allow access to the endpoint. You can customize this code to fit your specific needs, such as checking additional information in the password result or handling errors differently. Note that you need to create and manage application passwords in the WordPress administration area, under the user profile of the user who will be making the requests. A: It would use is_user_logged_in(). It's WordPress' job to authenticate the user not yours. permission_callback is there to test if that user has access, e.g. can an editor access this endpoint: The permissions callback is run after remote authentication, which sets the current user. This means you can use current_user_can to check if the user that has been authenticated has the appropriate capability for the action, or any other check based on current user ID. Where possible, you should always use current_user_can; instead of checking if the user is logged in (authentication), check whether they can perform the action (authorization). https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback If you are testing WP user logins, application passwords, etc in your permission_callback then this is incorrect, and not how the REST API works. Authenticated requests to the REST API are either: * *basic auth with application passwords *cookie sessions + REST API nonce WordPress will log the user in and create sessions on its own, it does all of that for you. Your code only needs to know is_user_logged_in(), and you don't need to do anything special for 3rd party remote clients.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search WordPress Hook for completed Elementor Update I am using WordPress and Elementor and looking for a hook that will fire when an Elementor update is completed. The hook should execute the Elementor function Regenerating CSS. This Elementor code should be executed with it: function clear_elementor_cache() { // Make sure that Elementor loaded and the hook fired if ( did_action( 'elementor/loaded' ) ) { // Automatically purge and regenerate the Elementor CSS cache \Elementor\Plugin::instance()->files_manager->clear_cache(); } } Code Source How do I use the WordPress hook "upgrader_process_complete" to clear the Elementor cache? A: If I understand correctly, you want to do this: add_action('upgrader_process_complete', 'my_clear_elementor_cache'); function my_clear_elementor_cache() { // Make sure that Elementor loaded and the hook fired if (did_action('elementor/loaded')) { // Automatically purge and regenerate the Elementor CSS cache \Elementor\Plugin::instance()->files_manager->clear_cache(); } }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I filter the user avatar displayed in comments? - get_avatar_url filter works everywhere but not in comments I have always used the get_avatar_url filter to alter the user avatar where it's printed. add_filter( 'get_avatar_url', 'my\plugin\filter_get_avatar_url', 10, 3 ); function filter_get_avatar_url( $url, $id_or_email, $args ) { // Do something and return whatever I want } But now I am printing comments with the wp_list_comments() function. And it's getting the avatar from Gravatar. I expect it to respect the filter. What should I do? A: By default, wp_list_comments() uses the get_avatar() function to display user avatars, which in turn retrieves the avatar URL from Gravatar. However, get_avatar() also applies the get_avatar_url filter before returning the URL, so you can modify the avatar URL for the comments by using that filter. Here's an example of how you can modify the avatar URL for comments using the get_avatar_url filter: add_filter( 'get_avatar_url', 'my_plugin_filter_get_avatar_url', 10, 3 ); function my_plugin_filter_get_avatar_url( $url, $id_or_email, $args ) { // Check if we are displaying a comment avatar if ( is_object( $args ) && isset( $args->object_type ) && $args->object_type === 'comment' ) { // Do something to modify the avatar URL for comments $modified_url = 'https://example.com/my-modified-avatar-url.jpg'; return $modified_url; } // Return the original avatar URL for other cases return $url; } In this example, we check if the object_type argument of the $args parameter is set to 'comment', which indicates that we are displaying a comment avatar. If that's the case, we modify the avatar URL as desired, and return the modified URL. For other cases, we simply return the original URL. Note that if you have other filters hooked to the get_avatar_url filter, they will also be applied to the comment avatars, so make sure your filter is compatible with other filters that may be running. A: The get_avatar_url filter you are using only affects the avatar URL generated by the get_avatar_url function. The wp_list_comments function, on the other hand, uses the get_avatar function to generate the avatar HTML, which does not go through the get_avatar_url filter. To modify the avatar displayed in comments, you can use the get_avatar_data filter, which is called by the get_avatar function and allows you to modify the data used to generate the avatar HTML. Here's an example of how you can use it: add_filter( 'get_avatar_data', 'my\plugin\filter_get_avatar_data', 10, 2 ); function filter_get_avatar_data( $args, $id_or_email ) { // Modify the avatar data as needed $args['url'] = 'https://example.com/my-custom-avatar.png'; return $args; } In this example, the get_avatar_data filter is used to modify the avatar data by changing the url parameter to the URL of a custom avatar image. You can modify the avatar data in any way you need, and the modified data will be used to generate the avatar HTML. Note that the get_avatar_data filter is called with two parameters: $args, which is an array of arguments used to generate the avatar, and $id_or_email, which is the user ID or email address associated with the avatar. You can use these parameters to modify the avatar data as needed. Keep in mind that modifying the avatar HTML in comments can be tricky, as comments may be cached by WordPress or by third-party caching plugins, so your changes may not be immediately visible. Additionally, modifying the avatar data may also affect other parts of your site that use the get_avatar function, so be sure to test thoroughly. Reference: https://developer.wordpress.org/reference/hooks/get_avatar_data/ A: After researching a bit more, I found out that we can indeed get the right avatar with the filter. The problem is, the filter param $id_or_email accepts many values: a user ID, Gravatar MD5 hash, user email, WP_User object, WP_Post object, or WP_Comment object. So, I had to modify the function that filters the value and make sure it also handles the case that the passed value is an instance of WP_Comment. function filter_get_avatar_url( $url, $id_or_email ) { // If $id_or_email is a WP_User object, just get the user ID from it if ( is_object( $id_or_email ) && isset( $id_or_email->ID ) ) { $id_or_email = $id_or_email->ID; } // If $id_or_email is a WP_Comment object, just get the user ID from it if ( is_object( $id_or_email ) && isset( $id_or_email->user_id ) ) { $id_or_email = $id_or_email->user_id; } // Normalize the current user ID if ( is_numeric( $id_or_email ) ) { $user_id = $id_or_email; } else if ( is_string( $id_or_email ) && is_email( $id_or_email ) ) { $user = get_user_by( 'email', $id_or_email ); if ( empty( $user ) ) { return $url; } $user_id = $user->ID; } else { return $url; } // Get user meta avatar $custom_avatar_url = get_user_meta( $user_id, 'avatar', true ); if ( empty( $custom_avatar_url ) ) { return $url; } return $custom_avatar_url; } Now, it's working as expected.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am using update_option function to update theme options programatically but page needs to be refreshed many time for changes to reflect! update_option( 'my-settings', $my_options, true ); This is updating the option but I need to refresh many times or clear cache every time for changes to reflect in frontend, is there a way for updating the option without needing to refresh many times?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Internal server error when enabling Multisite in WordPress Currently I am working on WordPress and I have added some line such as define('WP_ALLOW_MULTISITE',true); and after refreshing the page, this content shown on display: The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at postmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/8.2.0 Server at localhost Port 80
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set post status to draft after validating post meta values in save_post hook I have some custom meta values to a custom post type ('event'). The custom post type is displayed in the admin and the custom meta fields are appearing fine. I am using save_post_{$post->post_type} hook to validate the meta fields and change the post_status to draft (using wp_update_post) depending upon the validation of the meta fields and the newly set post_status. Problem: All things are working except the top right section (in the admin post edit page) do not reflect the change of status. If I publish a post, the validation is working fine with the post_status set to draft depending upon the set condition inside save_post_{$post->post_type}. But the top right corner of UI shows 'the post is now live', 'visit links' etc.(Screens #1). Upon refreshing the page, the proper draft status view is reflected (Screens #2). Screens #1: Although the post_status is successfully set to draft from save_post_{$post->post_type}, the UI view reflects the 'published' status. Screens #2: Upon refreshing, the actual draft status is restored: public function __construct() { $this->sconfig= ['post_type'=> 'event', 'slug'=>'events']; /* ... post type and meta declarations ... */ add_action('save_post_'.$this->sconfig['post_type'], array($this, 'event_mbox_save'), 10, 2); } function event_mbox_save($post_id, $post=false) { if (!isset($_POST['event_mbox_nonce']) || !wp_verify_nonce($_POST['event_mbox_nonce'], basename(__FILE__))) return $post_id; $valstat= $this->get_meta_posted_vals($_POST); // Validates the custom meta values. Returns $valstat['stat']= 0 if invalid and $valstat['log']= 'error message'. $original_pstat= $_POST['original_post_status']; $new_pstat= $_POST['post_status']; $insmeta= true; $errmsg= ''; if(($valstat['stat'] == 0) && (!empty($original_pstat))) { if(($new_pstat == 'publish') || ($new_pstat == 'future')) { remove_action('save_post_'.$this->sconfig['post_type'], array($this, 'event_mbox_save'), 10, 3); wp_update_post(array( 'ID' => $post_id, 'post_status' => 'draft') ); // Setting the post to draft add_action('save_post_'.$this->sconfig['post_type'], array($this, 'event_mbox_save'), 10, 3); $errmsg= 'ERROR: '.$valstat['log'].' ('.$this->sconfig['post_type'].' reverted to '.$original_pstat.' status.)'; $insmeta= false; // setting meta insertion false } } if(!empty($errmsg)) setcookie('event8273_add_notice', $errmsg, 0, '/' ); if($insmeta) { $evabstract = isset($postVal['evabstract']) ? $postVal['evabstract'] : ''; if (empty($evabstract)) add_post_meta($post_id, 'evabstract', $_POST['evabstract'], true); else update_post_meta($post_id, 'evabstract', $_POST['evabstract']); } } Note: I have tried using wp_insert_post_data alongwith redirect_post_location which did not work either. A: After some research, I altered my approach to validate the meta values in the following way: * *Create a new meta key(for post type) to store the validation (0 and 1). *Initiate it with 0. *This need not be kept/shown in the meta form. *While saving the meta fields (preferably within save_post hook), set its value depending upon the validation. *Use this meta value to detect the validation status of the post. For example you can display/hide the post depending upon this value.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why callback function is not working in wp_head hook? I have two versions of the simplest function that hooked to the wp_head action. One is working, andother one is not. Can someone explain? // Works ! function custom_description() { ?> <meta name="description" content="cococo" /> <?php } // Does not work /* function custom_description() { return '<meta name="description" content="cococo" />'; } */ add_action( 'wp_head', 'custom_description' ); A: I found answer i do not need to return value, i must echo it. So my function should look like: function custom_description(){ echo '<meta name="description" content="cococo" />'; } This works ! A: You can easily recognize where you're supposed to return a value, and where you're supposed to do an action (like echo or some other action). Although, internally they are very similar, but: * *Any hook that's called a filter hook, and used with add_filter function, expects a return. *On the other hand, any hook that's called an action hook, and used with add_action function, doesn't expect a return and instead expects an action (like echo or something else). Now, in your code, since wp_head is an action hook: add_action( 'wp_head', 'custom_description' ); you're supposed to do an action like echo, instead of return. You'll get more info. from the following documents: * *https://developer.wordpress.org/plugins/hooks/#actions-vs-filters *https://developer.wordpress.org/plugins/hooks/actions/ *https://developer.wordpress.org/plugins/hooks/filters/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to create a page that shows all of multiple category posts on a single page I have been attempting to get a solution to work that was previously posted for this question 1 I created the template as posted: <?php /* Template Name: Multiple Categories */ get_header(); $args = array( 'cat' => '1, 5, 9', 'posts_per_page' => -1, ); $my_posts = new WP_Query( $args ); if( $my_posts->have_posts() ){ while( $my_posts->have_posts() ){ $my_posts->the_post(); //Echo the post } } wp_reset_postdata(); get_footer(); When I select this template for a page, 'view page' displays only the theme header and footer with nothing in between. I suspect the template code is incomplete... or do I need to do something in the page itself? Or maybe the theme I'm using is keeping this from working? Suggestions? BTW, I want these displayed just as the theme displays individual category pages - trying to use plugins like wp_list_category_posts will not do this. A: I was seeing nothing in between the header&footer because I did not actually display the posts in my custom query, which can be done using template tags like the_title() and the_content(). More details here: https://developer.wordpress.org/themes/basics/the-loop/ But then I found out that I could simply use the cat parameter in the URL to view posts in certain categories, e.g. https://example.com?cat=1,5,9 to view posts in the categories 1, 5 and 9. So it was then easy to just stick the query URL in a menu item's custom link, and I no longer needed to use the custom template.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable WordPress canonical redirect to nearest matching URL and force 404 Page? WordPress appears to rewrite URLs, displaying Pages under the incorrect URL. Example. I have a page called "Emotion" with the slug /emotion/ On the front-end it should appear as the following URL ; example.com/learning/domains/emotion/ That is, there is a child/parent relationship defined within the Pages section of the website, as shown in that URL. Unfortunately, wordpress chooses to show anyone the page, no matter what URL you type in Examples; * *example.com/search/emotion/ *example.com/this-parent-doesnt-exist/emotion/ *example.com/learning/concepts/emotion/ None of these are real paths. I expect to see a 404 page. I've done research already, and tried the below two. The first one used to work in WP versions prior to v6. Now neither work. * *remove_filter('template_redirect', 'redirect_canonical'); *add_filter( 'redirect_canonical', 'disable_redirect_canonical', 10, 2 ); function disable_redirect_canonical( $redirect_url ) { return false; } How do I disable this rewrite rule? A: After doing some research, I have found the answer, albeit with a small limitation.... only shows the page with a trailing slash. This is perhaps technically correct url display so I'll deal with it. I found the solution buried in this similar Question Disable Wordpress URL auto complete The CORRECT solution is by David Vielhuber - strangely is not voted as the correct solution. The upvoted solution perhaps worked for older WordPress versions, but no longer since WP v6.x. To disable WordPress Canonical Redirect (to Nearest Matching URL) and force 404 Page... Add the following code to your child theme functions.php file. // Disable WordPress canonical redirect to nearest matching URL and force 404 Page // --------------------------------- add_filter( 'redirect_canonical', function( $redirect_url ) { $url = 'http'.((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'s':'').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; if( $redirect_url !== $url ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); } return false; });
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress REST API - Custom field not added to pages I have this code in my wordpress plugin. I'm working on an vue powered headless theme and I need to get all the informations about pages using the rest API. I've registered with success a custom res field for a cpt, but now when I try to add a rest field for page object, it will be not added if I call the wp-json\wp\v2\pages I will not see the added field function __construct() { add_action('rest_api_init', [$this, 'setup_custom_routes']); } function setup_custom_routes(){ register_rest_field( 'page', 'page_cover', [ 'get_callback' => [$this, 'get_pages_cover'] ] ); } function get_pages_cover( $post ){ return get_the_post_thumbnail_url( $post['id'] ); } Is there something wrong, or I need to do this in another way? A: You may need to flush the REST API cache in order to see the added field. You can do this by adding the following code to your plugin: This code will flush the REST API cache whenever a post (including a page) is saved or updated, so that the changes to the registered field will appear immediately. If the field still does not appear after flushing the cache, you may want to check that the REST API request you're making is for a single page object and not a collection. The field will only be returned when you make a GET request for a single page, for example: wp-json/wp/v2/pages/123. function flush_rest_api_cache() { wp_cache_flush(); } add_action( 'save_post', 'flush_rest_api_cache' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I add_rewrite_rule for a custom post type to preserve the referral id I've got this url /referral/{referralId} which needs to redirect to {customPostType}/{customPostSlug}/{referralId} and I'm really struggling to figure out how to do this with wordpress's add_rewrite_rule. Any help would be greatly appreciated! Will
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Meta_query question There is a problem with compiling a request to display posts by meta_query. Need to output posts whose title contains a substring. Can't figure out where I'm wrong. Can someone help? $inputValue = 'Palm'; echo $inputValue; $args = [ 'post_type' => 'projects', 'order' => 'DESC', 'posts_per_page' => -1, 'post_status'=> 'publish', 'meta_query' => [ [ 'key' => 'title', 'value' => 'Palm', 'compare' => 'LIKE', ] ], ]; } $query = new WP_Query($args); if ( $query->have_posts() ) { ?> <h2 class="portfolio__name"> <a href="<? the_permalink() ?>"> <? the_title() ?></a> </h2> <?php endwhile; wp_reset_postdata();?>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access files outside /var/www/html I'm using wordpress+apache2 and deploy it myself. I have created a custom mechanism to sync wordpress to git so that on the server itself I have to have symlinks between the synced wp-content folder and /var/www/html. For example, on my server: wp-content -> /temp/storefront-cms/wp-content And in turn: /temp/storefront-cms -> ff2cbcaf328b17f100f9446b1a49acf3b2e85b0c It all worked well, but we need to change the theme now and the new theme seems to be using WP customizer in a way that makes the site crash. This is an example from the logs: [21/Feb/2023:12:14:09 +0000] "GET /temp/ff2cbcaf328b17f100f9446b1a49acf3b2e85b0c/wp-content/plugins/kirki/kirki-packages/module-webfonts/src/assets/scripts/vendor-typekit/webfontloader.js?ver=3.0.28 HTTP/1.1" 404 114258 "https://mydomain/wp-admin/options-general.php" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36" I'm not good at PHP, so not sure how to proceed. I tried to just enable /temp access in apache, but it didn't help and I'm still getting 404: <Directory /temp> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> I understand that it fails because GET request should go to mydomain/wp-content... instead of calling full path(/temp...), but I can't figure out the easiest way to fix it. Whether it should be on apache level or WP or both. UPDATE In general I don't understand why some WP components try to call other components by their full path. Even if I remove the symlink and just use /var/www/html, it doesn't seem right that the calls are made to https://domain/var/www/html/..... I don't think that server folder structure should be exposed directly. That's the whole point of having a server, like apache, after all. What I see in network traffic:
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/414061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }