text
stringlengths
12
210k
meta
dict
Q: Swap Wordpress "Widget Area" based on Page Template i'm using 3 widget areas in my child theme's footer. i created a secondary custom theme successfully, and am hoping i can simply change those 3 widget area's out in the second theme. "Footer - Column 1" would change to "Alt Footer - Column 1" "Footer - Column 2" would change to "Alt Footer - Column 2" "Footer - Column 3" would change to "Alt Footer - Column 3" (and yes, i've already created in WP admin > Appearnace > Widgets, those 3 new custom widget areas, & put temp text widgets in them for now). i'm using this in "functions.php" to change the "Menu"... add_filter( 'wp_nav_menu_args', 'respect_menu_swap' ); function respect_menu_swap( $args = '' ) { if(is_page_template('template-respect.php') && $args['menu_id'] == 'avia-menu') { $args['menu'] = '16'; } return $args; } ...am hoping for something similar to change each of those "widget areas". i've searched, read, searched, & read a LOT trying to figure this out & just can't seem to grasp what should go in place of the menu terms in that code bit. i really struggle with PHP, so would greatly appreciate specific explanation & code:-) and, i'm saying "Widget Area" instead of "Widgets" because i realized that "Widgets" are INSIDE the "Widget Areas". i'd like to swap the whole area instead of just the widget so my people can add/remove various widgets in those 3 "areas" in the WP > Appearance > Widgets admin page as needed. it’s my understanding that if i just use the “Widget ID” then when someone changes which widget(s) are in one of those widget areas, it won’t update on the sites front-end without me changing those ID’s first. i’d like to avoid having to do that if possible. (BTW: i'm using the Enfold WP theme, if that matters) A: WOW! well, it would seems as tho i figured it out! after MORE searching, i came across https://learn.wordpress.org/lesson-plan/widget-areas apparently i had to "register" a "sidebar" - which thru me, as i was wanting to modify in the footer. after looking that up, the term "sidebar" is used anywhere the theme allows the user to add widgets in. and since the Enfold theme footer allows for widgets, i had to "register_sidebar" and THEN modify a line in the template. i also didn't understand why i had to "register" the "widget area's" at all, thinking that just by creating the custom widgets in WP admin > Appearance > Widgets, that should do it, but no. ya gotta create them there and ALSO register them in the child functions too. so after reading that wordpress page (linked above), i started hunting around in the main Enfold theme files, trying to find something similar. since apparently, some things are named differently than in other themes, which is why my copy/pasting of examples i found elsewhere didn't work. i found it in... themes > enfold > includes > admin > register-widget-area.php so i combined what that wordpress link offered with the footer widget registration and came up with this code that i put in my child functions.php... add_action( 'widgets_init', 'MYWIDGETAREA' ); function MYWIDGETAREA() { register_sidebar( array( 'name' => 'Respect Footer - Column ' . $i, 'id' => 'espect_foot_widget_' . $i, 'before_widget' => '<section id="%1$s" class="widget clearfix %2$s">', 'after_widget' => '<span class="seperator extralight-border"></span></section>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>' )); } in the array, i only changed the "name" & "id", leaving the rest so the structure matches the original theme. then i went to my template-custom.php and found this line... if( ! ( function_exists( 'dynamic_sidebar' ) && dynamic_sidebar( 'Footer - Column ' . $i ) ) ) ...and replaced it with... if( ! ( function_exists( 'dynamic_sidebar' ) && dynamic_sidebar( 'Respect Footer - Column ' . $i ) ) ) AMAZING!!! well hopefully all this may benefit someone else in a similar position some day.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I want create woocommerec match products columns I have created three columns. In two columns I want to add woocommerce products (e.g bottoms in one and tops in another) and for third column I want it to be populated from products present in tops and bottoms columns, when I click on them. Some one please help me with code.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP_Query (or WC_Product_Query) out of memory I'm building a plugin that's supposed to show the user a list of all products on the site. This testing website has 25000 products on purpose in order to test performance. This server and Wordpress installation has a memory limit of 1024M both set on PHP and wp-config. I've used an ajax function that basically just pulls all the products (and variations) and shows them in a dropdown. That function always receives a 500 error even if I try to pull only IDs. The same issue occurs using WP_Query. Here's the code I've used: /** * Ajax get all products. * @return array * @since 1.0.0 */ public function ajax_get_all_products() { check_ajax_referer( MY_PLUGIN_SLUG . '_ajax_get_all_products', 'security' ); $transient = get_transient( MY_PLUGIN_SLUG . '_get_all_products' ); if( !empty( $transient ) ) { wp_send_json_success( $transient ); } $products = []; $args = [ 'limit' => -1, ]; $args = apply_filters( MY_PLUGIN_SLUG . '_get_all_products_args', $args ); $products_posts = wc_get_products( $args ); foreach( $products_posts as $product ) { $product_name = $product->get_name(); $product_id = $product->get_id(); $products[ $product_id ] = '(' . $product_id . ') ' . __( 'Product', 'MYPLUGIN' ) . ': ' . $product_name; if( $product->is_type( 'variable' ) ) { $available_variations = $product->get_available_variations(); if( !empty( $available_variations ) ) { foreach( $available_variations as $available_variation ) { $variation_id = $available_variation['variation_id']; $products[ $variation_id ] = '(' . $variation_id . ') ' . __( 'Variation', 'MYPLUGIN' ) . ': ' . $product_name; } } } } set_transient( MY_PLUGIN_SLUG . '_get_all_products', $products, WEEK_IN_SECONDS ); $products = apply_filters( MY_PLUGIN_SLUG . '_get_all_products', $products ); wp_send_json_success( $products ); } I've tried adding 'return' => 'ids. Increasing the memory limit even further is not a good solution as I need this plugin to work on any kind of site without too much hassle, it's supposed to be a plug-n-play sort of thing. Any idea what I can do in order to improve performance? Would a custom query do the trick? Should I only pull 100 products and then do an infinite scroll load using offset with a search function? I'm trying to keep a good user experience so I would like to allow the user to easily find and search products on that dropdown menu that shows all products on the site. Thanks for the help!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Footer navigation menu Our website is https://de.ferberg.com and we are a manufacturer of warehouse equipment and mobile loading ramps. On our site the navigation menu is added to the footer via code and theme editor, it is duplicated from the main menu in the header, but we need to add elements there that are not in the main menu. We tried adding through the menu editor, but no new display areas are available in the theme. Can you tell me how to add a new menu display area in Wordpress? A: you can add new menu from WordPress admin on this https://de.ferberg.com/wp-admin/nav-menus.php?action=edit&menu=0 and then you need to call this menu where you're calling your footer menu.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What purpose does /embed/ URL have and how to avoid SEO problems? I've noticed this with many WordPress projects (and clients) over the years so I thought it was worth a public thread. When you interlink a post/page that has embedding enabled, the iframe source will affix /embed/ URL suffix: <iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" style="position: absolute; clip: rect(1px, 1px, 1px, 1px);" title="Example" src="https://example.com/blog/post/embed#?secret=12345#?secret=12345" data-secret="12345" width="500" height="282" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe> However this tends to make Google GSC go a bit crazy because their bots will try to crawl the iframes. WordPress does already include the noindex meta tag on those generated sub-pages: <meta name='robots' content='noindex, follow, max-image-preview:large' /> WordPress also includes a canonical tag: <link rel="canonical" href="https://example.com/blog/post" /> However, for search engines like Google they still assume you want the content crawled because of the iframe existing on a public page... resulting in tons of crawl errors in GSC. But because the rel flag is not supported on iframes, there doesn't seem to be any easy way to avoid this conflict? TLDR this seems to be more of a Google problem than a WordPress problem, but I find it strange that the /embed/ page has the exact same content as the canonical version... so what is the purpose of having both?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Styling parent based on a child element of a child in a WordPress page With $('section:has(h1.heading1)').addClass('as_child'); jQuery code, I've not been able to add a class/CSS to the parent element section. Below is the html. Could you please point out what is wrong in my code? <section class="Section Section--spacingNormal" id="section-template--14477139017774__c0f6b03c-2431-40fa-9755-3e3dfb96d834"> <div class="Container"><div class="Rte" style="text-align: center"> <h1 class="heading1">Gut Armor Ingredients</h1> </div> </div> </section>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress function that retrieves both posts written by a specific author& posts that contain a tag matching author's username on author archive page How can i achieve this? I have tried multiple codes but none seem to work.. function divi_include_author_tagged_posts( $query ) { if ( $query->is_author() && $query->is_main_query() ) { $author = $query->get( 'author' ); $tag = get_the_author_meta( 'user_login', $author ); $query->set( 'tag', $tag ); } } add_action( 'pre_get_posts', 'divi_include_author_tagged_posts' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove nonindex meta tag I noticed a number of pages like https://andersonadvisors.com/podcast/page/10/ are noindexed. I don't see any code in the template file that is adding <meta name='robots' content='noindex, follow' /> Please direct me to possible locations where I can remove this.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Full Site Editing Non-editble global styles? Working my way through learning FSE, I'm using this this article and wondered what to do for global styles you don't want user control over? Previous this would be controlled via style.css however, it seems split apart as you have styles for individual blocks as well as layout/typography etc called via the theme.json Have I missed something or is there a json setting or style sheet that can be called within the editor as well as front end but is also not customisable via the theme editor?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to clone a theme template from within Wordpress? I'm looking at the Raft theme and its got 8 templates, including one called Front Page. I wanted to clone Front Page to 'Front Page Modified' so I could have on it and still keep the original in its original form. I was able to add a new template using the Add New > Custom Template UI, but I don't see a way to copy the original Front Page contents template over to my new copy. I do see a 'Copy all blocks' in the editor menu, but when I try to paste, nothing happens. Thanks. ...Wordpress version 6.1.1.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use multiple custom post types to archive as front page? I am trying to modify my code to show multiple custom post types on the front page. This code works good for a single custom post type, but I can't figure out how to add a second custom post type. How can the following code be modified to show a second custom post type? function blestrecipes_cpt_filter( $query ) { if ( ! is_admin() && $query->is_main_query() && is_home() ) { $query->set( 'post_type', array( 'recipes' ) ); } } add_action( 'pre_get_posts', 'blestrecipes_cpt_filter' ); A: Well, looks like you've almost got it. To include multiple custom post types in the WP_Query object, just change: $query->set( 'post_type', array( 'recipes' ) ); to: $query->set( 'post_type', array( 'recipes', 'another-custom-post-type' ) ); Basically adding more elements to the array. So the final code becomes: function blestrecipes_cpt_filter( $query ) { if ( ! is_admin() && $query->is_main_query() && is_home() ) { $query->set( 'post_type', array( 'recipes', 'another-custom-post-type' ) ); } } add_action( 'pre_get_posts', 'blestrecipes_cpt_filter' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Removing the add to cart button from specific product pages I'm no PHP expert but I'm good enough to scrape some things together here and there. This is my attempt at hiding the WooCommerce add to cart button from specific category pages: // Remove the add to cart button from certain power line markers add_action( 'woocommerce_single_product_summary', 'remove_add_cart_button' ); /** * Remove add to cart button */ function remove_add_cart_button() { // Categories $categories = array( 'Power Line Markers' ); if ( has_term( $categories, 'product_cat', get_the_id() ) ) { remove_action( 'woocommerce_single_variation','woocommerce_single_variation_add_to_cart_button', 20 ); } } This works perfectly but it will only remove the add to cart button from specific categories and I'd like to remove it from specific products instead. I'm struggling with the PHP code to do that so I'm hoping someone can put me on the right path. Thanks in advance and God bless! A: I think you can update the condition of your function remove_add_cart_button to check for products, something like the code below: /** * Remove add to cart button */ function remove_add_cart_button(){ // Products $product_ids = array(110, 111, 112); //todo: put your product ids here if(in_array(get_the_ID(), $product_ids)){ remove_action('woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20); } }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: custom post filter based on Visitors country I'm looking for some advise on how to implement a custom filter which should be automatically applied based on Visitors country. The goal is to hide certain posts from visitors from Germany for example. So I added a custom field $dont_show_on_de. What I have so far on page-home.php : include_once("{$_SERVER['DOCUMENT_ROOT']}/get_visitors_country.php"); // third-party script which determines the visitors location from IP $country = GetCountry(); if ($country == 'DE') { $args = array( 'posts_per_page' => 10, 'post_type' => 'post', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'dont_show_on_de', 'value' => 0, 'compare' => '=', ), array( 'key' => 'dont_show_on_de', 'compare' => 'NOT EXISTS', ) )); } else { $args = array( 'posts_per_page' => 10, 'post_type' => 'post', ); } $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post); get_template_part( '/theme-parts/archive/loop' ); endforeach; wp_reset_postdata() This works fine, but I don't know how to apply this to categories for example. Maybe rather than modifiyng all the template files, could I instead add some sort of filter to functions.php ?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query a meta key using an array of values where the database value is a string If a meta value in the WordPress user_meta table is set as a comma separated list and not a serialized array, how can we compare an array of possible values to the values in the database table? Currently, we're trying this code, but it only works if the User's specializations key has only one value in the database; as soon as there are multiple values in the database, it is stored as a comma separated string and doesn't return any matches. $args = array( 'role' => 'member', 'meta_query' => array( 'key' => 'specializations', 'value' => array('doctor', 'researcher'), 'compare' => 'IN' ) ); $found_users = new WP_User_Query($args); In our example, we only get a returned User object if the User's specialization meta value is either 'doctor' or 'researcher'. If the User's specializations meta value contains multiple values like doctor, researcher (or more) in the database then the query returns nothing. Assuming we can't change how the meta values are created and stored in the first place, what's the best way to map an array of potential matches to a comma-separated string of values in the database? The intended behaviour is that if you select both 'doctor' and 'researcher', the resulting query will return anyone matching any or or all of the supplied values for the query. A: You could use multiple meta clauses in your WP_User_Query, along with a LIKE comparison. Something like $args = array( 'role' => 'member', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'specializations', 'value' => 'doctor', 'compare' => 'LIKE', ), array( 'key' => 'specializations', 'value' => 'researcher', 'compare' => 'LIKE', ), ), ); $found_users = new WP_User_Query($args); In reality you'd probably want to loop through your target specializations and build the set of clauses dynamically. That said, be aware that queries using LIKE are expensive. I'd say this method is a last resort, assuming you cannot refactor the DB structure to store each specialization in its own row (serialization won't help you here), and assuming that there are too many records for you to just grab the lot and search them in your PHP.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pre_get_posts has php notice when not on CPT archive I'm setting my post archive page to sort by a meta date. When I'm on the archive page it all works. However on other pages I get a PHP notice Undefined index: post_type. Here is my function: function rt_webinar_pre_query ($query){ if ( !is_admin() && $query->is_main_query() ) { if ( $query->query_vars['post_type'] == 'product' || $query->is_tax('product_cat') ) { $today = date('Ymd'); // Today's date $query->set( 'meta_key', 'event_date' ); $query->set( 'orderby', 'meta_value' ); $query->set( 'order', 'DESC'); $query->set( 'meta_query', array( array( 'key' => 'expiration_date', 'compare' => '>=', 'value' => date('Ymd'), 'type' => 'numeric', ) ) ); } } } add_action( 'pre_get_posts', 'rt_webinar_pre_query' ); (Yes the post type is Woocommerce Product, but I don't believe this is a woo issue. I think I've missed something in my function.)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use WP_Query to find a post with a particular menu_order? I can use WP_Query to order posts matching my query by menu_order. But can I also specifically find posts that have a particular menu_order? Even better, can I find posts with a menu_order larger than a particular number? Or smaller than a particular number? If so, how? Note: I can, of course, loop through posts that match my query and find the post I'm looking for in code, but it would be nicer if I can get the result directly from WP_Query. A: Matching by menu_order is easy, like this: $args = array( // find posts with menu_order 4 'menu_order' => 4, 'orderby' => 'menu_order', 'order' => 'ASC', 'posts_per_page' => 10, ); $query = new WP_Query( $args ); However, larger or smaller option for menu_order is not provided by default in WP_Query. You can still filter the where clause to achieve that. Something like this: $args = array( 'orderby' => 'menu_order', 'order' => 'ASC', 'posts_per_page' => 10, ); add_filter( 'posts_where', 'wpse_menu_order_filter', 10, 2 ); function wpse_menu_order_filter( $where, $query ) { // remove this filter to avoid changing other queries. remove_filter( 'posts_where', 'wpse_menu_order_filter' ); // custom where clause to show only posts with menu_order greater than 4 return $where . ' AND wp_posts.menu_order > 4 '; } $query = new WP_Query( $args ); You can do the same thing for smaller check as well. More advanced solution: You can also enhance the menu_order argument so that the greater or lesser sign and the compare value is not hard coded within the filter function. Like this: $args = array( 'post_type' => 'page', 'menu_order' => array( 'value' => 5, 'compare' => '<=' ), 'orderby' => 'menu_order', 'order' => 'ASC', 'posts_per_page' => 10, ); add_filter( 'posts_where', 'wpse_menu_order_filter', 10, 2 ); function wpse_menu_order_filter( $where, $wp_query ) { remove_filter( 'posts_where', 'wpse_menu_order_filter' ); $args = $wp_query->query; if( isset( $args['menu_order'] ) && is_array( $args['menu_order'] ) ) { $menu_order = $args['menu_order']; if( isset( $menu_order['value'] ) && isset( $menu_order['compare'] ) ) { $compare = $menu_order['compare']; // allow only four comparisons: '>', '>=', '<', '<=' if( in_array( $compare, array( '>', '>=', '<', '<=' ) ) ) { $value = $menu_order['value']; if( is_scalar( $value ) && '' !== $value ) { $value = absint( $value ); } else { $value = 0; } return sprintf( $where . ' AND wp_posts.menu_order %s %d ', $compare, $value ); } } } return $where; } $query = new WP_Query( $args ); With the above implementation, you can just change the $args to get the desired result. For example: // menu_order less than or equals 5 $args = array( 'post_type' => 'page', 'menu_order' => array( 'value' => 5, 'compare' => '<=' ) ); // menu_order greater than 10 $args = array( 'post_type' => 'page', 'menu_order' => array( 'value' => 10, 'compare' => '>' ) ); // equals will still work like before $args = array( 'post_type' => 'page', 'menu_order' => 6 );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Redirect to Multisite site 2 if site 1 has a setting On my Multisite, there is a custom setting that indicates whether the site is disabled. It uses get_blog_option($id, 'deleted') flag that is set if the blog is marked for deletion (essentially, the blog is 'inactive'). That flag doesn't seem to be used if you load that site. So I need to intercept the Site 2 load if that flag is set (if get_blog_option(2,'deleted') === '1'), and wp_redirect to a specific page on Site 1. I believe I can do this with the wp_loaded filter. But is that the proper filter to use? I need the theme code to load (since the test will be in the Child Theme's functions.php file; I don't need it to be in a separate plugin), but the blog content needs to switch to Site 1. It's not clear to me from the docs that using the wp_loaded filter is the proper spot to switch to Site 1. Is 'init' filter better? What sequence should I use to allow the 'test' in the Child Theme functions.php to switch to another blog if needed? Related to this is that if you 'inactive' a blog (via the Sites screen), why does that blog still load on the front end? Added I think what I need is a filter just after the blog ID has been set. Been looking through the 'load' process, but it's a bit complex. A: If you are implementing a global functionality for your entire multisite/sub-sites like what you describe, you should implement this as mu-plugins instead adding the cuztomization inside a theme file, just create a file like in wp-content/mu-plugins/GlobalConfig.php which holds the customization you want and will take effect globally, unless you want this customization for only specific sub-site. the init runs before the wp_loaded, but you can intercept the request at plugins_loaded hook since it runs even before init e.i. add_action('plugins_loaded', function() { //skip wp back-end request if ( is_admin() ) return; $isDeleted = get_blog_option(get_current_blog_id(), 'deleted'); if ( $isDeleted ) exit( wp_redirect( 'https://site2.com/sub-page', 301 ) ); });
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove My Account Menu items in Woocommerce based on user roles I need to be able to unset or disable certain Myaccount menu items in Woocommerce Dashboard based on user role. So for example show "orders" menu for customers (role) and not show menu "orders" for subscribers (role). Not sure of the best way to do that. I use the code in plugin called "Code Snippets" in Wordpress. add_filter ( 'woocommerce_account_menu_items', 'silva_remove_my_account_links' ); function silva_remove_my_account_links( $menu_links ){ unset( $menu_links['downloads'] ); // Disable Downloads // If you want to remove any of the other default links, just uncomment out the items below: //unset( $menu_links['edit-address'] ); // Addresses //unset( $menu_links['dashboard'] ); // Remove Dashboard //unset( $menu_links['payment-methods'] ); // Remove Payment Methods //unset( $menu_links['orders'] ); // Remove Orders //unset( $menu_links['edit-account'] ); // Remove Account details tab //unset( $menu_links['customer-logout'] ); // Remove Logout link return $menu_links; }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: on attachment.php, how to display previous and next attachment links that follow the same order as a custom WP Query Current behavior I have a media page that uses a custom WP_Query to return all thumbnails of media library attachments (regardless of post parent) with a custom taxonomy of media_visibility that has the term of published. This is working as expected on the media page. It's using my template file page-media.php. Relevant code sample: // how many media thumbnails to show at first. $thumbnails_to_show = 42; //Protect against arbitrary paged values $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; // query media $media_query_args = array( 'post_type' => 'attachment', 'post_status' => 'any', 'order' => 'DESC', 'orderby' => 'date', 'paged' => $paged, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'media_visibility', 'field' => 'slug', 'terms' => 'published', ), ), 'posts_per_page' => $thumbnails_to_show, ); $media_query = new WP_Query ($media_query_args); $thumbnails = array(); if ( $media_query->have_posts() ) : while ( $media_query->have_posts() ) : $media_query->the_post(); // store thumbnails in array $thumbnails[] = wp_get_attachment_link( get_the_ID(), 'thumbnail', true ); endwhile; endif; // end of media loop When one clicks on a link on a thumbnail image, it loads a page showing the attachment and previous / next links using my attachment.php file. Relevant code sample: while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', get_post_type() ); previous_post_link(); next_post_link(); if ( comments_open() || get_comments_number() ) : comments_template(); endif; endwhile; // End of the loop. Here, there seems to be an issue with the order of posts / the different loops. On some (maybe all) attachment pages, previous_post_link() is displaying a link to the same attachment shown rather than the previous one, and next_post_link() is not displaying anything. I also have another sort of page (a custom post type called "year story") that has a slightly different WP_Query to display multiple thumbnails - it's restricting the attachments to those that have the same terms in a couple of taxonomies. Full code in single-year_story.php: //get taxonomies from the post $this_ensemble = wp_get_post_terms(get_the_ID(),'ensemble')[0]->slug; $this_year = wp_get_post_terms(get_the_ID(),'vhs_year')[0]->slug; // how many media thumbnails to show at first $thumbnails_to_show = 6; // query media $media_query_args = array( 'post_type' => 'attachment', 'post_status' => 'any', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'ensemble', 'field' => 'slug', 'terms' => $this_ensemble, ), array( 'taxonomy' => 'vhs_year', 'field' => 'slug', 'terms' => $this_year, ), array( 'taxonomy' => 'media_visibility', 'field' => 'slug', 'terms' => 'published', ), ), 'posts_per_page' => $thumbnails_to_show, ); $media_query = new WP_Query ($media_query_args); $thumbnails = array(); if ( $media_query->have_posts() ) : while ( $media_query->have_posts() ) : $media_query->the_post(); // store thumbnails in array $thumbnails[] = wp_get_attachment_link( get_the_ID(), 'thumbnail', true ); endwhile; endif; // end of media loop Note that in both of these cases, the attachments don't necessarily have post parents. I set up the site to be fairly dynamic with visitors able to upload their own attachments, and I don't want to assign post parents to them when this happens (because we might not have created the corresponding year story post yet). Desired behavior What I want on the attachment page is to have previous and next text links that page through the attachment pages in the same order they appear on the WP_Query on the referring page (like a year story or media page) and only including those attachments shown on the referring page's WP_Query. If someone comes directly to an attachment page, I want these previous and next links to behave the same way as if someone came from the media page. If someone comes to the attachment page from an attachment in the body of a post or page, I want to either: * *have the previous and next links cycle through the attachments with the same post parent, or *hide the previous and next links - they're not very important for this case. Other attempts I tried some other approaches like the_post_navigation() and get_previous_image_link() / get_next_image_link() but did not get what I was trying to achieve here. I also tried replacing the loop on attachment.php with the same custom WP_Query that I used on page-media.php but this ended up always displaying the first attachment returned in the query, rather than the attachment specified in the URL. Links View the media page on staging site View a year story page on staging site (In order to view the above links, log in as username: stackexchange password: guest) Theme code This customized theme is based on underscores.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to add javascript to template parts Is it possible to add javascript to a template part, specifically I would like to add alpine.js to a template part. Any time I add a x-data="menuOpen" or even a data attribute I get This block contains unexpected or invalid content Any help on this is appreciated. A: This is not supposed to work (and it does not work) in a way you wanted. I guess you are talking about new FSE template parts (.hmtl), and not legacy (.php) template parts. You can only add HTML and blocks to .html template parts and javascript is enqueued as a part of a block. Alternatively, you can check in a functions.php if certain page/post/template/block is loaded and then enqueue javascript you want.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to self host fonts and have them show up in all the Full Site Block Editor Typography options, including global styling I'm a designer. I can't code, but I can follow directions and do minor modifications of code that others have written. I've been struggling on how to add self hosted fonts to my website and have them show up in the block editor typography options so I can use them in my design. I've done days of research and experimentation and most of what I've found uses the Customizer, which isn't what I need. I know just enough about coding to know that if it isn't exactly right, then it's wrong and won't work. I haven't been able to find something clear enough to allow me to know what I'm doing wrong. I used a plugin to make a child theme of twenty twenty three. Here is the function.php that it created. <?php /* This file is part of a child theme called 2023 Child. Functions in this file will be loaded before the parent theme's functions. For more information, please read https://developer.wordpress.org/themes/advanced-topics/child-themes/ */ // this code loads the parent's stylesheet (leave it in place unless you know what you're doing) function your_theme_enqueue_styles() { $parent_style = 'parent-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css'); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array($parent_style), wp_get_theme()->get('Version') ); } add_action('wp_enqueue_scripts', 'your_theme_enqueue_styles'); /* Add your own functions below this line. ======================================== */ Here is the style.css that was also created at the same time. /* Theme Name: 2023 Child Theme URI: Description: Author: Verity Author URI: https://myannoyingwebsite.me Template: twentytwentythree Version: 1.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html /* == Add your own styles below this line == --------------------------------------------*/ Someone wrote some code for me so I could plug in my own font information, which I did. They also suggested I make a dedicated added_fonts.css file to hold them all. This sounded very reasonable to me so I made a completely blank one and put this in it. @font-face { font-family: "Petrona"; src: url("fonts/petrona/petrona-v28-latin-regular.woff2") format("woff2"), url("fonts/petrona/petrona-v28-latin-regular.woff") format("woff"); font-weight: 400; font-style: normal; } They also told me I need to enqueue the file, and that's where I got stuck. I tried to follow some directions I found here and it didn't work. Or rather, the font didn't show up in the Typography Font Family. https://hollypryce.com/enqueue/ When I did further research, there were so many different sorts of code I found that I just got lost and have no idea what is right or wrong, because I don't code. Is my function.php file correct? I think it looks like the child's style.css file is enqueued in the generated code. Is it or does it need enqueued also? (the font code didn't work when pasted directly into style.css either) Does the .css file need any sort of header or is the stuff that is in the generated one just notes? Is the code to insert the font correct? And how do I properly enqueue it in the function.php file? Or is all of this wrong and I need to do something else for my real goal: having self hosted custom fonts show up in the block editors' Typography Font Family selector? Thanks! Verity
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Limit paginated result set to a maximum number of posts I would like to create a paginated result using a maximum number of posts. I have been trying to achieve this using \WP_Query class e.g: function getQuery(int $page, int $posts_per_page = 2, int $max_posts = 7): \WP_Query { $args = [ 'posts_per_page' => $posts_per_page, 'numberposts' => $max_posts, 'offset' => $page - 1, 'post_status' => [ 'publish', ], ]; return new \WP_Query($args); } // Get the last page query which I would assume only would contain a single post. $query = getQuery(3); This almost works, the problem is the maximum number of posts when using a paginated result set. I would assume that the last page only would get a single post taking the numberposts argument in to consideration, but this does not seem to work. One solution is to check if we have reached the end and then slice of the extra returned posts from the array e.g: if (($page + 1) * $posts_per_page > $max_posts) { $count = $max_posts - ($page * $posts_per_page); $query->posts = array_slice($query->posts, 0, $count); $query->found_posts = $count; $query->post_count = $count; } but this not seems like a very good solution. A: Hope I understand this correctly. Below is an approach using few hooks to modify the query before fetching the data. Might need some adjustments and testing. Note that numberposts is just an alias for posts_per_page in get_posts() wrapper of WP_Query. We could try to use paged instead of offset, but it will not work if we plan to modify posts_per_page on the last page calculated by ceil($max_posts/$posts_per_page ). So we set offset directly as: $args = array( 'posts_per_page' => $posts_per_page, 'offset' => ($page - 1) * $posts_per_page, 'post_status' => array( 'publish' ), ); We can adjust the number of found posts if it exceeds $max_posts: $fn_found_posts = function( $found_posts, $q ) use ( $max_posts, $page ) { return $found_posts > $max_posts ? $max_posts : $found_posts; }; add_action( 'pre_get_posts', $fn_pre_get_posts ); but this filtering will not adjust the returned posts array. We can therefore adjust the posts_per_page to $max_posts - ($page - 1) * $posts_per_page for the last page (according to $max_posts) because that will adjust the previously set offset: $fn_pre_get_posts = function( $q ) use ($page, $posts_per_page, $max_posts ) { if ( $page == ceil($max_posts/$posts_per_page ) ) { $q->set( 'posts_per_page', $max_posts - ($page - 1) * $posts_per_page ); } }; add_filter( 'found_posts', $fn_found_posts ); We can then return empty array for pages after the last page (according to $max_posts): $fn_posts_pre_query = function( $posts ) use ($page, $posts_per_page, $max_posts ) { return $page > ceil( $max_posts/$posts_per_page) ? array() : $posts; }; add_filter( 'posts_pre_query', $fn_posts_pre_query ); Here the modified getQuery() function: function getQuery(int $page, int $posts_per_page = 2, int $max_posts = 7): \WP_Query { $fn_found_posts = function( $found_posts ) use ( $max_posts ) { return $found_posts > $max_posts ? $max_posts : $found_posts; }; $fn_posts_pre_query = function( $posts ) use ($page, $posts_per_page, $max_posts ) { return $page > ceil($max_posts/$posts_per_page) ? array() : $posts; }; $fn_pre_get_posts = function( $q ) use ($page, $posts_per_page, $max_posts ) { if ( $page == ceil($max_posts/$posts_per_page ) ) { $q->set( 'posts_per_page', $max_posts - ($page - 1) * $posts_per_page ); } }; add_filter( 'found_posts', $fn_found_posts ); add_filter( 'posts_pre_query', $fn_posts_pre_query ); add_action( 'pre_get_posts', $fn_pre_get_posts ); $args = array( 'posts_per_page' => $posts_per_page, 'offset' => ($page - 1) * $posts_per_page, 'post_status' => array( 'publish' ), ); $q = new \WP_Query($args); remove_action( 'pre_get_posts', $fn_pre_get_posts ); remove_filter( 'posts_pre_query', $fn_empty_array ); remove_filter( 'found_posts', $fn_found_posts ); return $q; } ps: one might add some input range checks etc.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating posts with php-script + csv I'm trying to create posts with a Script + CSV. Each row schould create a post, while each column should fill the title/ACF-Fields. $csv_file_path = '/test.csv'; function create_wp_cpt_from_csv() { global $csv_file_path; if (($handle = fopen($csv_file_path, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { $post = array( 'post_title' => $data[0], 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'sorten' ); $post_id = wp_insert_post($post); update_field('acf_1', $data[1], $post_id); update_field('acf_2', $data[2], $post_id); } fclose($handle); } } add_action('init', 'create_link_to_import_csv'); function create_link_to_import_csv() { add_menu_page( 'Import CSV', 'Import CSV', 'manage_options', 'import_csv', 'import_csv_function'); } function import_csv_function(){ create_wp_cpt_from_csv(); } I implemented this code in my functions.php. CSV is in the same directory as the functions.php. Unfortunately, whenever i run the script via clicking on the "Import CSV" in the admin-backend, it just opens the following link, but it doesn't create posts: /wp-admin/admin.php?page=import_csv Theme: Impreza Are certain permissions missing here? Can this work at all via the functions.php? Have i built in a general error in the function? Thanks guys!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Homepage not loading correctly, only after refreshing I'm working on - https://nhukr.org/ When I open the site first I don't see my last changes, sometimes, the site looks like it without CSS. I cleaned the cache with different plugins. I disable caching on the server, and my hoster said to me that they don't use CDN for my webpage, I changed the theme from Astra to Twenty Twenty-One it also doesn't help. The problem you can see if you open the webpage on your phone and refresh Plugins I have: Elementor Elementor Pro Bluehost Starter Templates A: You can change your current theme to storefront and check whether the scripts and styles are properly enquequed. use this format to enqueque style and scripts and inspect the code for debugging class yourPluginName { public function __construct() { add_action('wp_enqueue_scripts', array($this, 'enqueue')); } public function enqueue() { wp_enqueue_script("jquery"); wp_enqueue_script('my-js', plugins_url('/script.js', __File__)); wp_enqueue_style('my-theme', plugins_url('/style.css', __File__)); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Load posts via AJAX without draft status When I load posts in the frontend via AJAX, I also see posts that have the status "Draft": function get_projects() { $args = array("post_type" => "project"); $loop = new \WP_Query($args); $projects = array(); while($loop->have_posts()) { $loop->the_post(); $project = '...'; array_push(projects, $project); } wp_reset_postdata(); echo json_encode($projects); die; } add_action('wp_ajax_get_projects', 'get_projects'); add_action('wp_ajax_nopriv_get_projects', 'get_projects'); The WordPress doc says the following about this: post_status (string / array) – use post status. Retrieves posts by post status. Default value is ‘publish‘, but if the user is logged in, ‘private‘ is added. Public custom post statuses are also included by default. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are ‘future‘, ‘draft‘ and ‘pending‘. Source (WordPress Developer Resources) Is there any way to prevent the status "protected" from being issued as well? A: admin-ajax.php is treated as part of the admin, so protected statuses will be included. To solve this just explicitly define post_status as publish to only get published posts: $args = array( 'post_type' => 'project', 'post_status' => 'publish' ); Or, better yet, consider using the REST API for AJAX requests, instead of the aging admin-ajax.php approach. If you want to query a custom type and receive JSON then you probably don't even need to create your own endpoint.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use pre declared blocks in a php file? Is there a way/ a function to insert a block and user reusable blocks from inside a php page/template-part like use_block('jetpack/google-calendar') to a block? (I am using a partial block theme, since block theme doesn't have support for all the features I want to use, but I still want the site to look uniform and not to use different styles for the same section) I have looked all over https://developer.wordpress.org/?s=block but I didn't find any suitable thing. A: You can use do_blocks and insert block content as string in that function, which will like do_shortcode transform block's html and metadata in html comments into final html. I am not sure if it works for reusable blocks, I never used them. If you want to use block theme, you should develop your own blocks for any missing features. This is nowadays much easier than it used to be, you can tweak existing blocks, create block variants, block styles, enqueue extra style for core blocks (wp_enqueue_block_style) etc.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a simple design in classic editor plugin creating post page through another Wp plugin I want to add simple html form without breaking the extisiting design or license of Classic Editor plugin which is GPLv2 I added simple code in classic-edior.php file (I'm not sure If it's the best way but I'm making a wp-plugin that must this simple form comes in Classic Edior creating post page so I can't use adding short code maybe?. function myfunction() { // after this next, plain HTML ?> <!-- HTML !--> <!-- HTML !--> <div style=" "> <button class="button-2" role="button" style=" display: flex; margin-left:25%; justify-content: center; ">Button</button> <form action="/action_page.php" style=" margin: auto; width: 50%;border: 3px solid black; padding: 10px;"> <label for="fname">Action:</label><br> <input type="text" id="fname" name="fname" value=" "><br> <input type="submit" value="Submit"> </form> </div> <!-- more HTML code here --> <?php // back to PHP // .. some more PHP stuff return; } myfunction(); A: You would need to do the following: * *add a metabox with a text input and a button ( give them unique IDs ) *enqueue a javascript file *in your javascript file, look for the input and button by the unique ID you gave them * *when the button is pressed, look up the inputs value, and make your AJAX request, jQuery should be enough to do this if you're unsure how *if it's successful, replace the content in the TinyMCE field using the standard javascript APIs *you will also need to implement an AJAX handler, either as a REST API endpoint, or via the old admin-ajax.php API. This is what makes the request to your API ( also why use curl when WordPress has a more portable wrapper around it with wp_remote_get/wp_remote_post and the WP_HTTP API ) There are quite a few parts here, each of which are covered already on the official dev docs and in questions other people have already asked and answered on the site. If you are unsure how to do any of the steps, search this stack or the official WP documentation for that smaller step. Important notes: * *never make direct browser requests to PHP files in your plugin or theme *never modify plugins you didn't write yourself *you don't need to modify the classic editor plugin to add metaboxes, any plugin can do that *you don't need the classic editor plugin to make custom post types not use the block editor *you could replace all the blocks in the block editors content in a 1 liner, using the classic editor does not make this task easier ( and the block editor will show a custom metabox in the sidebar anyway )
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Title- Custom taxonomy by using get_term Custom taxonomy( Categories) by using get_terms means recalling the categories in the URL for eg - Supoose abcd.com is gadget related website and I want to open its categories wise how can I do it? Eg - abcd.com/hub/categories/news/mobiles I want these types of links hub= custom post type, categories=taxonomy which I want to recall in URl news = custom taxonomy (categories) mobles = sub-categories Kidly I request that I really need help I also code but how to implement I don't know.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Network / Multisite login to one site allow access to all I have a wordpress installation that uses wordpress network (which I think was previously known as Wordpress Multisite). I have the following sites setup, http://www.example.com/uk http://www.example.com/fra http://subdomain.example.com I assumed that cookies would be able to be shared as they all use the same domain, but that does not seems to be the case, when I login at /uk and go /fra I am greeted as a logged out user, similarly so when I navigate to subdomain.. I have setup some cookie definitions in my wp-config.php define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', 'example.com'); define('COOKIEPATH', ''); define('COOKIEHASH', md5('BsyhlSyF-FhL9OED') ); define('SITECOOKIEPATH', ''); Where am I going wrong, I assumed that wordpress network/multisite would allow a user to sign in on one site and use that authentication across the network of sites?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Impossible to update jQuery version from 3.1.0 PageSpeed Insights is complaining about me using jQuery version 3.1.0 because of security risks. I've been trying to update my jQuery version with two plugins: * *jQuery Updater *jQuery Version Control I have cleared the cache after making the necessary configurations for the plugins, but to no effect. (My Wordpress version is 6.1.1 and all the other plugins are updated) When I check the jQuery version by typing jQuery.fn.jquery in the Developer Console, the version is still 3.1.0 What else can I try to do in order to update the jQuery version so Google regards my site as safe?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic header and footer template inclusion: footer script not included I have a file that is being required by both the header and footer, and that file is meant to include the content for the footer or header dynamically. So in my header.php and footer php, I only set a couple of variables, and include a common file, "include-cached-template": <?php $templatePath = get_template_directory() . '/templates/core-parts/footer-content.php'; $cacheId = 'footer'; require_once get_template_directory() . '/template-inclusion-handling/include-cached-template.php'; In include-cached-template.php I include the template that has the content for header or footer. I check that the dynamic variables are set, then do some cache check and require the template by the provided template path. So it starts with: <?php // required variable: $templatePath if(!isset($templatePath) || !isset($cacheId)){ return; } EDIT: I did some debugging, where it seemed that the variables were still having the values for the header when the template to include the footer was loading. But it turns out that the template to load the footer was never included (as Tom Nowell points out below) A: This is because the code uses require_once which only loads and runs the file once. require would fix the problem, but it would actually be better to use get_template_part() instead. This would allow you to use template filters, block templates, and child themes. get_template_part( string $slug, string $name = null, array $args = array() ): void|false https://developer.wordpress.org/reference/functions/get_template_part/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wp_redirect() doesn't work I am inserting a piece of code to my website that includes a redirect statement. Everything works fine except the wp_redirect();. The following warning message appears. Cannot modify header information - headers already sent by (output started at /home/xyz.com/b14_32999707/htdocs/wp-includes/class-wp-styles.php:350) in /home/xyz.com/b14_32999707/htdocs/wp-includes/pluggable.php on line 1416 Following is line 1416 of the mentioned file. $x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location ); if ( is_string( $x_redirect_by ) ) { header( "X-Redirect-By: $x_redirect_by" ); //Line 1416 } header( "Location: $location", true, $status ); return true; Tried each and every solution available on the web but nothing works except the JavaScript redirect which I don't want to use. Even a very simple php code like the following doesn't work. <?php if(...){ wp_redirect('http://www.my-site.com/my-page/'); exit(); } A: The problem is not what you are doing, but when you are doing it. When your browser requests a webpage, that webpage arrives with a set of HTTP headers, followed by a HTTP body that contains the HTML. Redirection is done via a HTTP header. The moment you echo, or printf or send any form of HTML, or even blank space PHP will send HTTP headers telling the browser to expect a webpage, then it will start sending the HTTP body. When this happens your opportunity to redirect has gone, and any attempt to send a HTTP header will give you the error in your question. For this reason, you cannot trigger http redirects in shortcodes, widgets, templates, etc. Instead, do it earlier, before output begins, preferably in a hook, e.g. add_action( 'init', 'asmat_maybe_redirect' ); function asmat_maybe_redirect() : void { if ( ... ) { wp_redirect( 'http://www.my-site.com/my-page/' ); exit(); } } Additionally, if that redirect is to somewhere else on the same site, use wp_safe_redirect instead. But whatever you do, it must happen early before any output occurs.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I display and edit other posts within the 'Edit Post' area of Wp-Admin Dashboard I'm wondering how to edit the 'New Post/Edit Post' area of Wordpress. I want to create a new 'Screen Element' like the plugins do. I want this area to display all posts with a corresponding taxonomy tag to the post being edited. I know how to write the code to make this work on the frontend. I just don't know how to apply this area to the backend. How do I create new areas in the backend? Plugins like Yoast SEO and Toolset create a new box there. Do I need to create a plugin to do so, or can I write a function for the functions.php? Thanks! A: Here is the code and explanation from this article about adding a custom meta box to the WordPress dashboard new post area. function custom_meta_box_markup() { } function add_custom_meta_box() { add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_markup", "post", "side", "high", null); } add_action("add_meta_boxes", "add_custom_meta_box"); add_meta_box should be called inside add_meta_boxes hook. add_meta_box takes 7 arguments. Here are the list of arguments: * *$id: Every meta box is identified by WordPress uniquely using its id. Provide an id and remember to prefix it to prevent overriding. *$title: Title of the meta box on the admin interface. *$callback: add_meta_box calls the callback to display the contents of the custom meta box. *$screen: It's used to instruct WordPress in which screen to display the meta box. Possible values are "post", "page", "dashboard", "link", "attachment" or "custom_post_type" id. In the above example we are adding the custom meta box to WordPress posts screen. *$context: It's used to provide the position of the custom meta on the display screen. Possible values are "normal", "advanced" and "side". In the above example we positioned the meta box on side. *$priority: It's used to provide the position of the box in the provided context. Possible values are "high", "core", "default", and "low". In the above example we positioned the meta box *$callback_args: Its used to provide arguments to the callback function.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Category Redirection Problem I am trying to redirect all categories at once to a specific page but didn't find any solution. I go through a solution by redirecting one by one category to a specific page. So is there any solution to redirect all categories? Thanks
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to save the results of a query as a php file for an autocomplete search bar I'm looking to cache the results of some queries in order to make autocomplete search bars and lists for forms. I'm using it for a form with <input type="list">. I'd like to save the post titles of a custom post type to a .php file $args = array( 'post_type' => 'custom_post_type', ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $thetitle=get_the_title(); echo '<option value='.$thetitle.'>',$thetitle,'</option>'; } } I could copy and paste the results into a file called options.php and refer to that with my search bar. This would have all the selections as options. <select name="currency" class="form-control"> <?php include get_template_directory() . '/includes/options.php';?> </select> However, I'd like to have this query run periodically and update the list. Is there a way to do this? Is this an inefficient way of getting 'cached' options for dropdowns and for <input type="list"> options? Thanks so much
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rewrite rule taxonomy url with different values in one function So I'm a little bit stuck here and honestly don't know how to proceed, I'm trying to do a rewrite rule to a series of specific urls I have a movies custom post type and an alphabet taxonomy and the terms A-Z, and I'm trying to make the url from sample.com/alphabet/a to sample.com/movies/a. So I tried this code in functions.php and it works for alphabet A. function custom_rewrite_rules() { add_rewrite_rule('^movies/a/?', 'index.php?taxonomy=movies_alphabet&term=a', 'top'); } add_action('init', 'custom_rewrite_rules'); Question: so my question is how to apply it on all alphabet? not just A but also the rest of the alphabets b,c,d,e,f,g,h,j without repeating writing custom_rewrite_rules() function. A: You can do that using a subpattern or capturing group like ([a-z]) in your rewrite rule's regex (i.e. regular expression pattern, which is the 1st parameter for add_rewrite_rule()), and then use $matches[<n>] in your query (the 2nd parameter for add_rewrite_rule()), where <n> is a number (1 or above) and it's the subpattern's position number. * *Why use $matches: Because when matching the current URL against the rewrite rules on your site (i.e. rules which use index.php), WordPress will use preg_match() with the 3rd parameter set to $matches. So for example in your case, you can try this which should match movies/a, movies/b, movies/c and so on, and that the $matches[1] would be the alphabet after the slash (e.g. c as in movies/c): add_rewrite_rule( '^movies/([a-z])/?$', 'index.php?taxonomy=movies_alphabet&term=$matches[1]', 'top' ); Notes: * *I added $ to the regex, so that it only matches movies/<alphabet> like movies/a and not just anything that starts with that alphabet or path (e.g. movies/aquaman and movies/ant-man). *See this for more details on regex meta-characters like that $. *You can play with the above regex here. ( PS: You can learn regex via this site; just check the explanation for the specific regex pattern.. :) ) Don't forget to flush the rewrite rules — just visit the Permalink Settings admin page, without having to do anything else. Bonus To support for pagination, e.g. the 2nd page at https://example.com/movies/a/page/2/, you can use the following regex and query: Note that we now have 2 capturing groups — ([a-z]) and (\d+) (the page number). $matches[2] is used to get the page number and will be the value of the query var named paged. add_rewrite_rule( '^movies/([a-z])(?:/page/(\d+)|)/?$', 'index.php?taxonomy=movies_alphabet&term=$matches[1]&paged=$matches[2]', 'top' ); You can test the regex here, and once again, remember to flush the rewrite rules after making changes to your regex and/or query. Happy coding!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change default URL (or permalinks) in the back-end Assume I have the following code add_menu_page('My Title', 'My Title', 'publish_posts', 'my-slug', function () { require_once ('path/to/render/page.php'); }); This code will add a menu item to the side bar of the admin section, and if you click on that new menu item, and inspect the URL, http://example.com/wp-admin/admin.php?page=my-slug Everything is great so far. Now my question: Is it possible to change the default URL above to something maybe like this? http://example.com/wp-admin/my-slug Or this? http://example.com/wp-admin/page/my-slug Or even this? http://example.com/wp-admin/admin.php/page/my-slug Basically, I do NOT want the query variables to be displayed as shown in the default setup. In other words, can I change the permalinks for the back-end? Thank you.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create a hierarchical list of posts that's grouped and nested by category I'm trying to show a list of book recommendations, grouped and sorted by category. The problem is some book recommendations belong only to a top-level category and some belong to sub-categories. I'd like to display the list like this: Book Category 1 Book Sub Category 1 * *Book 1 *Book 2 Book Sub Category 2 * *Book 3 *Book 4 Book Category 2 * *Book 5 *Book 6 *Etc. I've gotten the list to display all parent level categories, and books belonging to a sub-category but can't figure out how to create a condition for book recommendations that belong just to a parent category. Here's my code: $terms_array = array( 'taxonomy' => 'book_category', 'parent' => 0, ); $book_category_parents = get_terms($terms_array); foreach($book_category_parents as $book_category_parent): ?> <h1><?php echo $book_category_parent->name; ?></h1> <?php $subterms_array = array( 'taxonomy' => 'book_category', 'parent' => $book_category_parent->term_id, ); $book_category_children = get_terms($subterms_array); foreach($book_category_children as $book_category_child): ?> <h2 class="dark-gray"><?php echo $book_category_child->name; ?></h2> <?php $post_args = array( 'posts_per_page' => -1, 'post_type' => 'book', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'term_id', 'terms' => $book_category_child->term_id, ) ) ); $myposts = get_posts($post_args); ?> <ul> <?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <li> <a href="#"><?php the_title(); ?></a> </li> <?php endforeach; ?> </ul> <?php endforeach; ?> <?php endforeach; ?> This doesn't display anything for books with only a parent level category.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to authenticate/verify login credentials & check for user meta without logging in? I have custom login form and i used wp_signon() to authenticate. However, i wanted to run an additional check for usermeta and if the user has account_status === pending, throw an error or or prevent them from getting logged in. How do i do that? I can't seem to find a filter A: You could do this with a low-priority authenticate filter. I'm surprised there aren't more appropriate hooks in the login process, but I can't see one. (There is already an example of a filter like this though: wp_authenticate_spam_check.) If the value the filter is given is a user, that means a previous filter has accepted the username & password. We can then perform our check and then either return the user if good or an error if not: function authenticate_reject_account_status_pending( $user, $username, $password ) { if ( $user instanceof WP_User ) { if ( $user[ 'account_status' ] === 'pending' ) { return new WP_Error( 'user_is_pending', __( 'Account is pending approval. Please contact support for help.' ) ); } } return $user; } add_filter( 'authenticate', 'authenticate_reject_account_status_pending', 999999, 3 ); I have not tested this, but the general pattern should work even if this code doesn't. This runs before the cookie is created etc.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WordPress 6.1.1 does not upload the .WEBP images but with old browser upload does it correct I have WordPress version 6.1.1 and hello theme version 2.6.1 The issue is weird, from Dashboard -> Media I'm not able to upload .WEBP images. but when I click on Try the browser uploader instead it uploads .WEBP file successfully. but when I try from multi-file uploader(which is the default uploader) I got the below error: "This image cannot be processed by the web server. Convert it to JPEG or PNG before uploading." Screenshot: https://prnt.sc/Hy2VBEa2rGoH after, upload with browser-uploader the .WEBP image appears on media gallery without any issue and I can use the uploaded image in Elementor or anywehere. How can I fix this problem?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enable Gutenberg Editor when editing tags My content creators love the Gutenberg editor in Wordpress. However, they now want to write extensive descriptions for the tag pages for SEO reasons, and WordPress only offers the old default editor, which is clunky and doesn't do everything they want. Is it possible to enable Gutenberg on the tag editing page?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Product customizing quiz - quiz adding products to the cart Spend a lot of time on this and my client is getting angry but still no results… Is there any plugin (or solution to use) you know to instantly add product to cart after giving specific answer on a quiz? Cannot find anything like that. I’ve tried Product Recommendation Quiz but It just counts “votes” after every answer and then allows customer to manually add specific product to the cart. I would like to make it happen automatically. For eg “How old are you?” And when i click answer “more than 60 years old” it drops a vitamin pack (or better - 1000mg Vitamin C) into my basket immediately. Examples are: HUM Nutrition | Vitamins for Skin, Body & Mood, and https://www.gainful.com/quiz/ Thanks for your help, i would really appreciate it…
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieve data from external database and insert back in I have some code in my functions.php which inserts from fields into an external database table. and that part works okay. I then want to get the ID of the row I have inserted so I can insert into another table using the ID as the link between the tables. This section works fine: /* -- Send Form Entries to CRM -- */ add_action( 'elementor_pro/forms/new_record', function( $record, $ajax_handler ) { $raw_fields = $record->get( 'fields' ); $fields = []; foreach ( $raw_fields as $id => $field ) { $fields[ $id ] = $field['value']; } $DB_HOST = 'XXXX'; $DB_USER = 'XXXX'; $DB_PASS = 'XXXX'; $DB_NAME = 'XXXX'; $miss = $fields['missout']; if ($miss == "on") {$missnow = "Yes";} else {$missnow = "No";} $created = date('Y-m-d'); $web_id = uniqid('cs'); global $crmdb; $crmdb = new wpdb($DB_USER, $DB_PASS, $DB_NAME, $DB_HOST); $output['success'] = $crmdb->insert('customers', array( 'title' => $fields['title'], 'firstname' => $fields['firstname'], 'lastname' => $fields['surname'], 'fullname' => $fields['firstname'].' '.$fields['surname'], 'email' => $fields['emailaddress'], 'phone' => $fields['telephone'], 'marketing_source' => $fields['findout'], 'email_marketing' => $missnow, 'created' => $created, 'last_job' => $created, 'web_id' => $web_id)); $ajax_handler->add_response_data( true, $output ); $crmdb -> close(); }, 10, 2); The above all works okay but when I add this in before the ajax_handler line I can't get it to pull data from the database and insert into a different table on the database. Any help would be greatly appreciated: $query = $crmdb->ger_var("select * from customers where web_id = '$web_id'"); $result = mysqli_query($crmdb, $query); while($row = mysqli_fetch_array($result)){ $cusid = $row['id']; $outputnew['success'] = $crmdb->insert('opportunities', array( 'customer_id' => $cusid)); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress does not show the custom fields box I have created a new CPT in my wordpress locally at the moment, I need it to have custom fields and I have added it so that it does. the code: register_post_type( 'centro_de_recursos', array( 'labels' => array( 'name' => __( 'Recursos' ), 'singular_name' => __( 'Recurso' ) ), 'supports' => array('title', 'thumbnail', 'custom-fields'), 'public' => true, 'has_archive' => false, 'rewrite' => array('slug' => 'centro_de_recursos'), 'show_in_rest' => true, ) ); The thing is that searching for goole what I can see is that I should see in the "screen options" something like "custom fields"... And it is not like that, it has come to seem to me at certain times, but now I do not see any similar option in that field. Why is that? Edit: Here I show the current CPT options that appear with the supports. - A: It's very likely that your CPT does indeed have custom fields, but because you're using the classic editor, you need to have also enabled custom fields on the user you're logged in as via the user profile/settings page This is how core decides if there's a custom fields metabox: if ( post_type_supports( $post_type, 'custom-fields' ) ) { add_meta_box( 'postcustom', __( 'Custom Fields' ), 'post_custom_meta_box', null, 'normal', 'core', array( '__back_compat_meta_box' => ! (bool) get_user_meta( get_current_user_id(), 'enable_custom_fields', true ), '__block_editor_compatible_meta_box' => true, ) ); } Notice this specifically: '__back_compat_meta_box' => ! (bool) get_user_meta( get_current_user_id(), 'enable_custom_fields', true ), Important You don't need the custom fields metabox to use post meta. Lots of fields plugin frameworks exist, and post meta works even if the metabox isn't present and your CPT doesn't support them. Nothing is stopping you from using get_post_meta and update_post_meta, or registering your own custom metaboxes that read/save/update these values. You might see very old tutorials or tutorials from people with less experience using this as a beginner method of adding data without introducing metaboxes or sidebar panels, but modern WP development rarely relies on these.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle Ajax Calls, when using same shortcodes (with different parameters, e.g. 'post-type')? this is my very first question here. So please don't be too angry, if I miss something out or make mistakes while using the plattform. I was, of course, trying to find an answer on my problem first. Didnt work out too good :) My Problem: I'm trying to implement more dynamic content on a page, so I'm working around with ajax-function-calls in a shortcode. I managed to follow a lot of tutorials and successfully created a single shortcode with a post-type-parameter, which outputs f.e. the last 5 posts of a type and a pagination. I created the needed ajax function call in js and everything. Its working and so far I thought, I understand the logic behind it. But when I'm using the shortcode, with another post-type-parameter, twice or more on the same page, only the content of the last shortcode is loaded. A single shortcode with a given post type is always loading the content correctly. So now I'm stucked and I think, maybe I didnt get the idea behind ajax-calls and localization for js in wordpress, yet. If you add the script via action, like you should, its loaded only once, of course. How does localization work in general, when an "ajax.js" is called more than once on a page? Do I maybe have to create ajax_actions dynamically for every shortcode in a case like that? I will post my code, if you wish, but maybe the general answer already helpes me to understand the idea behind it. greetings to everybody EDIT: Okay, here is the code: functions.php require_once KNE_THEME_DIR . '/includes/helpers/view-classes/class-kne-theme-data-slider.php'; $slider = new KNE_DATA_SLIDER(); add_shortcode('kne_data_slider', array($slider, 'shortcode')); // creating Ajax call for WordPress add_action('wp_ajax_nopriv_kne_ajax_posts', array($slider, 'get_data_callback')); add_action('wp_ajax_kne_ajax_posts', array($slider, 'get_data_callback')); the dataslider-class <?php defined('ABSPATH') or die('No script kiddies please!'); class KNE_DATA_SLIDER { /** Data Slider Konstruktor */ public function __construct() { } /** Shortcode */ public function shortcode($atts) { extract(shortcode_atts(array(), $atts)); $posts_total = (isset($atts['posts_total']) ? $atts['posts_total'] : -1); $posts_per_page = (isset($atts['posts_per_page']) ?$atts['posts_per_page'] : -1); $post_type = (isset($atts['post_type']) ? $atts['post_type'] : 'post'); $kne_unique = rand(1, 9999); $nonce = wp_create_nonce('kne_ajax_nonce'); wp_register_script('kne_ajax_js', KNE_THEME_URI . '/assets/js/ajax-implementation.js', array('jquery'),'', false); wp_enqueue_script('kne_ajax_js'); $data_string = [ 'ajaxurl' => admin_url('admin-ajax.php'), 'security' => $nonce, 'page' => $page = (isset($page) ? $page : 1), 'post_type' => $post_type, 'posts_total' => $posts_total, 'per_page' => $posts_per_page, 'kne_unique_id' => $kne_unique ]; wp_add_inline_script('kne_ajax_js', 'var kne_ajax_object = ' . json_encode($data_string), 'after'); // wp_localize_script('kne_ajax_js', 'kne_ajax_object', $data_string); KNE_THEME_ENGINE::add_bootstrap(); ob_start(); ?> <div class="kne-posts-container-<?php echo $kne_unique ?>"> <span class="kne-loader">Loading...</span> <div class="kne-post-content"> </div> <div class="kne-post-content_name"> </div> </div> <?php return ob_get_clean(); } /** Get Data Callback */ public function get_data_callback($atts) { // check the nonce - still too simple check_ajax_referer('kne_ajax_nonce', 'security'); //get the data from ajax() call if (isset($_POST['page'])) { $post_type = $_POST['post-type']; $page = $_POST['page']; $page -= 1; $per_page = (isset($_POST['per_page']) ? $_POST['per_page'] : -1); //set the per page limit $start = $page * $per_page; $all_the_posts = new WP_Query(array( 'post_type' => $post_type, 'post_status ' => 'publish', 'orderby' => 'post_date', 'order' => 'DESC', 'posts_per_page' => $per_page, 'offset' => $start )); if ($all_the_posts->have_posts()) { while ($all_the_posts->have_posts()) { $all_the_posts->the_post(); echo the_title('<h3>', '</h3>', true); } } die(); } } // end of data-callback-function } // end of class the js jQuery(document).ready(function ($) { console.log('Ajax Implementation loading'); var post_data = { 'action' : 'kne_ajax_posts', 'security' : kne_ajax_object.security, 'page' : kne_ajax_object.page, 'post-type': kne_ajax_object.post_type, 'kne_unique_id' : kne_ajax_object.kne_unique_id, 'per_page' : kne_ajax_object.per_page, } $.post({ url: kne_ajax_object.ajaxurl, data: post_data, type: 'post', success: (response) => { console.log(response); var container = $('.kne-posts-container-' + kne_ajax_object.kne_unique_id); $(container).append(response); // var name_active_link = $(container + ' .kne-post-content' + '_name' + ' .kne_posts_pagination li.active'); // $(name_var).html(response); // $(container + ' .kne-loader').css('display', 'none'); // $(name_active_link).on('click',function(){ // console.log('clicked'); // var page = $().attr('p'); // kne_posts_make_ajax_call(kne_ajax_object, page); // }); }, error: (response) => { console.warn(response); } }); // $( document.body ).trigger( 'post-load' ); }); A: The problem is that your JS needs to know the post type for each shortcode, but rather than looking at the shortcodes output, it looks at the main global kne_ajax_object, and since there is only one kne_ajax_object, there can only be one post type. Additionally, your javascript code only runs one time, and only makes one AJAX call, which means there can only be one post type and one shortcode. Instead, store the AJAX URL/security stuff in kne_ajax_object but put the rest of the information on the HTML the shortcode generates. E.g. instead of this: <div class="kne-posts-container-<?php echo $kne_unique ?>"> Why not this? <div class="kne-posts-container" data-post-type="mycpt"> Then do the equivalent of this in JS: foreach element that matches `.kne-posts-container` post type = element.data('post-type') do the ajax call on success element.append( result ) Or even better, use the REST APIs that WordPress already provides. WP already has AJAX friendly data only URLs that return all this information as JSON, with pretty URLs like example.com/wp-json/wp/v2/posts. Additional Notes echo the_title('<h3>', '</h3>', true); the_title already echo's so this is the same as echo echo get_title(, you don't need to use echo on most functions that begin with the_ Using -1 for posts_per_page is bad, I know you want to list all posts, but can your server load an infinite number of posts? If it can handle 500 or less posts, why not set it to 500? Why chance that your server will fallover trying to send thousands of posts? Set posts_per_page to a high number you never expect to reach, but you know your server can actually handle. There's no point using offset, this isn't going to apply some old MySQL pagination speed trick. Just used the standard parameter 'paged' => $page, it might even be faster. Finally, escaping. This is bad code: echo '<a href="'. $url . '">'; Are you sure $url is a URL? Do you trust that? What if your site was hacked and it actually contains "><script>nasty stuff goes here</script>? Instead escape: echo '<a href="'. esc_url( $url ) . '">'; Now it is always a URL, it is guaranteed, we no longer need to trust $url. If it contains something nasty, it'll be neutered, cut down to a URL shaped size, and the worst case scenario is now a broken link. Finally, this: $slider = new KNE_DATA_SLIDER(); add_shortcode('kne_data_slider', array($slider, 'shortcode')); This is not object oriented programming, it's just functions being put inside a class. If you removed the class and turned them into pure functions it would work exactly the same. It's just additional boilerplate. If you're going to create classes and objects, do it because you need to. If you don't plan to create more than one of an object, and your class has no internal state, it's usually a sign you don't need a class/objects for the task. Namespaces will serve the same purpose just as well. A lot of developers think that as they get more experienced everything becomes objects and OOP, and use classes for everything regardless of what it is or wether it benefits tem, but that's not true. OOP is a tool that can be very useful, but it's not a universal hammer that does everything, use it when it's needed but for most things in WordPress like simple shortcodes or action hooks it's overkill.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to anchor to embed video How would I create an anchor link from the Test text to the embed conten? I tried adding an id="03T" inside of the div within the embed comment block. However, when doing that I am unable to see the embed block in the visual editor. <!-- wp:paragraph --> <p><a href="#03T" data-type="internal" data-id="#03T">Test</a></p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>Videos</h2> <!-- /wp:heading --> <!-- wp:embed {"url":"https://player.vimeo.com/video/25323516?","type":"video","providerNameSlug":"vimeo","responsive":true,"className":"wp-embed-aspect-4-3 wp-has-aspect-ratio"} --> <figure class="wp-block-embed is-type-video is-provider-vimeo wp-block-embed-vimeo wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper" id="03T"> https://player.vimeo.com/video/25323516 </div></figure> <!-- /wp:embed --> Any ideas on what could be fixed to insert the anchor link and see it visible in the visual editor? A: Editing the raw HTML isn't going to work, a worst case scenario is it fails block validation when reopened in the editor and your edits get replaced automatically. Instead, use the anchor box under the advanced panel. Since the HTML of an embed usually comes from a 3rd party via OEmbed, you can wrap the embed block inside a group block, and give the group block the anchor. E.g. Note that "group block" is just a standard block of type group that comes with core. There are multiple ways to create them but they are just blocks that contain things, and can be found in the block picker/inserter. Any block that contains things/has children and can take an anchor attribute will also work. E.g. Column blocks, cover images, etc but group blocks are the simplest and least intrusive: Remember, when building things with lego bricks you don't get a chisel out and carve the shape you want into the brick, you build what you want out of many smaller blocks. WP blocks are the same, don't modify blocks, combine and use them as building bricks to create what you actually want.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Wordpress Search - Reject partial matches I'm currently looking into a solution for a project i'm working on where I would use the basic WP Search (the S attribute to a WP_Query) but it would need to only return full word matches (and reject partial-word matches) Like if I search for Phone, I want to return only Phones and not Cellphones or iPhones. Is there a way to ask WP to only return full word matches?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: External api call using wordpress I want to start a new website and chose wordpress as my cmd, but im having a restriction. The website is all about api request to other websites and i triedto get an api to test it as an example. After writing in php and add it to code snippet i got an error. I went through wordpress developers documentation and found out how to make an external api request, i did the same in the code snippet but still didn't work. So decided to code a php file and upload it into the wordpress directory, but before doing this, o decided to ask for help. About how to make and external api request from a wordpress website, where and how to input the code and use the api on a page or post? This is the api i tried to use for test: ''' curl --location --request POST 'https://api.apyhub.com/data/convert/currency' --header 'Content-Type: application/json' --header 'apy-token: APT03xPn2ZVq7rFriUtRoamaY9Ucg1c7y17CPd60WtMW03' --data-raw '{ "source":"eur", "target":"inr" }' ''' And i also tried using postman and it worked. Please help. A: Your curl request should work from the command line. Put you will want to use it in a PHP file: $ch = curl_init(); $url = "https://api.com/"; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); http_build_query(array('postvar1' => 'value1'))); // Receive server response ... curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $api_output = curl_exec($ch); curl_close($ch); Which php file you put the curl in is going to be dependent on what you are trying to accomplish. For instance, you might setup a cron job to query the api once and hour, updating your content as necessary. Knowing what you are doing would allow me to provide more guidance. A: You could try with WPGetAPI, a free plugin built just for this (if you want to go down the plugin route)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way to relate different custom post types? Let's say I have 3 CPTs: series, seasons, and episodes. Now if I post in these custom post types the URL would be: * *Series CPT > post name: sample serie > URL: site.com/series/sample-serie *Seasons CPT > post name: sample season > URL: site.com/seasons/sample-season *Episodes CPT > post name: sample episode > URL: site.com/episodes/sample-episode Now what I want to do is combine these URLs together: * *site.com/series/sample-serie/sample-season/sample-episode : To show the page for the sample episode (previously: site.com/episodes/sample-episode) *site.com/series/sample-serie/sample-season/ : To show the page for the sample season (previously: site.com/seasons/sample-season) How can I implement this? Was creating 3 custom post types a good idea for doing this? Or is there any other methods to do this? (Preferably without any plugins) Appreciate any further assistance! A: I think a better approach for this would be to create a single nested (hierarchical) custom post type. For example, it can be series. Then a single series named sample-series as a top level post of series post type: site.com/series/sample-series/. Then seasons named season-one, season-two etc. can be children of sample-series, like: site.com/series/sample-series/season-one, site.com/series/sample-series/season-two. Similarly, episodes can be children of those seasons, like: site.com/series/sample-series/season-one/episode-one, site.com/series/sample-series/season-one/episode-two etc. Same thing can be done by default by WordPress page, since pages are by default hierarchical.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: On WordPress.org Plugin repository, Last Updated Date doesn't match with Plugin Version Update Date I have been going through the Plugin lists on all my client sites, looking for Plugins that haven't been updated by Plugin Authors. Every time we update a Plugin on a website, we note the date in our documentation. In the process, I have noticed a strange disagreement: on WordPress.org Plugin repository, Last Updated Date doesn't match with the Plugin's Version Update Date. For example, in our documentation, a plugin named Category Post shows that the last update to version 4.9.13 was done on 9/29/2021. The date here would cause this to be marked as a plugin that might need to be replaced, because it looks like it's a plugin that isn't being maintained. But, when I went to WordPress.org (on February 2023) to check on the plugin, it says Last Updated: 1 month ago, to that same version number (4.9.13)! Any clue as to what is happening? A: Please check the Category Posts Plugin's Changelog on WordPress.org (on the Development tab). I'm providing the screenshot below: You'll notice that version 4.9.13 was indeed updated on JULY 22 2021. 4.9.13 – JULY 22 2021 Fixed Line number with WordPress 5.8 However, on the right side it shows: Last updated: 1 month ago. This last update doesn't refer to updates to the plugin version itself, rather updated information on wordpress.org that it was Tested up to: 6.1.1. I've dug further down the source code to the last commit of the plugin files, and you can see that the change was only made on the readme.txt file and it's just the Tested up to: 6.1 part: WordPress.org's plugin listing page is generated from this readme.txt file. So what WordPress.org is referring to when it says: Last updated: 1 month ago, is only this much. So you see, there's no significant update and there's no actual disagreement about the update date.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Registering custom taxonomy using reserved terms I'm using CPT UI to manage all my custom CPTs and taxonomies. I've tried adding custom taxonomy with slug type, and CPT UI displays an error saying that type is reserved term. Now, if I try register_taxonomy and use type as tax slug, everything works just fine. Can someone explain how can this be? A: That's because some terms are reserved by WordPress core and shouldn't be used as custom slug. However, WordPress core itself doesn't check within register_taxonomy function whether a developer has used those reserved terms or not. It's up to the developers to read the documentation and implement accordingly. These core functions are low level implementations, so developers have more freedom and power with these functions. And as they say: On the other hand, Custom Post Type UI plugin is more of a user facing implementation, hence it doesn't expect its users to read all the documentation as a more advanced developer is supposed to. So it takes care of the reserved terms. You can check the code of CPT UI's cptui_reserved_taxonomies() function to check how it is implemented. FYI, the following is from WordPress developer documentation on reserved terms: Avoiding the following reserved terms is particularly important if you are passing the term through the $_GET or $_POST array. Doing so can cause WordPress to respond with a 404 error without any other hint or explanation. * *attachment *attachment_id *author *author_name *calendar *cat *category *category__and *category__in *category__not_in *category_name *comments_per_page *comments_popup *custom *customize_messenger_channel *customized *cpage *day *debug *embed *error *exact *feed *fields *hour *link_category *m *minute *monthnum *more *name *nav_menu *nonce *nopaging *offset *order *orderby *p *page *page_id *paged *pagename *pb *perm *post *post__in *post__not_in *post_format *post_mime_type *post_status *post_tag *post_type *posts *posts_per_archive_page *posts_per_page *preview *robots *s *search *second *sentence *showposts *static *status *subpost *subpost_id *tag *tag__and *tag__in *tag__not_in *tag_id *tag_slug__and *tag_slug__in *taxonomy *tb *term *terms *theme *title *type *types *w *withcomments *withoutcomments *year
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WooCommerce Review ID Block add_filter('get_comment_author', 'my_comment_author', 10, 1); function asterisk($num){ $arr = array(); for ($i = 1; $i <= $num; $i++) { array_push($arr,"*"); } return $arr; } function customerName($cName){ $name = $cName; $explode_name = explode(" ", $name); $fname = $explode_name[0]; $count_fname = strlen($fname); $count_fname = 1 - $count_fname; $count_fname = abs($count_fname); $asterisk = implode("",asterisk($count_fname)); $final = "$fname[0] $asterisk"; return $final; } function my_comment_author( $author = '' ) { // Get the comment ID from WP_Query $comment = get_comment( $comment_ID ); if (!empty($comment->comment_author) ) { if($comment->user_id > 0){ $user=get_userdata($comment->user_id); $author=$user->first_name.' '.substr($user->last_name,0,1);'.'; // this is the actual line you want to change } } else { $author = $comment->comment_author; } return customerName($author); } What I want to do is expose only the first letter of the review ID and cover the rest with *. In WooCommerce, the ID is basically set to be exposed, but please let me know if there is a code that exposes only the first letter of the ID and covers the rest with *. I really, really need help.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bulk post approval and publishing doesn't work I'm new to WordPress plugin development. I'm trying to develop a simple plugin that creates a sub-menu named Approval under Posts menu and checks if any draft post has the post meta approve set to value 'pre-publish'. The plugin works fine up to this point. There's a button in the Approval sub-menu page to bulk approve all the posts with post meta approve set to the value 'pre-publish'. The bulk approve process is supposed to set the post meta approve to 'approved' and then publish all those posts. However, it doesn't work as I expected. Somehow the posts disappear instead! This is my plugin CODE: <?php /* Plugin Name: Approve Posts Description: Bulk approve posts. */ // Create sub-menu under Posts function karma_posts_approval_menu() { add_submenu_page( 'edit.php', 'Approval Posts', 'Approval', 'manage_options', 'approval-posts', 'karma_posts_approval_page' ); } add_action( 'admin_menu', 'karma_posts_approval_menu' ); // Approval sub-menu page content function karma_posts_approval_page() { $posts = karma_get_pre_publish_posts(); // Check for approve button submit if ( isset( $_POST['approve_all_posts'] ) ) { karma_approve_all_posts( $posts ); } else { karma_list_pre_publish_posts( $posts ); } } function karma_approve_all_posts( $posts ) { if( count( $posts ) > 0 ) { foreach ( $posts as $post ) { update_post_meta( $post->ID, 'approve', 'approved' ); $update_post = array( 'ID' => $post->ID, 'post_status' => 'published' ); wp_update_post( $update_post ); } } ?> <div id="message" class="updated notice is-dismissible"> <p>All posts have been approved and published.</p> </div> <?php } function karma_list_pre_publish_posts( $posts ) { if( count( $posts ) > 0 ) { echo '<h1>Posts requiring approval:</h1>'; echo '<ul>'; foreach ( $posts as $post ) { echo '<li><a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a></li>'; } echo '</ul>'; ?> <form method="post"> <input type="submit" name="approve_all_posts" value="Approve" class="button button-primary"> </form> <?php } else { echo "<h1>Nothing to approve.</h1>"; } } function karma_get_pre_publish_posts() { // get all draft posts with 'approve' custom field set to 'pre-publish' $args = array( 'post_type' => 'post', 'post_status' => 'draft' ); $approval_posts = array(); $draft_posts = get_posts( $args ); foreach ( $draft_posts as $post ) { if( get_post_meta( $post->ID, 'approve', true ) == 'pre-publish' ) { $approval_posts[] = $post; } } return $approval_posts; } A: The problem I can immediately see is, you've set: 'post_status' => 'published' This should be: 'post_status' => 'publish' Also, since you are only updating the post status, it's less error prone and more appropriate to use wp_publish_post function instead of wp_update_post function. With this change, your karma_approve_all_posts() function will look like this: function karma_approve_all_posts( $posts ) { if( count( $posts ) > 0 ) { foreach ( $posts as $post ) { update_post_meta( $post->ID, 'approve', 'approved' ); wp_publish_post( $post->ID ); } } ?> <div id="message" class="updated notice is-dismissible"> <p>All posts have been approved and published.</p> </div> <?php }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to create a fully functional user registration in WordPress? I used many user signup plugins for users registration and they did good job, but the problem is, each website collects different data through user registration forms. In my case, the data collected was stored partially in the users table in the database. For example, I want the users to mention their institute but I find this data nowhere in the database later. How do I create a fully functional user registration system in WordPress? I I can do a bit of PHP programming if that can help. A: You would want to create a custom registration form with HTML and send it to a PHP function that creates the user and then adds user meta data. For example, the form: <form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post"> <!-- TODO: add a nonce in here --> <!-- this "action" pipes it through to the correct place --> <input type="hidden" name="action" value="custom_registration"> <input type="text" name="username" /> <input type="text" name="email" /> <input type="text" name="institute" /> <input type="password" name="password" /> <input type="submit" value="Register" /> </form> This is just an example, in reality you would want to add extra validation and nonce to prevent any naughty business. This was just the basic form idea. Then in your functions.php file to receive the form you make a hook using add_action(), where the first parameter uses the format admin_post_nopriv_+[action]. The nopriv means that this is for non-logged in users to execute functions (which a user who is registering most likely would not be logged in) This [action] needs to match the value of the hidden action field in our HTML form. Since we called it custom_registration then the hook would be admin_post_nopriv_custom_registration: add_action( 'admin_post_nopriv_custom_registration', 'custom_make_new_user' ); // the format here is "admin_post_nopriv_" + [the hidden action you put in the html form] function custom_make_new_user(){ // TODO: validate the nonce before continuing // TODO: validate that all incoming POST data is OK $user = $_POST['username']; // potentially sanitize these $pass = $_POST['password']; // potentially sanitize these $email = $_POST['email']; // potentially sanitize these $institute = $_POST['institute']; // potentially sanitize these $user_id = wp_create_user( $user, $pass, $email ); // this creates the new user and returns the ID if($user_id){ // if the user exists/if creating was successful. $user = new WP_User( $user_id ); // load the new user $user->set_role('subscriber'); // give the new user a role, in this case a subscriber // now add your custom user meta for each data point update_user_meta($user_id, 'institute', $institute); wp_redirect('/thank-you'); // redirect to some sort of thank you page perhaps. }else{ // user wasn't made } } That should do the trick. You could add any other user data you wanted by adding extra update_user_meta(); - the first param is the user_id, second param is the meta_key, third param is the meta value. The neat thing about update_user_meta() is that if it didn't exist already it will make it, otherwise it will update an existing value. Then to retrieve this data anywhere, you would write this: $user_institute = get_user_meta($user_id, 'institute', true); The third parameter of get_user_meta is useful because without it, or with it set to false by default, you would receive an array but with it set to true it returns a single value ready to use. Hope that helps! A: Ultimate Member is generally one of the most popular ones to use, creating a user registration form manually is easy - the hard part to manage manually is the login and everything that comes with that (i.e. forgotten passwords, verifying email addresses etc. it's no easy feat!), Custom fields for Ultimate Member are in the usermeta database table
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Gutenberg block HTML image rendering override Hello fellow developers, I am currently working on a side project using WP as my headless CMS which I consume via the REST API. When I retrieve the post's rendered content (post.content.rendered) my images are rendered like this: <figure class="wp-block-image size-large"> <img decoding="async" src="image.jpg" /> </figure> How can I customize this output HTML, so that I can edit the img tag attributes? What I would like to do on my frontend is add lazyloading and reduce layout shift, which is typically achieved via HTML attributes and CSS. Ideally my output would look something like this: <figure class="wp-block-image"> <img loading="lazy" data-src="image.jpg" /> </figure> Thanks! Ricky
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving multiple custom meta box fields So, I have a custom metabox, with multiple fields on it, and the amount of boxes is variable (could be 3, could be a lot more, depending on order quantity number) I'm trying to write a save function that will loop though all the fields, see which ones need updating/saving, then do the save SIDE NOTE: The custom metabox is added to a WooCommerce Order The metabox is displaying fine on the order edit page Here's what I have so far: function order_add_delegates_metabox() { add_meta_box( "order-delegates", // metabox id "Ticket Delegates", // metabox title "delegates_meta_markup", // metabox markup callback "shop_order", // post type "normal", // metabox position "low", // metabox priority on screen ); } add_action("add_meta_boxes", "order_add_delegates_metabox"); function delegates_meta_markup() { global $post; wp_nonce_field(basename(__FILE__), "add_delegates_nonce"); ?> <table class="wp-list-table widefat fixed striped table-view-list"> <thead> <tr> <th>Ticket Type</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <?php $order = new WC_Order($post->ID); $qty = $order->get_item_count(); for($x = 1; $x <= $qty; $x++) { ?> <tr> <td> <select id="ticket_type_<?= $x; ?>" name="ticket_type_<?= $x; ?>" style="width: 100%"> <option>--</option> <?php foreach($order->get_items() as $item_id => $item) { echo '<option value="'.str_replace(' ', '_', $item->get_name()).'">'.$item->get_name().'</option>'; } ?> </select> </td> <td> <input type="text" id="del_name_<?= $x; ?>" name="del_name_<?= $x; ?>" placeholder="Delegate Name" style="width: 100%" value="" /> </td> <td> <input type="email" id="del_email_<?= $x; ?>" name="del_email_<?= $x; ?>" placeholder="[email protected]" style="width: 100%" value="" /> </td> </tr> <?php } ?> </tbody> </table> <?php } function save_custom_meta_box($post_id, $post) { // nonce check if(!isset($_POST['add_delegates_nonce']) || !wp_verify_nonce($_POST['add_delegates_nonce'], 'agm')) { return $post_id; } // check current user permissions $post_type = get_post_type_object($post->post_type); if(!current_user_can($post_type->cap->edit_post, $post_id)) { return $post_id; } // do not save the data if autosave if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // define your own post type here if('shop_order' !== $post->post_type) { return $post_id; } // save fields data return $post_id; } add_action("save_post", "save_custom_meta_box", 10, 3); Any ideas? I can't think how I'm going to do it, as each field is generating and will be saved with it's own meta key (ticket_type_1, ticket_type_2 ... del_name_1, del_name_2 ... del_email_1, del_email_2)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Deobfuscate a sourcecop protected WordPress plugin? I have a plugin, which was obfuscated by plugin developer with sourcecop. At some point it began sending out lots of php warnings to debug.log. I couldn't debug it myself since it was obfuscated, but plugin support was also silent. Online Deobfuscateors I tried didn't help. How to Deobfuscate it? A: I came up with a single (linux) terminal command to deal with this. Logic is to just change eval( code_to_eval ) in obfuscated php files to file_put_contents( __FILE__, code_to_eval ). At least that worked for me (my problematic plugin was "Wishlist 1Click Registration" by "HappyPlugins"). Here's the command: grep -irl --include \*.php "eval(.*);" . | xargs -i sh -c "echo {}; sed -i 's/eval(\(.*\));/file_put_contents(__FILE__,\1);/g' {}" | xargs -i sh -c "echo {}; php {} > /dev/null || true; sed -i '1s/^?>//g' {}" What the command does: * *gets all .php files in current directory (need to cd to plugin root directory) that contain eval() in them, *replaces all eval( code ) with file_put_contents( __FILE__, code ), *executes those files with php (need to have php available from command line) - this runs all file_put_contents() statements and replaces all current obfuscated code in .php file with whatever was passed to eval(). *removes ?> from beginning of each of those files afterwards - it was used for eval code to work for some reason, but now it would just echo "?>" to browser, which we don't need. Afterwards, you can also probably delete the "scopbin" folder in plugin's root - it contains one, now unused, .php file.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a User Role and give permission to only use Web Stories plugin? I want to create a new user role "Story Maker" with only the "Google Web Stories" plugin shown in the dashboard for the user to create and publish stories. I don't want the user to get access to any other thing other than the web stories plugin. I'm new to PHP and would appreciate it if you could give me the right snippet to add to the functions.php file. Thanks in advance.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modifying post_type_link hook messing up edit function for a custom post I'm using Wordpress as a headless CMS. I have several custom post types that are being consumed by a non-Wordpress application via WP's REST API. On the custom posts, I would like permalinks to the post to point to the appropriate location in the non-Wordpress application to view the data as it is being shown to users. I'm using the post_type_link hook for this and it works fine in all instances exception one. In this instance, I need to look up if a person is associated with a different custom post type. This works fine when generating the View link. That works fine. However, Edit link for the post now takes me to a screen with just the title and description field with data from a different custom post type. The URL for the Edit link is fine, correctly showing the ID the correct post and the correct custom post type. Here is the code that is causing this behavior in the post_type_link hook. Removing this code resolves the issue: function update_post_link( $url, $post ) { if ( \people\POST_TYPE == get_post_type( $post ) ) { $labId; $postId = get_the_ID(); $query = new \WP_Query( 'post_type=lc_labs' ); while ( $query->have_posts() ){ $query->the_post(); $id = get_the_ID(); $PIs = get_post_meta($id, 'principal_investigators', true); if (is_array($PIs) && in_array($postId, $PIs)) { $labId = $id; } } if (isset($labId)) { return get_home_url() . '/laboratories/view?id=' . $labId; } else { return get_home_url() . '/laboratories'; } } return $url; } add_filter( 'post_type_link', '\people\update_post_link', 10, 2 ); What's really confusing me is that this shouldn't matter! The post_type_link hook should only be affecting permalinks, so why is this even affecting the Edit link on these posts?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Plugin Icon does not work correctly When i click on the icon - nothing happens. Only 404 error appears. The menu is gone, i cant add new plugins. I don't know what the problem is?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gutenberg block not displaying prop values I created a simple Gutenberg block. When I use static values to display in both the editor and front-end it works but when I try to use dynamic values using props and attributes, after saving the post it does not show up in the front-end. Here's the code: attributes: { skyColor: {type: "string"}, grassColor: {type: "string"} }, edit: function (props) { function updateSkyColor(event) { props.setAtrributes({skyColor: event.target.value}) } return ( <div> <input type="text" placeholder="sky color" value={props.attributes.skyColor} onChange={updateSkyColor} /> </div> ) }, save: function (props) { return ( <p> <span className="skyColor">{props.attributes.skyColor}</span> </p> ) } })
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filtering image class at output I would expect this (added to functions.php) to add "no-shadow" to all image output from the media library... it does nothing. function jma_child_get_attachment_image_attributes( $attr, $attach ) { $shadowless_imgs = array(9204); //if(in_array($attach->ID, $shadowless_imgs)) $attr['class'] .= ' no-shadow'; return $attr; } add_filter( 'wp_get_attachment_image_attributes', 'jma_child_get_attachment_image_attributes', 10, 2 );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two pagination in one page without being synchronous How can I have two pagination without them being synchronous? so let's say I have <div class="block-a"> and <div class="block-b">, when I try to proceed to Block A's pagination result 2 which I get redirected to page/2 and then it displays the Block A's page 2 results, but when I scroll down to check Block B it is also showing the page 2 results. is it possible to have two pagination in one page without them being synchronous? when I go to Block A's page 2, Block B shouldn't display page 2 results. I'm a man of SEO and tracking traffic on my site, that's why I wouldn't go for AJAX solution.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom post type with custom taxonomies structure url not working archive of CPT I trying to adjust url structure for CPT(collections) and custom taxonomy(collection). To create full url like (page.com/collections/collection/cat/subcat I'm using 'rewrite' => array( 'slug' => 'collections/%collection%', ); But when I use this notation (/%collection%) archive page for /collections not working, it return 404. Is there any way to combine these two possibilities?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Translate Woocommerce tab I have added a new tab in Woocommerce but I can not find how to add translation to it (I am using WPML plugin) do anyone has an idea how to deal with that? I need translation of the content of title This is my code snippet : add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' ); function woo_new_product_tab( $tabs ) { // Adds the new tab $tabs['desc_tab'] = array( 'title' => __( 'TEXTTTT', 'woocommerce' ), 'callback' => 'woo_new_product_tab_content' ); return $tabs; } Thanks in advance
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Some data of one custom user profile is erased when I update another custom user profile I have some problems with custom user profil. I Created 2 différents user profiles : * *one is calld "particulier" *the other is called "entreprise" You can see the code below. The thing is : At the begining, all the fields are filled, for all the users for all users regardless of their profile. I go to the profile of a "particular" user. I modify a value of a field I update the user. and then, some of the fields become empty. These are fields for users whose profile is "entreprise". More specifically, these are fields that are pooled for all users belonging to the same company (I have specified the location of these fields or variables in the code). I really don't understand why these data are erased ... I really hope you can help me. I have been trying to find a solution for several days. Many many thanks for your help. the code is : <?php /* ---------------------------------------*/ /* FIRST CUSTOM USER PROFIL "particulier" */ /* ---------------------------------------*/ add_action( 'show_user_profile', 'extra_user_particulier_fields' ); add_action( 'edit_user_profile', 'extra_user_particulier_fields' ); function extra_user_particulier_fields( $user ) { global $lang, $langue; $user_id = $user->ID; $user1 = new WP_User( $user_id ); $user_role = array_shift($user1->roles); if ($user_role == 'administrator' ) return false; if ($user_role == 'membres_entreprise' ) return false; ?> <h3>Information membre particulier</h3> <?php if (current_user_can( 'manage_options' )) { $user_partinfo = get_userdata($user_id); $user_registered_part = $user_partinfo->user_registered; $last_name = $user_partinfo->last_name; $first_name = $user_partinfo->first_name; $user_email = $user_partinfo->user_email; ?><style> .user-url-wrap { display:none; } </style> <table class="form-table"> <tbody> <tr> <th>Civilité/Anrede* </th> <td><input class="regular-text" id="particulier_titre1" type="text" name="particulier_titre1" value="<?php echo esc_attr( get_the_author_meta( 'particulier_titre1', $user_id ) ); ?>" /></td> </tr> <tr> <th>Titre</th> <td><input class="regular-text" id="particulier_titre2" type="text" name="particulier_titre2" value="<?php echo esc_attr( get_the_author_meta( 'particulier_titre2', $user_id ) ); ?>" /></td> </tr> <tr> <tr> <th>Nom </th> <td> <?php echo esc_attr( get_the_author_meta( 'last_name', $user_id ) ); ?></td> </tr> <th>Prénom</th> <td><?php echo esc_attr( get_the_author_meta( 'first_name', $user_id ) ); ?></td> </tr> <tr> <th>Rue (partie 1)</th> <td><input class="regular-text" id="particulier_rue1" type="text" name="particulier_rue1" value="<?php echo esc_attr( get_the_author_meta( 'particulier_rue1', $user_id) ); ?>" /></td> </tr> <tr> <th>Code postal</th> <td><input class="regular-text" id="particulier_plz" type="text" name="particulier_plz" value="<?php echo esc_attr( get_the_author_meta( 'particulier_plz', $user_id ) ); ?>" /></td> </tr> <tr> <th>Ville</th> <td><input class="regular-text" id="particulier_ort" type="text" name="particulier_ort" value="<?php echo esc_attr( get_the_author_meta( 'particulier_ort', $user_id ) ); ?>" /></td> </tr> <tr> <th>Pays</th> <td><input class="regular-text" id="particulier_pays" type="text" name="particulier_pays" value="<?php echo esc_attr( get_the_author_meta( 'particulier_pays', $user_id ) ); ?>" /></td> </tr> <tr> <th>Téléphone</th> <td><input class="regular-text" id="particulier_telfix" type="text" name="particulier_telfix" value="<?php echo esc_attr( get_the_author_meta( 'particulier_telfix', $user_id ) ); ?>" /></td> </tr> <tr> <th>Téléphone mobile</th> <td><input class="regular-text" id="particulier_telmobile" type="text" name="particulier_telmobile" value="<?php echo esc_attr( get_the_author_meta( 'particulier_telmobile', $user_id ) ); ?>" /></td> </tr> <tr> <th>Société </th> <td><input class="regular-text" id="particulier_societe" type="text" name="particulier_societe" value="<?php echo esc_attr( get_the_author_meta( 'particulier_societe', $user_id ) ); ?>" /></td> </tr> </tbody> </table> <?php } ?> <?php } add_action( 'personal_options_update', 'save_extra_user_particulier_fields' ); add_action( 'edit_user_profile_update', 'save_extra_user_particulier_fields' ); function save_extra_user_particulier_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } update_user_meta( $user_id, 'particulier_titre1', $_POST['particulier_titre1'] ); update_user_meta( $user_id, 'particulier_titre2', $_POST['particulier_titre2'] ); update_user_meta( $user_id, 'particulier_rue1', $_POST['particulier_rue1'] ); update_user_meta( $user_id, 'particulier_plz', $_POST['particulier_plz'] ); update_user_meta( $user_id, 'particulier_ort', $_POST['particulier_ort'] ); update_user_meta( $user_id, 'particulier_pays', $_POST['particulier_pays'] ); update_user_meta( $user_id, 'particulier_telfix', $_POST['particulier_telfix'] ); update_user_meta( $user_id, 'particulier_telmobile', $_POST['particulier_telmobile'] ); update_user_meta( $user_id, 'particulier_societe', $_POST['particulier_societe'] ); } /* ---------------------------------------*/ /* SECOND CUSTOM USER PROFIL "entreprise" */ /* ---------------------------------------*/ add_action( 'show_user_profile', 'extra_user_entreprise_fields' ); add_action( 'edit_user_profile', 'extra_user_entreprise_fields' ); function extra_user_entreprise_fields( $user ) { global $lang,$isupp; /* permet l'affichage sur certain rôle seulement*/ $userent_id = $user->ID; $user1 = new WP_User( $userent_id ); $user_role = array_shift($user1->roles); if ($user_role == 'administrator' ) return false; if ($user_role == 'membres_particulier' ) return false; ?> <h3>Information membre entreprises</h3> <?php if (current_user_can( 'manage_options' )) { $user_entinfo = get_userdata($userent_id); $user_registered_ent = $user_entinfo->user_registered; ?> <table class="form-table"> <tbody> <tr> <th>Raison sociale</th> <td><?php echo esc_attr( get_the_author_meta( 'raisonsociale', $userent_id ) ); ?></td> <td><input style="visibility: hidden;" class="regular-text raisonsociale" type="text" name="raisonsociale_data" value="<?php echo esc_attr( get_the_author_meta( 'raisonsociale', $userent_id ) ); ?>"/> </td> </tr> <tr> <th>N° de membre de la société <br/> (Ajouté par le club)</th> <td><input class="regular-text" id="entreprise_nummembre" type="text" name="entreprise_nummembre" value="<?php echo esc_attr( get_the_author_meta( 'entreprise_nummembre', $userent_id ) ); ?>" /><br/> <i><?php echo 'La valeur ici sera modifiée automatiquement pour tous les membres de la même entreprise '; ?> </i> </td> </tr> <tr> <th>Civilité/Anrede </th> <td><input class="regular-text" id="anrede" type="text" name="anrede" value="<?php echo esc_attr( get_the_author_meta( 'anrede', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Titre</th> <td><input class="regular-text titel" type="text" name="titel" value="<?php echo esc_attr( get_the_author_meta( 'titel', $userent_id ) ); ?>" /></td> </tr> <tr> <th><i>Information nom / prénom </i></th> <td><i> <?php echo 'Le nom et le prénom sont à remplir dans la partie "Nom" du profil (au dessus). ' ?> </i> </td> </tr> <tr> <th>Nom </th> <td><?php echo esc_attr( get_the_author_meta( 'last_name', $userent_id ) ); ?></td> </tr> <tr> <th>Prénom</th> <td><?php echo esc_attr( get_the_author_meta( 'first_name', $userent_id ) ); ?></td> </tr> <tr> <th>Fonction</th> <td><input class="regular-text" id="fonction" type="text" name="fonction" value="<?php echo esc_attr( get_the_author_meta( 'fonction', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Service</th> <td><input class="regular-text" id="service" type="text" name="service" value="<?php echo esc_attr( get_the_author_meta( 'service', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Téléphone </th> <td><input class="regular-text" id="tel" type="text" name="tel" value="<?php echo esc_attr( get_the_author_meta( 'tel', $userent_id ) ); ?>" /></td> </tr> <tr> <th>E-mail</th> <td><input class="regular-text email" type="text" name="email" value="<?php echo esc_attr( get_the_author_meta( 'email', $userent_id ) ); ?>" /></td> </tr> <tr> <th> <p>Contact pour la facturation</p></th><td>--------------------------------</td></tr> <tr> <th>Civilité/Anrede </th> <td><input class="regular-text" id="contactanrede" type="text" name="contactanrede" value="<?php echo esc_attr( get_the_author_meta( 'contactanrede', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Titre</th> <td><input class="regular-text titel" type="text" name="contacttitel" value="<?php echo esc_attr( get_the_author_meta( 'contacttitel', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Nom </th> <td><input class="regular-text nachname" type="text" name="contactnachname" value="<?php echo esc_attr( get_the_author_meta( 'contactnachname', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Prénom</th> <td><input class="regular-text name" type="text" name="contactvorname" value="<?php echo esc_attr( get_the_author_meta( 'contactvorname', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Fonction</th> <td><input class="regular-text" id="contactfonction" type="text" name="contactfonction" value="<?php echo esc_attr( get_the_author_meta( 'contactfonction', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Service</th> <td><input class="regular-text" id="contactservice" type="text" name="contactservice" value="<?php echo esc_attr( get_the_author_meta( 'contactservice', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Téléphone </th> <td><input class="regular-text" id="contacttel" type="text" name="contacttel" value="<?php echo esc_attr( get_the_author_meta( 'contacttel', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Téléphone mobile</th> <td><input class="regular-text telmobile" type="text" name="contactmobile" value="<?php echo esc_attr( get_the_author_meta( 'contactmobile', $userent_id ) ); ?>" /></td> </tr> <tr> <th>E-mail</th> <td><input class="regular-text useremail_contactfact" type="text" name="contactemail" value="<?php echo esc_attr( get_the_author_meta( 'contactemail', $userent_id ) ); ?>" /></td> </tr> <tr> <th>Visibilité <br/> (Choisie par les membres)</th> <td> <?php echo esc_attr( get_the_author_meta( 'visibiliteent', $userent_id )); ?></td> <td><input style="visibility: hidden;" class="regular-text" id="visibiliteent" type="text" name="visibiliteent" value="<?php echo esc_attr( get_the_author_meta( 'visibiliteent', $userent_id ) ); ?>" /> </td> </tr> <tr> <th>Admission de l'entreprise par le club </th> <td> <input type="radio" name="admissionsociete_data" value="oui" id="oui" <?php echo ("oui" !== get_the_author_meta( 'admissionsociete', $userent_id )) ? "" : " checked=\"checked\"";?> /> <label class="oui" for="oui">oui</label> <br/> <input type="radio" name="admissionsociete_data" value="non" id="non" <?php echo ("non" !== get_the_author_meta( 'admissionsociete', $userent_id )) ? "" : " checked=\"checked\"";?> /> <label class="non" for="non">non</label> <br/> </td> </tr> </tbody> </table> <?php } ?> <?php } add_action( 'personal_options_update', 'save_extra_user_entreprise_fields' ); add_action( 'edit_user_profile_update', 'save_extra_user_entreprise_fields' ); function save_extra_user_entreprise_fields( $userent_id ) { if ( !current_user_can( 'edit_user', $userent_id ) ) { return false; } update_user_meta( $userent_id, 'raisonsociale', $_POST['raisonsociale_data'] ); update_user_meta( $userent_id, 'admissionsociete', $_POST['admissionsociete_data'] ); update_user_meta( $userent_id, 'anrede', $_POST['anrede'] ); update_user_meta( $userent_id, 'titel', $_POST['titel'] ); update_user_meta( $userent_id, 'fonction', $_POST['fonction'] ); update_user_meta( $userent_id, 'service', $_POST['service'] ); update_user_meta( $userent_id, 'tel', $_POST['tel'] ); update_user_meta( $userent_id, 'contactanrede', $_POST['contactanrede'] ); update_user_meta( $userent_id, 'contacttitel', $_POST['contacttitel'] ); update_user_meta( $userent_id, 'contactvorname', $_POST['contactvorname'] ); update_user_meta( $userent_id, 'contactnachname', $_POST['contactnachname'] ); update_user_meta( $userent_id, 'contactfonction', $_POST['contactfonction'] ); update_user_meta( $userent_id, 'contactservice', $_POST['contactservice'] ); update_user_meta( $userent_id, 'contacttel', $_POST['contacttel'] ); update_user_meta( $userent_id, 'contactmobile', $_POST['contactmobile'] ); update_user_meta( $userent_id, 'contactemail', $_POST['contactemail'] ); update_user_meta( $userent_id, 'typem', $_POST['typem'] ); //-------------------------------------------- //Loop to modify the field for all members //when there is a modification for one member // ALL THE DATA IN THIS LOOP ARE DELETED //-------------------------------------------- $raisonsociale = $_POST['raisonsociale_data'] ; $userscommun = new WP_User_Query( array( 'meta_key' => 'typem', 'orderby' => 'meta_value', 'order' => 'asc', 'meta_query' => array( array( 'key' => 'raisonsociale', 'value' => $raisonsociale, 'compare' => 'LIKE' ), ) ) ); $userfirmas = $userscommun->get_results(); foreach( $userfirmas as $userfirma ) { $useridcommun = $userfirma->ID; update_user_meta( $useridcommun, 'entreprise_nummembre', $_POST['entreprise_nummembre'] ); update_user_meta( $useridcommun, 'contactanrede', $_POST['contactanrede'] ); update_user_meta( $useridcommun, 'contacttitel', $_POST['contacttitel'] ); update_user_meta( $useridcommun, 'contactvorname', $_POST['contactvorname'] ); update_user_meta( $useridcommun, 'contactnachname', $_POST['contactnachname'] ); update_user_meta( $useridcommun, 'contactfonction', $_POST['contactfonction'] ); update_user_meta( $useridcommun, 'contactservice', $_POST['contactservice'] ); update_user_meta( $useridcommun, 'contacttel', $_POST['contacttel'] ); update_user_meta( $useridcommun, 'contactmobile', $_POST['contactmobile'] ); update_user_meta( $useridcommun, 'admissionsociete', $_POST['admissionsociete_data'] ); update_user_meta( $useridcommun, 'contactemail', $_POST['contactemail'] ); } } A: I found. All users have the same fields. When you add a custom field to a user, it is added to the others. So, in my loop below the text // ALL THE DATA IN THIS LOOP ARE DELETED I use the variable $SocialReasons = $_POST['socialreasons_data'] ; and for this one, it is not specified to use the variable $raisonsociale of the user being updated. Then,when I update a user "Particulier", $raisonsociale is thus empty and the data which results from it are NULL I added a test if (!empty($raisonsociale)) and it works ! The code below..... thanks for your help !! //Boucle pour modifier le champs chez tous les membres $raisonsociale = $_POST['raisonsociale_data'] ; if (!empty($raisonsociale)) { $userscommun = new WP_User_Query( array( 'meta_key' => 'typem', 'orderby' => 'meta_value', 'order' => 'asc', 'meta_query' => array( array( 'key' => 'raisonsociale', 'value' => $raisonsociale, 'compare' => 'LIKE' ), ) ) ); $userfirmas = $userscommun->get_results(); foreach( $userfirmas as $userfirma ) { $useridcommun = $userfirma->ID; update_user_meta( $useridcommun, 'entreprise_nummembre', $_POST['entreprise_nummembre'] ); update_user_meta( $useridcommun, 'logo_listeentreprise', sa_sanitize_chars($_POST['logo_listeent']) ); update_user_meta( $useridcommun, 'width_logoent', $_POST['width_logoent'] ); update_user_meta( $useridcommun, 'dateinscripsociete', $_POST['dateinscripsociete'] ); update_user_meta( $useridcommun, 'admissionsociete', $_POST['admissionsociete_data'] ); update_user_meta( $useridcommun, 'siegerue1', $_POST['siegerue1'] ); update_user_meta( $useridcommun, 'siegerue2', $_POST['siegerue2'] ); update_user_meta( $useridcommun, 'siegeplz', $_POST['siegeplz'] ); update_user_meta( $useridcommun, 'siegeville', $_POST['siegeville'] ); update_user_meta( $useridcommun, 'siegepays', $_POST['siegepays'] ); update_user_meta( $useridcommun, 'siteweb', $_POST['siteweb'] ); update_user_meta( $useridcommun, 'contactanrede', $_POST['contactanrede'] ); update_user_meta( $useridcommun, 'contacttitel', $_POST['contacttitel'] ); update_user_meta( $useridcommun, 'contactvorname', $_POST['contactvorname'] ); update_user_meta( $useridcommun, 'contactnachname', $_POST['contactnachname'] ); update_user_meta( $useridcommun, 'contactfonction', $_POST['contactfonction'] ); update_user_meta( $useridcommun, 'contactservice', $_POST['contactservice'] ); update_user_meta( $useridcommun, 'contacttel', $_POST['contacttel'] ); update_user_meta( $useridcommun, 'contactmobile', $_POST['contactmobile'] ); update_user_meta( $useridcommun, 'contactemail', $_POST['contactemail'] ); update_user_meta( $useridcommun, 'facturationservice', $_POST['facturationservice'] ); update_user_meta( $useridcommun, 'facturationrue1', $_POST['facturationrue1'] ); update_user_meta( $useridcommun, 'facturationrue2', $_POST['facturationrue2'] ); update_user_meta( $useridcommun, 'facturationplz', $_POST['facturationplz'] ); update_user_meta( $useridcommun, 'facturationville', $_POST['facturationville'] ); update_user_meta( $useridcommun, 'facturationpays', $_POST['facturationpays'] ); update_user_meta( $useridcommun, 'facturationpays', $_POST['facturationpays'] ); } } $oldadmissionent = get_the_author_meta( 'admissionent', $userent_id ); $newadmissionent = $_POST['admissionent']; if ($oldadmissionent !== $newadmissionent && $newadmissionent=='oui') { $user_ID = $userent_id; do_action( 'mail_admission', $user_ID); } update_user_meta( $userent_id, 'admissionent', $_POST['admissionent'] ); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle Wordpress account for terminated employee An employee was terminated and I want to know the best way to handle this individual's Wordpress/Woocommerce account. He was in the Shop Manager role and he mostly worked doing order fulfillment. I don't believe he was involved with producing CMS content like blogs, pages, or products. Other ecommerce systems I have used in the past have had options to "disable" an account so they can no longer login, but I don't see an option like that. As far as I can tell the best options I have are to 1) delete the user account permanently or 2) set the role to "No role for this site", but I'm not sure if these are the best options. I'm averse to installing a 3rd party plugin to add functionality. Any thoughts or best practices are welcome. A: In general, an account for an employee that has 'moved away' (for any number of reasons) should have their access privileges immediately downgraded. I would also change their password to prevent access. There are many instances of a former employee still having access, and doing improper things to the business computer systems. When an employee leaves (or is 'asked' to leave), their access to anything should be severely restricted, even if they are given a two-week transition before actually leaving. This is especially true for the employee that has administrative access to anything in the company computer systems.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically creating posts based on external JSON feed (asynchronously) I am currently trying to create a Wordpress plugin which create posts in the Wordpress database based on data from an external JSON API. As an example this NewsAPI feed could be used: https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=81143272da6c48d58bc38fe80dd110d6 The plugin I have written decodes the JSON data by using json_decode and loops through the article object in the JSON feed. Finally, the posts is being inserted programmatically using wp_insert_post: <?php /** * Plugin Name: Automatic News Feed Importer * Version: 1.0.0 */ function news_importer() { $url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=81143272da6c48d58bc38fe80dd110d6"; $response = wp_remote_get( $url ); $data = json_decode( wp_remote_retrieve_body( $response ) ); foreach( $data->articles as $news ) { $post_title = $news->title; $post_content = $news->content; $post_date = $news->publishedAt; $post = array( 'post_title' => $post_title, 'post_content' => $post_content, 'post_date' => $post_date, 'post_status' => 'publish', 'post_type' => 'post' ); wp_insert_post( $post ); } } My problem is that when the plugin is activated, no posts are creating and added to the database. When a new post is uploaded and appearing in the feed it has to be uploaded automatically (asynchronously). Any ideas on why this isn't working? A: By checking if the 'products' object exists in an if statement and looping through the objects (as in the code above), the function seems to be working: function json_to_post() { $response = wp_remote_get('https://dummyjson.com/products'); $json_data = wp_remote_retrieve_body($response); $data = json_decode($json_data, true); if (isset($data['products'])) { $products = $data['products']; foreach ($products as $post) { $title = $post['title']; $content = $post['description']; $new_post = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'post' ); wp_insert_post($new_post); } } } add_action('init', 'json_to_post'); A: There's a ready built plugin that does exactly this: https://wpgetapi.com/downloads/custom-post-import/
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to have a form page for logged-out users where values are stored persistently? I don´t know if this sounds a bit weird but I´m looking for a way to give unregistered users a form on which they can choose different options and depending on these values there should be content variations on other pages. And to make it one step more difficult: These values should be stored persistently beetween sessions? This could surely be achieved when you put additional custom fields on users profile pages, but I´m looking for a way (or at first an answer of the question if this is possible at all - because when this won´t work I don´t need to think about it any more ;-)). My first thought was to submit the form to a database and then the content variations should be shown dependig on a query with WHERE statement. But how should the database should know which entry belongs to which user? Would this be possible, if there is one unique value to identify the user? But that all sounds a bit strange. Instead I thought about saving the chosen values in browsers local storage. But I don´t know if they can be used to query content in a database. Or do I think in a totally false way and is there any other way to reach this goal (if it is possible at all)? Maybe I should give a real example so you could image what I want to achieve: Think about a form on which the users can choose their country and then on one corner of the other pages their flag should be shown. Or they choose their favourite sports and then their will be different content for tennis, football etc. A: You could always stored the selections in cookies or localStorage, then query the database via ajax calls on subsequent pages.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: YOAST slug does not take the custom permalink I have made So I wanted to create custom permalinks for my pages for an SEO project I’m working on. I can customise the permalink fine as I have downloaded a custom permalink plugin, but the YOAST plug-in I’m using has a different slug that it takes. For example, I want to change an existing post from: /sports-therapy-services/ To /services/sports-therapy/ So I can do this part fine. However, when I save changes, the slug that shows on YOAST is: sports-therapy-services It is replacing the slash with a dash. Is there a way so I can put in slashes into the YOAST slug? Or is there a way to make the YOAST slug match what I have put into the custom permalink? A: If the YOAST SEO plugin's slug is not taking the custom permalink that you have set, there are a few potential solutions: * *Check the settings: Go to the YOAST SEO settings and make sure that the custom permalink setting is enabled. *Disable pretty permalinks: Try disabling the "pretty permalinks" setting in WordPress and see if the custom permalink is honored. If it is, you can re-enable pretty permalinks and try a different solution. *Use the wpseo_slug filter: You can use the wpseo_slug filter to set the custom permalink for YOAST SEO. Add the following code snippet to your WordPress theme's functions.php file: add_filter( 'wpseo_slug', 'set_custom_permalink', 10, 1 ); function set_custom_permalink( $slug ) { // Check if we are on the post type that should use the custom permalink if ( get_post_type() === 'custom_post_type' ) { // Set the custom permalink $slug = 'custom-permalink'; } return $slug; } In this example, the code uses the wpseo_slug filter to set the custom permalink for the custom post type with the name "custom_post_type". Make sure to replace "custom-permalink" with the actual custom permalink that you want to set. Note: The wpseo_slug filter may not work in all cases, depending on your WordPress setup and other plugins that you have installed. If this solution doesn't work, you may need to try a different approach or reach out to the YOAST SEO support team for further assistance.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: delete_term is not working properly with add_action() delete_term is not working, I'm trying to delete term and after I deleted it, it'll also delete the similar term from different a taxonomy based on their slugs here's my code of the delete_term, so in the code below, when I deleted a term from movies_category taxonomy, it'll look/find for a similar slug from category (the default wordpress taxonomy for Posts), and then delete it also programmatically, but the code doesn't work on my end, I'm not sure where did I go wrong here. function delete_similar_term($term_id, $tt_id, $taxonomy, $deleted_term) { if( $deleted_term->taxonomy === 'movies_category' ) { $post_cat_term = get_term_by( 'slug', $deleted_term->slug, 'category' ); wp_delete_term( $post_cat_term->term_id, 'category' ); } } add_action( 'delete_term', 'delete_similar_term' , 10, 3 ); It's hard for me to debug this also because I can't see any errors, when I delete a term from my movies_category it will just highlight the term red and AJAX delete stops working. A: AFAIK, slug is unique. So $post_cat_term = get_term_by( 'slug', $deleted_term->slug, 'category' ); shouldn't return anything. Instead, you may try name. Also, delete_term callback gets 5 parameters, so it's better to adjust that accordingly. See if the following works: function delete_similar_term( $term_id, $tt_id, $taxonomy, $deleted_term, $object_ids ) { if( $deleted_term->taxonomy === 'movies_category' ) { $post_cat_term = get_term_by( 'name', $deleted_term->name, 'category' ); wp_delete_term( $post_cat_term->term_id, 'category' ); } } add_action( 'delete_term', 'delete_similar_term' , 10, 5 );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Fetch Custom Woocomerce filed data and check the data avialble in Wp-user table as nicname or username using function.php I write a code for add custom filed in checkout form as add affiliate code I want to match that custom field data with username. If custom field data match with any of the username the chcekout process move further other wise show error. I have write something but it's not working please help to solve this issue. Here is my code: // adding custom filed add_action('woocommerce_before_checkout_form', 'custom_checkout_field'); function custom_checkout_field($checkout) { echo '<div id="custom_checkout_field"><h2>' . __('Add Reference Affiliate Code') . '</h2>'; woocommerce_form_field('custom_field_name', array( 'type' => 'text', 'class' => array( 'my-field-class form-row-wide' ) , 'label' => __('Affiliate Code') , 'placeholder' => __('Affiliate Code') , ) , $checkout->get_value('custom_field_name')); echo '</div>'; } // Chcek custom filed data with username add_action('woocommerce_checkout_process', 'custom_checkout_field_validation'); function custom_checkout_field_validation() { if(username_exists( $_POST['custom_field_name'] )){ }else{ echo $_POST['custom_field_name']; wc_add_notice( __( $_POST['custom_field_name']), 'error' ); wc_add_notice( __( 'Lütfen Geçerli TC Kimlik No Girin.' ), 'error' ); } }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect posts to post editor page based on query string I want the posts that has the param edit to open the respective post editor page. This is because the admin bar is disabled on my site. So I need to make things easier to edit on my sites. I made the following code and inserted it in my plugin, but it's not working. I tried header("Location: ") instead of wp_safe_redirect, but that didn't work either. Any ideas? function myfunction() { if( isset( $_GET['edit'] ) && empty( $_GET['edit'] ) ) { wp_safe_redirect( admin_url( '/post.php?action=edit&post=' . get_the_ID() ) ); exit; } } A: Implementation notes: * *You need to use that function with an appropriate action hook. For example, template_redirect hook can be used here. *If you want URL to have ?edit, then empty check is not necessary, if you want URL to have something like ?edit=1, then use ! empty check. *Check and ignore if we are already on the admin pages. *Check and proceed if we are on a single post page. CODE: Following is an example code that'll work: function fyz_edit_redirect() { if( ! is_admin() // skip if we are on admin pages already && is_single() // apply only if it's a single post && isset( $_GET['edit'] ) && ! empty( $_GET['edit'] ) ) { wp_safe_redirect( admin_url( '/post.php?action=edit&post=' . get_the_ID() ) ); exit; } } add_action( 'template_redirect', 'fyz_edit_redirect' );
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Display the posts in a category with How can I adapt this html code to wordpress so I can do this? Please advise, best regards
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Complex Custom Loop with Includes The Problem I have a complex loop designed for showcasing my portfolio. Here is the criteria: * *Portfolio is powered by a custom post type called PORTFOLIO *Each post will be assigned a class of either 'landscape' or 'portrait' so that I can serve two different featured image sizes, and it's handled by dev logic, to add visual interest to the layout on each visit *Needs to paginate *I have included a graphic to illustrate what I am trying to achieve *I have variables (count, classes, customClass), that won't work inside includes unless they are added as global variables, which I know is poor practice Details & What I Have Tried The code below is working, but I know it is not optimal. I am seeking input on how to improve this to be more digestible. * *I understand that WP as of 5.5+ allows arguments within template files: https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/ – so when I try passing the variables like so: <?php get_template_part('template-parts/portfolio/portfolio', 'article', $count, $classes, $customClass); ?> it does not work. *I have the article element housed in an include template, as it is repurposed so often. Is this the correct/best approach? As noted above, I am also leveraging global variables which I would like to resolve, as I understand that is a no-no. This is my existing working loop. //----------------------- WORK PAGE LOOP <div class="portfolio grid__container"> <?php // IMG ORIENTATION VARIABLE $classes = array( 'landscape', 'portrait', ); $count = 0; $paged = (get_query_var('paged') > 1) ? get_query_var('paged') : 1; // ARGUMENTS $args = array( 'post_type' => 'portfolio', 'orderby' => 'rand', 'posts_per_page' => 99, 'paged' => $paged, 'paged' => 1, ); // LOOP QUERY $portfolio_loop = new WP_Query($args); ?> <div class="grid__row"> <?php // POWER THE LOOP while ($portfolio_loop->have_posts()): $portfolio_loop->the_post(); $count++; $customClass = $classes[$portfolio_loop->current_post%2]; ?> <!-- ROW 1 --> <?php if (in_array($count, array( 1,2,3 )) && $paged == 1) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--4"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 2 --> <?php elseif ($count <= 5 && $paged ==1 ) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--6" id="count-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 3 --> <?php elseif ($count <= 7 && $paged ==1 ) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--6"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 4 --> <?php elseif($count > 7 && $count < 12 && $paged == 1) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--4"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 5 --> <?php elseif($count > 11 && $count < 16 && $paged == 1) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--6" id="count-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 6 --> <?php elseif ($count > 15 && $paged == 1) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--4" id="count-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <?php endif; ?> <?php endwhile; ?> </div> <?php if ($portfolio_loop->max_num_pages > 1) { // check if the max number of pages is greater than 1 ?> <nav class="prev-next-posts"> <div class="prev-posts-link"> <?php echo get_next_posts_link( 'Older Articles', $portfolio_loop->max_num_pages ); // display older posts link ?> </div> <div class="next-posts-link"> <?php echo get_previous_posts_link( 'Newer Articles' ); // display newer posts link ?> </div> </nav> <?php } ?> <?php wp_reset_postdata(); ?> </div> This is my include file: <?php // GLOBAL VARIABLES global $count; global $classes; global $customClass; ?> <article id="post-<?php the_ID(); ?>" <?php post_class( $customClass . $count . ' m-b-20--sm m-b-75--lg'); ?>> <!-- COMING SOON --> <?php if(has_term('coming-soon', 'portfolio_status')) { ?> <?php get_template_part('template-parts/portfolio/portfolio', 'soon-badge'); ?> <?php } else { ?> <?php } ?> <!-- COMING SOON --> TEST: <?php echo $customClass; ?> <figure class="lazyload portfolio__image m-b-30--md m-b-20--sm"> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> <a href="<?php echo get_permalink(); ?>"> <?php } if ($customClass == "landscape") { echo the_post_thumbnail('portfolio-landscape'); } elseif ($customClass == "portrait") { echo the_post_thumbnail('portfolio-portrait'); } ?> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> </a> <?php } ?> </figure> <span class="block meta"><?php echo strip_tags(get_the_term_list( $post->ID, 'portfolio_categories', ' ',', ')); ?></span> <h2 class="h4 portfolio__title"> <span class="h4"> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> <a href="<?php echo get_permalink(); ?>"> <?php } ?> <?php the_title(); ?> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> </a> <?php } ?> </span> </h2> <div class="portfolio__excerpt m-t-10"><?php the_excerpt(); ?></div> <?php get_template_part('template-parts/portfolio/portfolio', 'tags'); ?> </article> Updated V2 Code * *Simplified conditional statements, not sure why I made them so complicated before. *Removed double instances of $paged and updated pagination to use the built in WordPress paginate_links snippet as noted by @Rajiii4u <div class="portfolio grid__container"> <?php // VARIABLE FOR IMG ORIENTATION $classes = array( 'landscape', 'portrait', ); // COUNT THE POSTS $count = 0; // PAGINATE $paged = (get_query_var('paged') > 1) ? get_query_var('paged') : 1; // ARGUMENTS $args = array( 'post_type' => 'portfolio', 'orderby' => 'rand', 'posts_per_page' => 18, 'paged' => $paged, ); // CUSTOM LOOP QUERY $portfolio_loop = new WP_Query($args); ?> <div class="grid__row"> <?php // POWER THE LOOP while ($portfolio_loop->have_posts()): $portfolio_loop->the_post(); $count++; $customClass = $classes[$portfolio_loop->current_post%2]; ?> <!-- ROW 1 // 1 TO 3 --> <?php if (in_array($count, array( 1,2,3 ))) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--4" id="counter-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 2 // LESS THAN OR EQUAL TO 5 --> <?php elseif ($count <= 5 ) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--6" id="counter-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 3 // LESS THAN OR EUQAL TO 7 --> <?php elseif ($count <= 7 ) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--6" id="counter-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 4 // LESS THAN OR EQUAL TO 12 --> <?php elseif($count <= 10 ) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--4" id="counter-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 5 --> <?php elseif($count <= 12 ) : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--6" id="counter-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <!-- ROW 6 --> <?php else : ?> <div class="grid__cell grid__cell__small--12 grid__cell__medium--4" id="counter-<?php echo $count; ?>"> <?php get_template_part('template-parts/portfolio/portfolio', 'article'); ?> </div> <?php endif; ?> <!-- END CONDITIONAL STATEMENTS--> <?php endwhile; ?> </div> <!-- GRID_ROW --> <?php wp_reset_postdata(); ?> <?php $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $portfolio_loop->max_num_pages ) ); ?> </div> A: Here are some optimization suggestions for the code: Refactor the code structure: Currently, the code is using multiple if statements to determine which template to display for each portfolio item. This can be refactored to use a single switch statement. This will make the code more readable and easier to maintain. Remove redundant code: The $paged variable is defined twice in the $args array, so it can be removed from the second definition. Improve pagination: Currently, the pagination is done by checking if $portfolio_loop->max_num_pages is greater than 1. A better approach would be to use the paginate_links() function provided by WordPress to display the pagination links. Remove unused variables: The $customClass variable is defined but not used, so it can be removed. Replace magic numbers with constants: Currently, the code is using magic numbers (e.g., 7, 11, 15, 99) to determine the layout for each portfolio item. These values should be replaced with constants to make the code more readable and easier to maintain. <?php // GLOBAL VARIABLES global $count; global $customClass; ?> <article id="post-<?php the_ID(); ?>" <?php post_class("$customClass $count m-b-20--sm m-b-75--lg"); ?>> <!-- COMING SOON --> <?php if(has_term('coming-soon', 'portfolio_status')) { get_template_part('template-parts/portfolio/portfolio', 'soon-badge'); } ?> <!-- COMING SOON --> TEST: <?php echo $customClass; ?> <figure class="lazyload portfolio__image m-b-30--md m-b-20--sm"> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> <a href="<?php echo get_permalink(); ?>"> <?php } if ($customClass === "landscape") { echo the_post_thumbnail('portfolio-landscape'); } elseif ($customClass === "portrait") { echo the_post_thumbnail('portfolio-portrait'); } ?> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> </a> <?php } ?> </figure> <span class="block meta"><?php echo strip_tags(get_the_term_list( $post->ID, 'portfolio_categories', ' ',', ')); ?></span> <h2 class="h4 portfolio__title"> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> <a href="<?php echo get_permalink(); ?>"> <?php } ?> <?php the_title(); ?> <?php if(!has_term('coming-soon', 'portfolio_status')) { ?> </a> <?php } ?> </h2> <div class="portfolio__excerpt m-t-10"><?php the_excerpt(); ?></div> <?php get_template_part('template-parts/portfolio/portfolio', 'tags'); ?> </article>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: website images getting corrupt automatically I have just migrated my website from hostinger to hostinger manually. And now when I upload any picture on my website the photos getting corrupted automatically. Although the picture was shown on my hosting but I am not able to use picture on my website. my website link - https://sablog.in/ A: It sounds like the issue with the pictures being corrupted is happening during the upload process. This could be due to a number of reasons, including incorrect file permissions, insufficient server resources, or a problem with the upload process itself. Here are a few steps you can take to try and resolve this issue: Check your server resources: Ensure that your server has enough resources (e.g. disk space, memory, CPU) to handle the upload of large files. Check file permissions: Make sure that the file permissions for your wp-content/uploads directory are set correctly, allowing WordPress to write to the directory. You can set the permissions to 755 or 777 depending on your server configuration. Use a different upload method: Try uploading the photos using a different method, such as FTP, to see if the issue persists. Deactivate plugins: If you have any plugins installed, try deactivating them one-by-one and uploading a photo each time to see if any of them are causing the issue. Check image compression: Make sure that the images are not being compressed during the upload process, which could cause them to become corrupted. If these steps don't resolve the issue, you may want to reach out to your hosting provider for further assistance, as the issue could be related to your server configuration. A: I had this before too, but in my case, the size of the pictures were messed up. Try to disable lazy load, this sometimes cause problems. Also do not only change the read and write permissions, but also the ownership of the files of your wordpress installation. chown www-data:www-data -R * # Let Apache be owner find . -type d -exec chmod 755 {} \; # Change directory permissions rwxr-xr-x find . -type f -exec chmod 644 {} \; # Change file permissions rw-r--r-- After the setup you should tighten the access rights, according to Hardening WordPress all files except for wp-content should be writable by your user account only. wp-content must be writable by www-data too. chown <username>:<username> -R * # Let your useraccount be owner chown www-data:www-data wp-content # Let apache be owner of wp-content
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I stop my WordPress database collecting transients such as RSS feeds in wp_options table? I ran a check on wp_options table and I found lots of unsolicited RSS content, which points to sites such as WordPress.org and WP Tavern. This content is taking 75% of space in my database. I am aware of a few SE questions about how to remove orphan transients that are not removed automatically, but I'd like to know if there is a way to prevent them from getting into my database in the first place. A Google search does not help. A: but I'd like to know if there is a way to prevent them from getting into my database in the first place. The only way to prevent expired transients ever being a thing is to never use them to begin with. When you create a transient an option is created with a particular name. Eventually that transients expiration date comes and it needs cleaning up, this can be automated and WordPress does this automatically. Your situation happens because that automation is either disabled or unable to run. Sadly, what you're asking for is the very thing you're trying to avoid, a clean up cron job of some sort. As for RSS feeds, you wouldn't want this. Not caching the result would lead to major performance losses. HTTP requests are some of the slowest and most expensive things you can do in WordPress. This can also have significant knock on effects on popular plugins that fetch news and other RSS feeds, as well as RSS widgets and RSS blocks. As an aside, if you have an object cache, WP will try to use it instead for transient storage, e.g. Redis or memcached. Redis/etc will auto-cleanup, and has its own expired garbage collection processes too. This becomes highly dependent on your server and software though, and you're essentially trading one set of problems for another. You should get a persistent object cache if you can, but because it's a big performance boost, not for transient cleanup.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sidebars panel in customizer I write a template and I want to create a panel like widgets panel for footer. I register some sidebar which represent the columns of the footer and I want to create a panel which contains section for each footer Column sidebar. I try to use wp_widget_area_customize_control but when i add a widgets, nothing be happen. I don't know if i should use another section class or what and what setting use. Can someone help me please? A: It sounds like you are trying to create a custom WordPress panel that will display your footer widget areas. To achieve this, you will need to create a custom section in your WordPress Customizer that will be responsible for displaying the widgets. You can use the WP_Customize_Section class to create your custom section, and the WP_Customize_Control class to create a custom control for your widgets. Here is a basic example of how you can create a custom section for your footer widgets: class Footer_Widgets_Section extends WP_Customize_Section { public $type = 'footer_widgets'; public function render_content() { // Your code to render the section content } } class Footer_Widgets_Control extends WP_Customize_Control { public $type = 'footer_widgets'; public function render_content() { // Your code to render the control content } } // Register your custom section and control add_action( 'customize_register', function ( $wp_customize ) { $wp_customize->add_section( new Footer_Widgets_Section( $wp_customize, 'footer_widgets', array( 'title' => __( 'Footer Widgets' ), 'priority' => 30, ) ) ); $wp_customize->add_setting( 'footer_widgets', array( 'default' => '', ) ); $wp_customize->add_control( new Footer_Widgets_Control( $wp_customize, 'footer_widgets', array( 'section' => 'footer_widgets', 'label' => __( 'Footer Widgets' ), ) ) ); } ); This is just a basic example to get you started. You will need to add more code to the render_content methods of both the section and control to actually display the widget areas and allow the user to add widgets to them.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Edit a page/post DB data? Hello fellow Wordpress users. I purchased a theme, and it has some content blocks ready to use. I enjoy the simplicity of this, but I cannot fine-tune the details of these blocks. I eventually found the low-level data for the page in the database (in the wp_posts table) and edited that. (This is the data you see when comparing revisions of a page in the admin dashboard.) So my question is this: Is there a plugin or a built-in way to directly edit the database data for a page (and perhaps its revisions)? I've done some searching, but haven't come up with a solution yet. Thanks! A: There is no built-in way to directly edit the database data for a page or its revisions in WordPress. However, you can achieve this by using a plugin such as WP-DB Manager, which provides a user-friendly interface for managing and editing your WordPress database. This plugin allows you to directly edit the database data for a page and its revisions, as well as perform other database management tasks like backing up, restoring, and optimizing your database.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: change div text and link for logged in users this question was already similar asked but I don't find a way to get it working without using a plugin. So basically I got a text on my homepage which says login, so it's a normal text which i want to change to "my account" if a user is logged in. Also then the link has to change. I thought about creating 2 divs and hide one via css wether a user is logged in or not but this seems pretty inefficient and non-responsive to me. I would like to do it on my own but since I'm pretty new to php, I don't know how to do it. Tnaks in advance A: You can use the session functionality in PHP to determine if a user is logged in or not. <?php session_start(); if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) { $link = '/my-account.php'; $text = 'My Account'; } else { $link = '/login.php'; $text = 'Login'; } ?> <a href="<?php echo $link; ?>"><?php echo $text; ?></a> A: So, firstly thanks for your answer. The mentioned code above didn't work out for me, smh It doesn't recognize me being logged in. Anyways I changed the if condition to the inbuilt logged_in check from wordpress/woocommerce and managed to fix it. So for everyone who is as desperate as I was, I will post the results <?php if(is_user_logged_in()) { $link = '/myaccount'; $text = 'My Account'; } else { $link = '/login'; $text = 'login'; } ?> <a href="<?php echo $link; ?>"><?php echo $text; ?></a> Use wp code snippets, create a shortcode, insert it and then style it via css :)
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ‘wp_site_health_scheduled_check’ Causes Failure Of Other Scripts I introduced a heartbeat monitoring system on all my websites late last year. The system involves using a wp-cron action to send a GET request to an API hosted by Better Uptime, triggered by crontab command (wp cron event run --due-now;) every thirty minutes. This works flawlessly on all my websites, except one where every week at exactly 20:30 GMT the heartbeat fails. I have been investigating this. You can see the pattern for yourself here: https://status.paragondrones.co.uk (open the ‘heartbeat’ section). Firstly, I checked with Better Uptime. They confirmed that they never received the relevant heartbeats. Secondly, I checked the wp-cron action timing (a known issue). That was fine. Thirdly, I checked whether the Termly plugin was the cause (another known problem). It wasn't. Turning my focus then to Wordpress, and after some lengthy troubleshooting, I discovered that: * *In 60% of cases, there was no crontab log. Probably because Wordpress was too busy to process the crontab command. *In 40% of cases, a crontab log existed but the heartbeat action was missing from it. Probably because Wordpress was too busy processing scripts because … *In 100% of cases, the wp-cron action wp_site_health_scheduled_check preceded the failure. Note: the wp_site_health_scheduled_check action is a standard feature of Wordpress since v5.2.0, one of only two wp-cron actions scheduled to run once per week. My initial thoughts were that the wp_site_health_scheduled_check script was timing out or trying to utilise too many server resources e.g. RAM, but comparing PHP Variables across three of my websites resulted in no discrepancies – all values were identical. Specifically, max_execution_time, and max_input_time were the same and set to a relatively generous 120 seconds, and memory_limit was set to a generous 768M. Of course, I could just disable the wp_site_health_scheduled_check action, but this only fixes the issue, not the underlying problem. I am at a loss now as to what to do or try next. * *I could try disabling the action, just to prove that it is the root cause, but that doesn’t fix anything. *Is there a way to log what wp_site_health_scheduled_check is doing, find out how long it is taking to execute? *Should I just arbitrarily increase the PHP limits to see whether that helps? *SiteGround, my hosting provider, has two ‘configurations’ of PHP, either ‘Standard’ or ‘Ultra Fast’. I’m not sure what the differences are but is it worthwhile downgrading to ‘Standard’ to see what happens? This is beyond my knowledge. Any advice/guidance would be warmly received. David.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Featured Image as Hero Background in Word Press I have the Author Cats theme in Word Press (kimcoxauthor.com). I had hoped they would add this feature for the book pages in a future update since I bought a lifetime license for all updates but it's been a few years and the last time I asked they said they didn't intend to do that and I should hire a developer if I wanted to change it. Since I can't afford that and have some coding experience, I have been trying to figure out how to fix it myself. I appreciate any help you can give me. Here's the problem: In the hero section of my home page, it has the option to use a background image, then there is a book cover and a description beside it. On the blog post page, which I don't use, the hero section lets you use the featured image as the background but doesn't have a book cover image on top of it (sample post page: https://kimcoxauthor.com/sample-3/). On the book page, it only allows you to use a background color which will be the same on all your book pages (book page: https://kimcoxauthor.com/books/all-this-time/). Note not all book covers look good on the same color. I want my book page hero sections to allow me to use the featured image as the background image. What have I tried so far? I mixed the codes for book page and some of post page together and it worked. It pulled the featured image, had a book cover, and had a description. The only problem is the book cover was off - too close to the top on my laptop and even worse on mobile view. I changed and added css (margin and padding in numerous places) to try to fix it to no avail. No matter what I did or changed, the cover stayed in the same spot. I was able to fix it well- enough for my laptop view by adding more description to the hero section, but the mobile version was still messed up, showing only about half of the book cover. I ended up changing it back to the background color. This is the php code to get the featured image as used in the post page: // featured image if (has_post_thumbnail()) { $full_featimg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full'); $featimg = $full_featimg[0]; } else { $get_default_featimg = get_field('default_featured_image','option'); $get_featimg_size = 'full'; // (thumbnail, medium, large, full or custom size) $featimg_array = wp_get_attachment_image_src($get_default_featimg, $get_featimg_size); $featimg = $featimg_array[0]; } ');">
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gravity Forms with Advanced Post Creation Add-On not updating ACF fields on custom taxonomy I've tried everything I can think of and read about. I cannot seem to figure out why this doesn't work, let alone get it to work. I have a Custom post type called Talk. That custom post type has a custom taxonomy (non-hierarchical) of Speaker. The taxonomy Speaker has three Advanced Custom Fields added to it: Institution, Phone, Email. A Gravity Form using the Advanced Post Creation add-on creates a Talk as a draft. The speaker name, institution, phone and email are all fields on that form. Below is the latest version of my attempts to have the Speaker ACF update after post creation. add_action( 'gform_advancedpostcreation_post_after_creation_2', 'after_post_creation', 10, 4 ); function after_post_creation( $post_id, $feed, $entry, $form ){ $spkr_inst = rgar( $entry, '3' ); $spkr_ph = rgar( $entry, '10' ); $spkr_em = rgar( $entry, '11' ); $talk_speakers = get_the_terms( $post_id, 'talk_speaker' ); foreach($talk_speakers as $talk_speaker) { $spkr_id = 'speaker_'.$talk_speaker->term_id; GFCommon::send_email( '[email protected]', '[email protected]','','','New Post', $spkr_id); // update_field( 'speaker_institution', $spkr_inst, 'speaker_'.$talk_speaker->term_id); // update_field( 'speaker_phone_number', $spkr_ph, 'speaker_'.$talk_speaker->term_id); // update_field( 'speaker_email_address', $spkr_em, 'speaker_'.$talk_speaker->term_id); } } The commented out update_field stuff NEVER happens, whether I'm using 'speaker_'.$talk_speaker->term_id or the above $spkr_id. But the test email sends, and has the correct $spkr_id value in the email body, speaker_112 ... I've read through these (but far be it from me to assume I missed nothing ...): https://www.advancedcustomfields.com/resources/update_field/#update-a-value-from-different-objects https://docs.gravityforms.com/gform_advancedpostcreation_post_after_creation/#examples A: Well. Thanks to this question: How to update custom taxonomy meta using ACF update_field() function or any other wordpress function I slowed down long enough to realize I typed the function name of my own dang custom taxonomy incorrectly when prefixing the term id ... should have been 'talk_speaker_'.$talk_speaker->term_id; not just speaker_ ... in short, what I have works, if I didn't make that mistake. Good night sleep and some coffee will do wonders. Final Code: add_action( 'gform_advancedpostcreation_post_after_creation_2', 'after_post_creation', 10, 4 ); function after_post_creation( $post_id, $feed, $entry, $form ){ $spkr_inst = rgar( $entry, '3' ); $spkr_ph = rgar( $entry, '10' ); $spkr_em = rgar( $entry, '11' ); $talk_speakers = get_the_terms( $post_id, 'talk_speaker' ); foreach($talk_speakers as $talk_speaker) { $spkr_id = 'talk_speaker_'.$talk_speaker->term_id; update_field( 'speaker_institution', $spkr_inst, $spkr_id); update_field( 'speaker_phone_number', $spkr_ph, $spkr_id); update_field( 'speaker_email_address', $spkr_em, $spkr_id); } } A: To resolve the issue with Gravity Forms and the Advanced Post Creation Add-On not updating ACF fields on a custom taxonomy, you can try adding the following code snippet to your WordPress theme's functions.php file: add_action( 'gform_post_create_post', 'update_custom_taxonomy_acf_fields', 10, 3 ); function update_custom_taxonomy_acf_fields( $post_id, $form, $entry ) { // Check if the custom taxonomy term is set in the Gravity Form entry $custom_taxonomy_term = rgar( $entry, 'custom_taxonomy_field_id' ); if ( ! $custom_taxonomy_term ) { return; } // Update the custom taxonomy term for the post wp_set_object_terms( $post_id, $custom_taxonomy_term, 'custom_taxonomy', false ); // Update the ACF field for the custom taxonomy term update_field( 'acf_field_name', $custom_taxonomy_term, $post_id ); } In this example, the code uses the gform_post_create_post action to hook into the Advanced Post Creation Add-On and update the custom taxonomy term and ACF field when a post is created. The code first checks if the custom taxonomy term is set in the Gravity Form entry, and if it is, it uses the wp_set_object_terms() function to update the custom taxonomy term for the post and the update_field() function from the Advanced Custom Fields plugin to update the ACF field. Note: Make sure to replace "custom_taxonomy_field_id" with the actual field ID for the custom taxonomy field in your Gravity Form, "custom_taxonomy" with the actual name of your custom taxonomy, and "acf_field_name" with the actual name of your ACF field.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress site down for my IP only after trying to implement .htaccess whitelist UPDATE: the problem seems to have solved itself now, about 24 hours later. It would still be useful to know what happened, though. My team and I have tried to make 2FA plugins work with WordPress a few times, but it never seems to work properly, and I end up removing the plugin. Today, I tried to use the approach given here, which provides code for implementing an IP whitelist by pasting the following code in: AuthUserFile /dev/null AuthGroupFile /dev/null AuthName "WordPress Admin Access Control" AuthType Basic <LIMIT GET> order deny,allow deny from all # whitelist Syed's IP address allow from xx.xx.xx.xxx # whitelist David's IP address allow from xx.xx.xx.xxx </LIMIT> I was logged in with WordPress at the time, and I edited the .htaccess file via FTP. Suddenly, I cannot access our website (www.csca.ca) at all from my own IP. I can access it over LTE or with a VPN, but not from my home IP. So I just reverted the .htaccess file to what it was before, but I'm still locked out. How can I undo this? .htaccess file before (and what it is again now) #Begin Really Simple Security <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTPS} !=on [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] </IfModule> #End Really Simple Security # BEGIN WordPress # The directives (lines) between `BEGIN WordPress` and `END WordPress` are # dynamically generated, and should only be modified via WordPress filters. # Any changes to the directives between these markers will be overwritten. <IfModule mod_rewrite.c> RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress .htaccess file after (My IP is replaced with 123... for privacy here, but I actually left my colleague's IP as xx.xx.xx.xxx, thinking I'd replace it later.) #Begin Really Simple Security <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTPS} !=on [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] </IfModule> #End Really Simple Security # BEGIN WordPress # The directives (lines) between `BEGIN WordPress` and `END WordPress` are # dynamically generated, and should only be modified via WordPress filters. # Any changes to the directives between these markers will be overwritten. <IfModule mod_rewrite.c> RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # Begin IP whitelist AuthUserFile /dev/null AuthGroupFile /dev/null AuthName "WordPress Admin Access Control" AuthType Basic <LIMIT GET> order deny,allow deny from all # whitelist Marks's IP address allow from 12.34.56.789 # whitelist David's IP address allow from xx.xx.xx.xxx </LIMIT> # End IP whitelist When I try to access the page from my IP, all I see is this: This site can’t be reached www.csca.ca took too long to respond. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_TIMED_OUT
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using custom pages for myaccount in woocommerce at the moment I'm trying to use custom pages for "my account/dashboard page". This worked fined since now as I use Shoplentor(woolentor) which lets me add widgets for that use. Anyways I'm struggling since when i'm on my order overview and try to view the order, it always shows me a fixed order overview wether its the order id 6557 or whatever. My structure atm is as following: /myaccount , myaccount/orders, myaccount/mascots, myaccount/address and logout This is the orders table: When I press on view I get on the default myaccount page set in woocommerce settings. This consists only of the order details widget of woolentor. So my Problem at the moment is, that it uses a fixed order, which I can't understand. It doesn't show they order of they given order id as example: https://www.xdaysleft-wear.com/accounts/view-order/6267/ I'm using the default woocommerce endpoints. Hope someone can help me bc this drives me crazy.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show success message on comment submit when email and name is not required field As you know in WordPress when you select "author must fill out name and email" and the user submit a comment it shows "is awaiting moderation". But when name and email is not required there is no way to show he user that the comment is received. Can you help me solve this problem? I want to show the user a message that the comment is submitted and will be published after admin approval. I think about 2 ways: * *make name and email required with above setting but with some codes in fact make it unrequired to be able to show is awaiting moderation again. *Use some codes to show successful comment submission. I have searched a lot but I couldn't find a way that works for me. Can you help me?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable "Quick edit" for roles in WP dashboard How can you disable the "quick edit" link in posts in WP dashboard for roles with following conditions: * *The "Delete" ability shall stay *the "View" post ability shall stay *The "Edit" ability shall be removed I tried this code in functions.php: if ( current_user_can( 'manage_options' ) ) { } else { add_filter( 'post_row_actions', 'remove_quick_edit', 10, 1 ); } But this code prevents you also from deleting the post. The DELETE link (delete to wastebasket) shall be preserved. Then, I tried this code in functions.php: function remove_quick_edit( $actions ) { unset( $actions['inline hide-if-no-js'] ); return $actions; } if ( ! current_user_can( 'manage_options' ) ) { add_filter( 'post_row_actions', 'remove_quick_edit', 10, 1 ); } But this code enables the EDIT link. I refer to this post: Disable "quick edit" only for non admin in functions.php A: I hope you need to disable "Edit" and "Quick Edit" for non-admin roles. So you can modify your code as follows function remove_quick_edit( $actions ) { unset($actions['edit']); unset($actions['inline hide-if-no-js']); return $actions; } if ( ! current_user_can('manage_options') ) { add_filter('post_row_actions','remove_quick_edit',10,1); }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to make content as required in custom post type? I created custom post type Testimonials and made the title required using the code in this link: Require title for pages Now I applied the code in order to make the content required, and it works fine. Just when I click Publish button and editor is empty, an alert message appears at the top of the screen that the content is required. But here is the problem: when I enter some content and click Publish button, the alert message displayed again. Here is the used code: function force_testimonials_post_content_init() { wp_enqueue_script('jquery'); } function force_testimonials_post_content() { if ( get_post_type( get_the_ID() ) == 'testimonials' ) { echo "<script type='text/javascript'>\n"; echo " jQuery('#publish').click(function() { var contentvar = jQuery('[id^=\"postdivrich\"]') .find('.mce-container-body'); if (contentvar.val().length < 1) { jQuery('[id^=\"postdivrich\"]').css('background', '#fff3cd'); setTimeout(\"jQuery('#ajax-loading').css('visibility', 'hidden');\", 100); alert('TESTIMONIAL POST CONTENT IS REQUIRED'); setTimeout(\"jQuery('#publish').removeClass('button-primary-disabled');\", 100); return false; } }); "; echo "</script>\n"; } } add_action('admin_init', 'force_testimonials_post_content_init'); add_action('edit_form_advanced', 'force_testimonials_post_content'); // Add this row below to get the same functionality for page creations. add_action('edit_page_form', 'force_testimonials_post_content'); A: the content_save_pre filter. It checks the post type of the current post and ensures that the content field is not empty. If the content field is empty, the function calls wp_die() to display an error message and stop the post from being saved. Note: Make sure to replace "custom_post_type" with the actual name of your custom post type. Also, you can modify the error message to fit your needs. add_filter( 'content_save_pre', 'validate_custom_post_type_content' ); function validate_custom_post_type_content( $content ) { global $post; if ( 'custom_post_type' === $post->post_type && empty( $content ) ) { wp_die( __( 'The content field is required for this custom post type. Please enter some content and try again.' ) ); } return $content; }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A better way of getting draft posts that has a particular post meta using get_posts function I'm developing a simple WordPress plugin as part of my WordPress learning. It's about bulk post approval. The full plugin code is given in this question: Bulk post approval and publishing doesn't work. The plugin works the way I want it to, but I'm now trying to improve it. For example, the following function is part of the plugin code: function karma_get_pre_publish_posts() { // get all draft posts with 'approve' custom field set to 'pre-publish' $args = array( 'post_type' => 'post', 'post_status' => 'draft' ); $approval_posts = array(); $draft_posts = get_posts( $args ); foreach ( $draft_posts as $post ) { if( get_post_meta( $post->ID, 'approve', true ) == 'pre-publish' ) { $approval_posts[] = $post; } } return $approval_posts; } It gets all the draft posts using get_posts function, and then checks for all the posts that has post meta approve set to 'pre-publish' using get_post_meta function. The function works, but I was thinking: if I have many such posts, say 100, then the code will basically run get_post_meta function 100 times. I'm assuming WordPress runs SQL queries in the background every time I use get_post_meta function. This doesn't look very efficient. I can probably run a single SQL join query like this post to get all the necessary post data, but I'm wondering if there is a more standard way of doing the same in WordPress. Any suggestions? Any related documentation link would be helpful too. A: You can use the post meta arguments that get_posts function already supports. So, there is no need to use get_post_meta function in a PHP loop. For your use case, post meta related arguments can be used in one of the two possible ways: * *Either using meta_key, meta_value, meta_compare arguments; *Or, using the meta_query argument which supports an array of different post meta checks and hence is more powerful. Using any of these methods returns all the necessary post data in one go. Method-1: The following example uses meta_key, meta_value, meta_compare arguments to achieve what you want: function karma_get_pre_publish_posts() { $args = array( 'post_type' => 'post', 'post_status' => 'draft', 'meta_key' => 'approve', 'meta_value' => 'pre-publish', 'meta_compare' => '=' ); return get_posts( $args ); } Method-2: The meta_query argument on the other hand requires an array of one or more argument arrays to query the posts with related post meta. Like this: function karma_get_pre_publish_posts() { // Yes, $meta_query argument has to be coded as an array of arrays. $meta_query = array( array( 'key' => 'approve', 'value' => 'pre-publish', 'compare' => '=' ) ); $args = array( 'post_type' => 'post', 'post_status' => 'draft', 'meta_query' => $meta_query ); return get_posts( $args ); } Further reading: * *Post meta related arguments (or parameters) of the get_posts function come from the parse_query method of WP_Query class. You may check the parse_query method documentation for more details. *Also, since the internal implementation related to post meta arguments is using the WP_Meta_Query class, you will also find some details in WP_Meta_Query class and WP_Meta_query constructor documentations. There are user contributed examples in these documentations with more advanced use cases, including multiple post meta comparisons in a single query.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Disable - Post search field - for non-admin roles in WP dashboard How can you disable the post search field "Search posts" - for non-admin roles in WP dashboard? Image attached: In my case, the non-admin role is a customer. The customer cannot and must not edit or delete any further posts which belong to other parties. Those posts the customer can view on pages as a common viewer. It's a customer. So I am asking why to show up that search field. I want to disable it. (Example: if you advertise a flower vase, do you would then want to search for flower vases from others? Maybe some want it - but I don't want to offer that feature) (Incidental things not relevant to answering the question: BTW, in case someone is asking: I cannot assign the common WP customer role because it does not meet the requirements. BTW, The customer is eligible to delete and view his post. Editing the own posts is possible with Elementor but not with the common WP link) Attempts: I tried 4 code snippets from the plugin "Code Snippets" by WPCode, but the search field "Search posts" in WP dashboard (posts) for non-admin roles stays! // Prevent search queries add_action( 'parse_query', function ( $query, $error = true ) { if ( is_search() && ! is_admin() ) { $query->is_search = false; $query->query_vars['s'] = false; $query->query['s'] = false; if ( true === $error ) { $query->is_404 = true; } } }, 15, 2 ); // Remove the Search Widget add_action( 'widgets_init', function () { unregister_widget( 'WP_Widget_Search' ); }); // Remove the search form add_filter( 'get_search_form', '__return_empty_string', 999 ); // Remove the core search block add_action( 'init', function () { if ( ! function_exists( 'unregister_block_type' ) || ! class_exists( 'WP_Block_Type_Registry' ) ) { return; } $block = 'core/search'; if ( WP_Block_Type_Registry::get_instance()->is_registered( $block ) ) { unregister_block_type( $block ); } }); A: There is no straight forward documented way of removing the search box in the admin panel's Post dashboard (wp-admin/edit.php). However, it's still possible by extending WP_Posts_List_Table class. Additionally, it makes sense that if you remove the search box, you'd also like to disable the search capability all together (based on your requirement). In that case, you may redirect any search request to the default wp-admin/edit.php page. That'll effectively disable any manual search attempts. Following is a fully functional example plugin code that demonstrates how this can be implemented: <?php /** * Plugin Name: @fayaz.dev Remove post search in dashboard * Description: Remove post search option in wp-admin/edit.php for users who don't have the capability to edit other's posts. * Author: Fayaz Ahmed * Version: 1.0.0 * Author URI: https://fayaz.dev/ **/ namespace Fayaz\dev; function init_search_box_removal() { if( is_admin() && ! wp_doing_ajax() && ! current_user_can( 'edit_others_posts' ) ) { // disable search capability if( isset( $_REQUEST['s'] ) ) { wp_safe_redirect( admin_url( 'edit.php' ) ); exit; } // remove the search box add_filter( 'wp_list_table_class_name', '\Fayaz\dev\define_wp_posts_list_table', 10, 2 ); } } add_action( 'set_current_user', '\Fayaz\dev\init_search_box_removal' ); function define_wp_posts_list_table( $class_name, $args ) { if( $class_name === 'WP_Posts_List_Table' ) { class WP_Posts_List_Table_Search extends \WP_Posts_List_Table { // this just overrides WP_List_Table::search_box() method. // the overriding function here does nothing, // hence it effectively removes the search box public function search_box( $text, $input_id ) {} } return '\Fayaz\dev\WP_Posts_List_Table_Search'; } return $class_name; }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Run PHPMailer function after ajax function completes that adds row to custom table Is there any way of calling a separate (php) function to send an email after ajax success? Code below works fine and as intended (cropped some bits out for brevity...) what I am looking to do is to call the PHPMailer part after the ajax function is complete due to the length of time its taking and don't want it to be so slow on the client side. Is there a function that I can use to watch the messages custom table for updates and to send an email based on the updated row? Apologies if there is something obvious I have been struggling to figure out how to word it! $wpdb->insert('messages', array( 'sender_id' => $sender_id, 'recipient_id' => $recipient_id, 'listing_id' => $listing_id, 'conversation_id' => $conversation_id, 'message' => $message, 'message_date' => date("d-m-Y"), 'message_time' => date("H:i a"), 'message_status' => 'unread' )); //echoes out response //variables for email use //Create a new PHPMailer instance $mail = new PHPMailer; $mail->SMTPDebug = 0; // Enable verbose debug output //SMTP settings start $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'localhost'; // Specify main and backup SMTP servers $mail->SMTPAuth = false; // Enable SMTP authentication $mail->Username = ''; // SMTP username $mail->Password = ''; // SMTP password $mail->SMTPAutoTLS = false; $mail->SMTPSecure = false; // Enable TLS encryption, `ssl` also accepted $mail->Port = 25; //Sender $mail->setFrom('[email protected]', 'Cranxs'); //Receiver $mail->addAddress($recipient_email); //Email Subject & Body $mail->Subject = 'You\'ve got a new message'; //Form Fields $mail->Body = $email_body; $mail->isHTML(true); // Set email format to HTML //Send the message, check for errors if (!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invalid login email notification for password-protected category Does vanilla WordPress (no related plugins installed) supports sending email notification or logging for invalid login on password-protected category? After reading the related documemt, I found only site-wide invalid login has such feature. Is it true that this feature is not present in a given category for vanilla WordPress? Thanks!
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: src="https://dns.firstblackphase.com/scripts/start.js" always this message appeared in my WordPress site https://prnt.sc/MPFNisaNmFQq https://prnt.sc/ADcQ8a5VbzKi https://prnt.sc/qN65SdKELtmS https://prnt.sc/DfB7XLarovbo could you please help me to fix this problem A: Looks like your site has been compromised (or possibly your computer if its not just happening on your site?) - can you access the admin area? If so I would recommend getting a plugin such as Wordfence which can help you to locate and remove any affected code and files?
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace the custom post type permalink I am quite new to wordpress and I'd like to know what I am doing wrong here: I've created a custom post type, let's say, custom_post_type_jobs. And I have a page which is called jobs. When I create a custom post type post, it has a permalink like this: .../custom_post_type_jobs/post-title. Since I have a shortcode on the page "jobs", which renders some stuff, I would like to render the posts there and when clicking them I want a structure as follows: /jobs/post-title. Am I missing here something? When creating the custom post type, I gave it the args: 'rewrites' => array( 'slug' => 'jobs' ), A: Wow, I just realized: the argument 'rewrites' was wrong. It's rewrite. Thank you guys anyway. A: To replace the permalink structure for a custom post type in WordPress, you can use the following code snippet in your theme's functions.php file: add_filter( 'post_type_link', 'replace_custom_post_type_permalink', 10, 4 ); function replace_custom_post_type_permalink( $post_link, $post, $leavename, $sample ) { if ( 'custom_post_type' === $post->post_type ) { $slug = 'custom-post-type'; $post_link = str_replace( '%' . $post->post_type . '%', $slug, $post_link ); } return $post_link; } In this example, the custom post type's permalink structure is defined using a custom placeholder, %custom_post_type%, in the permalink settings. The code replaces the placeholder with a custom string, custom-post-type, in the permalink for each post of this custom post type. Note: Make sure to replace "custom_post_type" with the actual name of your custom post type and "custom-post-type" with the desired permalink structure.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I modify the error code array used by "shake_error_codes" filter? I have a plugin with a registration_errors filter to prevent users from using a .gov email address. I have this code in the "registration_errors" filter function: $errors->add( 'gov_email', 'Please provide a private email address. not an official work email address.'); } I want to shake the login form when the error is encountered so I added this to my plugin: $shake_error_codes = array( 'empty_password', 'empty_email', 'invalid_email', 'invalidcombo', 'empty_username', 'invalid_username', 'incorrect_password', 'retrieve_password_email_failure', 'gov_email' ); add_filter( 'shake_error_codes', $shake_error_codes ); Note the gov_email at the end of the array in the code above to try to add the custom error code. Not only does this not work, but the form no longer shakes for other errors, either. Also tried this: add_filter( 'shake_error_codes', 'custom_add_error_code'); function custom_add_error_code($error_code) { return array_push($error_code, 'gov_email'); } This did not work, either. A: OK, my php is a little rusty. Doing a "return" on an array_push does not return the array. So had to change my add_filter to: add_filter( 'shake_error_codes', 'custom_add_error_code'); function custom_add_error_code($error_code) { array_push($error_code, 'gov_email'); return $error_code; }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I replace the values in WP_Term? WP_Term outputs: WP_Term Object ( [term_id] => 3 [name] => Public [slug] => public [term_group] => 0 [term_taxonomy_id] => 3 [taxonomy] => category [description] => [parent] => 0 [count] => 10 [filter] => raw ) What is the best way to replace the values for [name] => Public or slug] => public dynamically? Is array_replace the best option? The objective is rather than use unset( $terms[$key] ); for example, I'd like to replace/rename the values in the array. A: To replace values in a WP_Term object, you can modify its properties directly. For example: $term = get_term( $term_id, $taxonomy ); if ( ! empty( $term ) && ! is_wp_error( $term ) ) { $term->name = 'New Term Name'; $term->slug = 'new-term-slug'; $term->description = 'New Term Description'; } In this example, the get_term() function is used to retrieve a WP_Term object based on the term ID and taxonomy. If the term is found and is not an error, its properties name, slug, and description are updated with new values. Note that after updating the properties, you need to use the wp_update_term() function to persist the changes in the database: $update_result = wp_update_term( $term->term_id, $taxonomy, array( 'name' => $term->name, 'slug' => $term->slug, 'description' => $term->description, ) ); if ( is_wp_error( $update_result ) ) { // error updating term } else { // term updated successfully }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sort posts alphabetically based on a specific parent category I'm building out an index page of posts that are grouped under multiple categories, but those categories are all under the same umbrella parent category. I'd like to have these posts displayed alphabetically by default. I've found functions that work to change the post order globally on my site, but I'd like to find a function that works to ONLY sort posts alphabetically based on either the post ID of this index page or the parent category ID. I'm using a Divi child theme if that matters for anything. A: You can use the following code snippet to sort posts alphabetically based on a specific parent category in WordPress: <?php $parent_cat = 'Parent Category Name'; $parent_cat_id = get_cat_ID($parent_cat); $args = array( 'category__in' => array($parent_cat_id), 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1 ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); the_title(); echo '<br>'; } wp_reset_postdata(); } else { // no posts found } ?> In the code, replace "Parent Category Name" with the actual name of the parent category you want to sort posts from. The code will retrieve all the posts under this category, sort them alphabetically based on the post title, and display the title of each post. A: You can use the pre_get_posts action hook to modify the query that retrieves the posts, and sort them alphabetically based on a specific parent category. Here's an example: function sort_posts_alphabetically_by_parent_category( $query ) { if ( is_admin() || ! $query->is_main_query() ) { return; } if ( is_category( 'your-parent-category-slug' ) ) { $query->set( 'orderby', 'title' ); $query->set( 'order', 'ASC' ); } } add_action( 'pre_get_posts', 'sort_posts_alphabetically_by_parent_category' ); Replace 'your-parent-category-slug' with the actual slug of your parent category. This function will sort the posts alphabetically based on their title, only when the parent category archive page is being displayed.
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is WordPress wrapping search for users that looks like integers with asterisks and how do I fix it? I've got a custom meta field for users called "user_ein". It looks like an integer but is a string of number and it can start with the number "0". I have the following code in a custom plugin so users can be searched on this number: function search_by_user_ein( $query ) { if ( ! is_admin() || ! $query->query_vars['search'] ) { return $query; } global $wpdb; $search = trim( $query->query_vars['search'] ); // Uncomment next line to get search working on user_ein field // $search = trim( $search, '*' ); $search = '%' . $wpdb->esc_like( $search ) . '%'; $query->query_from .= " LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb->usermeta}.user_id"; $query->query_where .= $wpdb->prepare( " OR ({$wpdb->usermeta}.meta_key = 'user_ein' AND {$wpdb->usermeta}.meta_value LIKE %s)", $search ); return $query; } add_filter( 'pre_user_query', 'search_by_user_ein' ); This didn't work. If I put in "552398" into the search field, nothing was returned even though there is a user with the user_ein. After some head scraching, I dumped out the query and noticed that it was searching on *552398*. The search term was getting surrounded by asterisks. To fix the problem, I added this code in after getting the search term from the $query object: $search = trim( $search, '*' ); Things seem to work perfectly now but I'm worried there might be some unintended consequences. Is there a better fix than this? A: The search term was getting surrounded by asterisks. Yes, and they are wildcard characters, and in the case of the Users list table at wp-admin/users.php, those asterisks are being added by wp-admin/includes/class-wp-users-list-table.php (see source on GitHub for WordPress v6.1), so that a LIKE '%<keyword>%' query is performed by default. So to fix the issue, yes, I'd also use trim( $search, '*' ). But you can also use the raw search keyword, e.g. using $_REQUEST['s'].
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching for a custom meta from user.php in the admin I am trying to extend the standard user search to 1 specific custom usermeta. I am following the great answer provided in this question. I am still not able to get any result when I search for this custom meta (your_game_guid) value. Here is my function.php code: add_action('pre_user_query','mxbs_extend_user_search'); function mxbs_extend_user_search( $u_query ){ if ( $u_query->query_vars['search'] ){ $search_query = trim( $u_query->query_vars['search'], '*' ); if ( $_REQUEST['s'] == $search_query ){ global $wpdb; if (!isset($_GET['s'])){ return; }else{ $queryArg = $u_query->query_vars[ 'search' ]; } $count = $wpdb->get_var("SELECT COUNT(*) as nbr FROM {$wpdb->usermeta} WHERE {$wpdb->usermeta}.meta_key='your_game_guid' AND {$wpdb->usermeta}.meta_value = '$queryArg'"); if($count >= 1 && !is_null($u_query->search_term)){ $search_meta = $wpdb->prepare("ID IN ( SELECT user_id FROM {$wpdb->usermeta} WHERE {$wpdb->usermeta}.meta_key='your_game_guid' AND {$wpdb->usermeta}.meta_value LIKE '%s' ))", $queryArg); $u_query->query_where = str_replace( 'WHERE 1=1 AND (', "WHERE 1=1 AND ($search_meta OR ", $u_query->query_where ); } } } }
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute a shortcode within a custom field? I am using a plugin that generates a shortcode to display files from a Dropbox folder. I need to display the shortcode on a specific page, but it will be different for each user. Therefore I have created a custom field for each user, called 'view_files_shortcode'. I thought I could then call this user custom field on the page, and it would display whatever was set for each user. However it just displays the actual shortcode. Currently I am using this: <?php if ( is_user_logged_in() ) { $userid = get_current_user_id(); get_userdata( $userid ); get_field('view_files_shortcode', 'user_'. $userid );}?> <?php the_field('view_files_shortcode', 'user_'. $userid ); ?> Can anyone tell me how to make the shortcode execute? Thank you. A: Using the_field(); will just return the content of that field (guessing it's just text field?). <?php if (is_user_logged_in()) { $userid = get_current_user_id(); get_userdata($userid); $shortcode = get_field('view_files_shortcode', 'user_' . $userid); } ?> <?php echo do_shortcode($shortcode); ?>
{ "language": "en", "url": "https://wordpress.stackexchange.com/questions/413575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }