INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Post meta data not showing in frontend, until hitting 'update' button I try to insert around 2000 video-posts into WP. There is a custom field in the theme for the video-url, so I add the video-url to the post meta data with the corresponding field name. ACF seems not to be used by this theme (Edge, Journo). This meta data shows up correctly in that field in the backend, however not in the frontend until I hit the update button for every post. After hitting the update button, everything works perfectly. I tried so far: * wp_insert_post with a postarr containing 'meta_input' * wp_insert_post followed by add_post_meta * additional update_post_meta * additional wp_update_post * additional update_field * different versions of creating the post as a draft and then use wp_publish_post at different times Does anyone know which functions excactly are triggered by the update button? Or other ideas? Thanks in advance!
Thanks for your answers! Maybe I was a bit unclear, but I don't use ACF, it is just a field that comes with the theme. However, this question and answers helped to find the problem: < My WP metadata table entry was incomplete after creating a post programatically, the theme required another field. Saving the post again through the UI fixed that. Using a plugin to display the meta data I compared the post's meta data after inserting the post and after hitting the update button, so I identified the missing value in the meta data..! Hope this helps also for others with a similar issue!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, post meta, wp insert post, wp update post" }
Change register form action url I have 2 registration forms, default one on `/wp-login.php?action=register` for "recruiter" users, other one on `/wp-login.php?action=register&type=candidat` for "candidates" users My problem is that on candidate form, the form tag still has `/wp-login.php?action=register` as the action URL, and I want it to be `/wp-login.php?action=register&type=candidat` I tried updating wp-login.php file but if I update Wordpress in the future, my code will be overwritten I've tried other topics recommanding to use 'register_url' hook but it doesn't seem to work
You could do something like this: <?php add_action( 'register_form', function() { $get_type = filter_input( INPUT_GET, 'type', FILTER_SANITIZE_STRING ); if ( ! $get_type ) { return; } ?> <input type="hidden" name="type" value="<?php echo esc_attr( $get_type ); ?>" /> <?php }); This will add the `type` parameter as a hidden field on the form if it is set in the GET query string.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "login, urls, forms, user registration" }
I need use is_single in functions.php I need to use validation is_single('wordpress') in file functions.php. But the function is_single() does not work in the file functions.php. What can I do so that I can use is_single() in file functions.php? If more, then: I'm doing a check, its single page or not. And for single page I am set custom function.. Please help me someone.
`is_single` most likely only works inside of The Loop, and `functions.php` loads before you're in The Loop. You could try something like this: add_action( 'wp_head', function(){ var_dump(is_single()); }); And now you see that `is_single()` returns `true`. EDIT: I was probably off for suggesting it only works inside The Loop, but there's definitely better places for `is_single` than in `functions.php`, and if you're checking the "singleness" of a page, wait until you're in the request proper, or the template, to use it.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "conditional tags" }
Optimized PHP & Wordpress settings for speed/performance? I have a big site with several plugins that take up memory, a lot of requests to the server, etc. I've maxxed out my hosting to help account for this, but are there optimum PHP and Wordpress settings for big heavy site, or just optimum PHP base settings for Wordpress period. Here are my current settings: allow_url_fopen = Disabled allow_url_include = Disabled display_errors = Enabled enable_dl = Disabled file_uploads = Enabled max_execution_time = 600 max_input_time = 400 max_input_vars = 10000 memory_limit = 128M session.save_path = (blank) upload_max_filesize = 2M
From a WordPress perspective, there's not a lot to configure for performance. You can set `define( 'WP_DEBUG', false );` in your `wp-config.php` to disable logging, which will gain you some minimal savings. Beyond that, I would recommend working on making sure your heavier plugins are optimized as best as you can, reduce the number of requests if possible, and optimize your queries. You can take a look at plugins like Debug Bar to get an idea of what may be taking up the most resources on any given request, and services like New Relic can provide deeper insights to what's going on with your server in general.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, options, server, optimization" }
How can I delete a user from entire multisite nework I'm making a front-end user delete button but it only removes the user from the current installation and I need to remove them from the entire multisite network so they are able to sign up again with the same email if they decide. Is there a way to do this? $userid = get_current_user_id(); wp_delete_user( $userid );
You would want to use `wpmu_delete_user`: $userid = get_current_user_id(); wpmu_delete_user( $userid ); > Deletes a user from the network and removes it from all sites. <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "multisite, users" }
How To Display Author Popup on Entry Meta (Genesis Framework)? How to when the mouse pointer on the author name can display Author Popup like this site? ![enter image description here]( Thank you!
Genesis doesn't have built-in popup styling like (for example) bootstrap etc. You will have to find an extension plugin or built it custom. Take a look at this tutorial to start with CSS tooltips: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, jquery, javascript, post meta, author" }
Want to creat a search for my wordpress theme im new in wordpress , i've made my first theme and i need your help guys , i want to creat a search for my theme this is my search form : searchform.php <div class="search-home"> <form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>"> <input class="schome" type="text" id="search-box" value="<?php the_search_query(); ?>" placeholder="find your favorite game"> <button> search </button> </form> </div> what should i do pls ?
WordPress uses the `s` key for search. If you add `name="s"` to the input field this would probably work out of the box. Also make sure the button element has `type="submit"` so your browser knows this is the submit button.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "search, search engines" }
jQuery .html rendering I'm trying to render HTML in jQuery but it doesn't work. My PHP file : if ( $lastTokens[0]['token'] < $lastTokens[1]['token']) { $prixachat_format = '<i class="fas fa-arrow-up"></i>'.number_format($prixachat, 0, ',', ' '); } elseif ($lastTokens[0]['token'] > $lastTokens[1]['token']) { $prixachat_format = "<i class='fas fa-arrow-down'></i>".number_format($prixachat, 0, ',', ' '); } else { $prixachat_format = '<i class="fas fa-arrow-right"></i>'.number_format($prixachat, 0, ',', ' '); } $result = array( 'token' => $prixachat_format, ); wp_send_json($result); My JS file: jQuery.post( ajaxurl, { 'action': 'get_token' }, function(response) { jQuery('.update-token').html(response.token); } ) But it's still displayed as plain text? Any idea how to fix it ? Thank you
Try .append() instead of .html() jQuery.post( ajaxurl, { 'action': 'get_token' }, function(response) { jQuery('.update-token').append(response.token); } )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
WP_User_Query with 2 sets of conditions 'AND' I would like to write some arguments for my query and both need to be true. I am having trouble with the Syntax. 'meta_key' => $campaign_type, 'meta_value' => $Campaign_ID, **AND** 'meta_key' => 'organisation', 'meta_value' => $userOrg, Below is my query code: $args = array ( 'meta_query' => array( 'relation' => 'AND', array( 'meta_key' => $campaign_type, 'meta_value' => $Campaign_ID, 'compare' => '=' ), array( 'meta_key' => 'organisation', 'meta_value' => $userOrg, 'compare' => '=' ) )); Thank you.
You have an example here: < Problem with your query is that you use wrong keys. It should be: $args = array ( 'meta_query' => array( 'relation' => 'AND', array( 'key' => $campaign_type, 'value' => $Campaign_ID, 'compare' => '=' ), array( 'key' => 'organisation', 'value' => $userOrg, 'compare' => '=' ) )); Longer versions (`meta_key`, `meta_value`, `meta_compare`) are used, when you don't use `meta_query` but put them directly in the query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp user query" }
Combine two different filter callback functions I am currently using this code which works fine. function add_data_attribute($tag, $handle) { if ( 'chargebee' !== $handle ) return $tag; return str_replace( ' src', ' data-cb-site="mydomain" src', $tag ); } add_filter('script_loader_tag', 'add_data_attribute', 10, 2); However I need to combine this code with another tag: function google_maps_script_attributes( $tag, $handle) { if ( 'google-maps' !== $handle ) { return $tag; } return str_replace( ' src', ' async="async" defer src', $tag ); } add_filter('script_loader_tag', 'google_maps_script_attributes', 10, 2); Should I call two separate functions as best practice, or is it faster and better to combine the two functions together somehow?
I think you could or even should combine your filters to keep your code DRY. add_filter('script_loader_tag', function( $tag, $handle ) { if ( 'chargebee' == $handle ) : return str_replace( ' src', ' data-cb-site="mydomain" src', $tag ); elseif( 'google-maps' == $handle ) : return str_replace( ' src', ' async="async" defer src', $tag ); endif; return $tag; }, 10, 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions" }
WooCommerce does not translate every string So I have an issue with WooCommerce translation to German language - basically it does not translate every single string. I'm using a child theme of "Neighborhood" theme and we have a plugin Loco Translate active. I've inspected .po file and it seems that every string is being translated properly, I've tried to place the file in multiple different directories based on WooCommerce localization instructions, but somehow this issue still persists. URL to the site : < I should mention that this issue has occured once we've switched from German to English and then back to German ( meaning after the language toggle, before the toggle site was on German and everything worked great ). I've also tried disabling Loco Translate and tried different translation methods recommended by WooCommerce, yet still there was no change. Any help would be appreciated!
So as you explained I installed fresh WordPress with woo-commerce and Loco Translate is working fine, I am using storefront theme, So i guess It's something your theme is not compatible. One thing i found is that when i changed language from English to German and then back to German there were still some words left unchanged but when i removed product from cart, everything become normal. I think you should take support help if you are not able to do it yourself.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, translation, localization" }
Website does not reflect changes on live after uploading files via FTP I have a Wordpress site that is already published on a domain. As I wanted to update the content of some pages, I edited the local version of my website on localhost and then uploaded the files using an FTP client. However, the changes do not appear on the live site. I cleared the cache of my browser and also emptied all caches of my wordpress site using a plugin. Still no content updates showing on the website.
There is a difference between Wordpress files you upload on your **FTP** , and Wordpress "content" that is stored in your **database**. For your content to be updated, **you have to migrate your Wordpress database online**. **Resources:** * This link explains how you can migrate your Wordpress website entirely < * For example, has stated by @WebElaine, you can use database migration plugins such as this one among others < * * * _Also, as said in the comments, you could also copy paste your content from localhost to your live website. In order for the whole thing to be easier, try using the "preview" functionality in your editor instead of updating your localhost website._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads, updates, ftp, post content" }
Custom Field Order by Last Name and First Name I'm looking to find a way to order my query by Last Name first then First Name. I was able to do Last Name although not much luck in the Last Name + First Name part. This is what I came up: $posts = get_posts( [ 'post_type' => 'soldier', 'post_status' => 'publish', 'posts_per_page' => 5, 'meta_key' => 'last_name', 'orderby' => 'meta_value', 'order' => 'DESC', 'meta_query' => [ [ 'key' => 'last_name', 'orderby' => 'meta_value', 'order' => ASC ], [ 'key' => 'first_name', 'orderby' => 'meta_value', 'order' => ASC ], ], 'paged' => $soldier_paged ] );
Your code has a few issues, some unrelated, but generally, you need named meta queries to order by multiple meta keys: $posts = get_posts( [ 'post_type' => 'soldier', 'posts_per_page' => 5, 'paged' => $soldier_paged, 'meta_query' => [ 'last_name_clause' => [ 'key' => 'last_name', 'compare' => 'EXISTS' ], 'first_name_clause' => [ 'key' => 'first_name', 'compare' => 'EXISTS' ], ], 'orderby' => [ 'last_name_clause' => 'ASC', 'first_name_clause' => 'ASC', ], ] );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, php, custom taxonomy" }
Template for front page (latest posts) I am having * * * index.php -> This renders the latest post with sidebar * * * page.php-> This renders the page layout : Templates are fullwidth,sidebarleft& sidebarright * * * single.php-> This renders the single post layout : Templates are fullwidth,sidebarleft& sidebarright * * * whether a template can be provided for index.php? How can i provide option for full width, sidebarleft& sidebarright options for index.php?
> whether a template can be provided for index.php? There's no built-in capability for selecting a custom template for archives. > How can i provide option for full width, sidebarleft& sidebarright options for index.php? You can add a generic Customizer control with options for which template to use for archives, then inside index.php you would just check the saved value of that control with `get_theme_mod()` and change the template accordingly, or include another template file, for example: switch ( get_theme_mod( 'layout' ) ) { case 'fullwidth': get_template_part( 'index', 'fullwidth' ); break; case 'sidebarleft': get_template_part( 'index', 'sidebarleft' ); break; case 'sidebarright': get_template_part( 'index', 'sidebarright' ); break; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, templates, page template" }
How to disable autocomplete for inputs in contact form 7? I have below code for contact form 7. Usually I use `autocomplete="off"` for html input field. However not able to figure out how to do the same for contact form 7 <div class="row"> <div class="col-md-6"> [text* FirstName placeholder "First Name"] </div> <div class="col-md-6"> [text* LastName placeholder "Last Name"] </div> <div class="col-md-12"> [email* EmailAddress placeholder "Email Address"] </div> <div class="col-md-12"> [text* desc placeholder "Tell us a bit about yourself..."] </div> <div class="col-md-12"> [submit "Submit"] </div> </div>
Autocomplete tag in form settings does not work anymore (as today Contact Form 7 plugin version `5.1.3`. The only solution which worked for me was to add custom attributes thanks to < E.g. if You have `FirstName` and `LastName` fields, where You want to disable autocomplete. Add this into `functions.php` file: add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' ); function imp_wpcf7_form_elements( $content ) { $str_pos = strpos( $content, 'name="FirstName"' ); if ($str_pos) { $content = substr_replace( $content, ' autocomplete="both" autocomplete="off" ', $str_pos, 0 ); } $str_pos = strpos( $content, 'name="LastName"' ); if ($str_pos) { $content = substr_replace( $content, ' autocomplete="both" autocomplete="off" ', $str_pos, 0 ); } return $content; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, forms, plugin contact form 7" }
Possible to have duplicate usernames on different two multisites I have a multisite set up with two sites setup: example.com/site01 example.com/site02 With both sites, they are using the same custom theme which generates a default list of users (`publisher01`, `publisher02`, ..., `publisher10`) However, when I activate the theme on the second site, the users don't get generated due to the fact of having the same usernames. Is it possible to have the same list of users (but not the same user) in each site apart of the network? The only way I can think of is to have it unique Wordpress installs, and not apart of the network.
Short answer, No. Because WordPress Multisite stores all users in one table, you can't have two user on two sites in network with the same username. Read more at: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, users, user registration" }
How to remove the Welcome watermark on this page? If you go to my website you'll see a big watermark with "Welcome on it" How do I remove this? I've tried using inspect element and I get span as the element so I do in additonal css #span{ display: none; } but it does not seem to be working. ![problem](
#span would reffer to an element with id="span" you need to refer the correct element to achieve this: .intro-item span{display: none;} Read a css manual on selectors for more about this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Custom field disappeared from screen options I've been trying to display the custom field section for my posts in the admin, but it's not under screen options anymore... Was it moved somewhere else? Thanks!
If you have ACF installed, they added a setting to disable Core's Custom Fields to try to speed up editor page load time. To disable you can use this filter: add_filter('acf/settings/remove_wp_meta_box', '__return_false');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field" }
separate functions for home VS other pages I need a function that replaces the price in WooCommerce with "Request a quote". On my site's homepage I just need the text, but on the product page (which is a custom product from my travel theme) I need it to be a button. How can I have 2 functions, one that only works on Home and the other one that works in the rest of the site? In functions.php, something like: **IF IS_HOME:** add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); function custom_call_for_price() { return 'Request a quote'; } **AND IF IS_NOT_HOME:** add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); function custom_call_for_price() { $html .= '<a href="#"><input value="Request a quote" type="submit"></a>'; return $html; } Can it be done? Thanks!
Use this: function your_function() { if ( is_front_page() ) { $output = ... } else{ $output = ... } return $output; } p.s. It's not needed to use `is_home()`. Whoever needs the technical details, see `is_front_page` and `is_home`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
update_option_{$option} Too Few Arguments Adding a callback to `"update_option_{$my_option}"` results in the error _Too few arguments to function_. My callback accepts `$old_value` and `$new_value`. If I remove `$new_value` from the callback declaration and debug `$old_value` I am supplied with the correct `$old_value`. Why isn't `$new_value` being supplied by WordPress?
When you call `add_action`, you need to tell it how many parameters of the action that you want to receive. The default is just the first parameter. If you want more, then you tell it so. `add_action( 'update_option_whatever', 'example_callback', 10, 2 );` The 10 is the priority (10 is default). The 2 is the number of parameters to send to your callback (1 is the default). So if example_callback looks like this: `function example_callback( $old_value, $new_value )` Then you need that 10,2 on the add_action.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, options" }
Admin List Dynamic Heading I want to modify dynamically the Heading1 that appears on top of the Admin List of posts. E.g. the Page heading of the Pages list. ![pages admin list]( I have exhausted all possible searches I could think of and nothing relevant came out. Is there any function, filter, etc that allows us to modify what the content of the H1 heading of a custom post type list page would be? I actually want to be able to add the title of a taxonomy when the list is filtered by that taxonomy.
When you take a look at `wp-admin/edit.php`, you'll see that this string is printed with this line: echo esc_html( $post_type_object->labels->name ); So there is no filter to modify it in `edit.php`. There are no filters in `get_post_type_object` also, so we can't change it in there too, but... The object for given post type is stored in global variable called `$wp_post_types`, so you can modify it: function change_page_post_type_object() { global $wp_post_types; $wp_post_types['page']->labels->name = 'Not-Pages ;)'; } add_action( 'init', 'change_page_post_type_object' ); And that's the result: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom post types, filters, admin" }
Create dynamic logo carousel without using any plugin I am converting an html template to a WordPress theme. In the WordPress theme development process I'm stuck at dynamic logo carousel. Can anyone tell me how to create a logo carousel dynamically without using a plugin? Maybe by using any method like featured post, an image carousel, etc. ![client logo carousel](
You can create a **custom post type** for the logos as shown below, function create_post_type() { register_post_type( 'logo', array( 'labels' => array( 'name' => __( 'Logos' ), 'singular_name' => __( 'Logo' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Logo' ), 'featured_image' => __( 'Add Image' ), 'edit_item' => __( 'Edit Logo' ) ), 'public' => true, 'menu_icon' => 'dashicons-images-alt2', 'has_archive' => true, 'rewrite' => array('slug' => 'logo'), 'supports' => array('title','thumbnail'), ) ); } add_action( 'init', 'create_post_type' ); Add the above code in your theme's functions.php file. Then you replace your static logos with post loop.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, functions, theme development" }
How to parse Yoast SEO Snippet Variables I see Yoast stores the snippet variables in the database. I'd like to get their values and ship them via the WP REST API. I'd also like to keep the Admin functionality for Administrators and the default settings for scalability. I'm shipping the values off to a different application, but I can't ship the placeholders. They can obviously get parsed because that's how they display in the frontend. I just don't see how to do it. In the database you can see: _yoast_wpseo_title %%title%% %%page%% %%sep%% %%sitename%% On the front end you can see: <title>About - Cool Site Name</title>
Basically this is the answer I was looking for from this question: function yoastVariableToTitle( $post_id ) { $yoast_title = get_post_meta( $post_id, '_yoast_wpseo_title', true ); $title = strstr( $yoast_title, '%%', true ); if ( empty( $title ) ) { $title = get_the_title( $post_id ); } $wpseo_titles = get_option( 'wpseo_titles' ); $sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options(); if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) { $sep = $sep_options[ $wpseo_titles['separator'] ]; } else { $sep = '-'; //setting default separator if Admin didn't set it from backed } $site_title = get_bloginfo( 'name' ); $meta_title = $title . ' ' . $sep . ' ' . $site_title; return $meta_title; } <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin wp seo yoast" }
Additional CSS for the nav menu I have customised the navigation menu on this site. Each main menu item has its own hover colour. My question is, how do I change the selected menu item colour to match in the sub menus. Currently I can change all to a different colour but what I want to achieve is a different colour for each sub menu selected item. It is currently set to a shade of orange. www.clowntown.co.uk
Using the menu id for each menu item I could customise each menu heading as I needed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css, navigation" }
Show total sales for each products on search results page Woocommerce I customize my search results page like this when show the results as shown in the picture at the bottom I want to show total sales for each products on search results page ![enter image description here](
You can use third-party WooCommerce plugin 'Woo Total Sales' to display total sales of the specific product on product archive, product single or product search page. Woo Total Sales: < You can also use below shortcode that plugin provides and add product ID to display its count. [awts-total-sales product_id="0" include_setting="true/false"] ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, woocommerce offtopic, search" }
Gutenberg editor add a custom category as wrapper for custom blocks As we know by the provided API from Gutenberg we can create a custom block as const { registerBlockType } = wp.blocks; registerBlockType( 'my-namespace/my-block', { }) but how do I create a wrapper(category like layout) around my custom blocks in gutenberg editor? Let's say I want to have a collector for my custom elements as slider, gallery ...
Digging myself deeper in documentation, I got the following result. There is a way to group your custom blocks around a given category in Gutenberg, and therefore we have the method `block_categories_all`. So with a filter, you can extend the default categories with custom ones. Here is my example: add_filter( 'block_categories_all', function( $categories, $post ) { return array_merge( $categories, array( array( 'slug' => 'my-slug', 'title' => 'my-title', ), ) ); }, 10, 2 ); You can find more on this in the provided API.
stackexchange-wordpress
{ "answer_score": 15, "question_score": 10, "tags": "categories, customization, editor, block editor" }
How to get all attributes with their terms related to specific Woocommerce product category As we know, to get terms of specific attribute added to a product we can use: $attr_terms = $product->get_attribute( 'attr_slug' ); OR to get all terms of specific attribute regardless of a product we can use $attr_terms = get_terms( 'pa_attr_slug' ); But how to get all attributes with their terms added to products of specific product category? Something like: $cat_attrs = ... ($cat->id); foreach($cat_attrs as $cat_attr) { echo $cat_attr->name; // name of attribute foreach($cat_attr->terms as $term) { echo $term->name; // name of attribute term } }
Well, I found the following solution: $args = array( 'category' => array( 'category_slug' ) // or 'term_taxonomy_id' => 4 i.e. category ID ); foreach( wc_get_products($args) as $product ){ foreach( $product->get_attributes() as $attr_name => $attr ){ echo wc_attribute_label( $attr_name ); // attr label // or get_taxonomy( $attr_name )->labels->singular_name; foreach( $attr->get_terms() as $term ){ echo $term->name; } } }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 1, "tags": "woocommerce offtopic, terms, customization" }
Same Server, Same PHP, One Site Doesn't Work I have three domains on the same server (CentOS 7.5.1804), all running WordPress 4.9.8, all running the same version of PHP (7.2.10) and using the same php.ini file (literally, not the same php.ini file copied to each directory, the exact same single file). The problem is that on only one domain, WordPress thinks that I don't have `php-mysql` installed, yet the other two sites work without issue. I get the following on the non-working domain: > Your PHP installation appears to be missing the MySQL extension which is required by WordPress. Despite the fact that the same `php.ini` file is being used, on the non-working site, the `phpinfo()` report is missing the `mysqli` section. Domains are: hummdis.com (non-working), dev.hummdis.com (working), exoticallyplugged.com (working). Thoughts??
So, I've resolved the issue and I'm not 100% sure what fixed it. However, these are the steps that I took: 1. `yum update` 2. This resulted in: > Found 3 pre-existing rpmdb problem(s), 'yum check' output follows: I'm not going to provide the full update, the point is that I couldn't perform a Yum update because of these issues. 3. I found this post and followed the steps. 4. I then found this post and followed the steps that install `yum plugin-priorities`. I then tested the site and it's loading without issue.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Overriding a plugin's pluggable function in theme's function I came across this snippet - < \- that creates a function with the same name as an existing WC function as a means of overriding it. I also learnt that this way of overriding works because the original function is 'pluggable' due to the !function_exists() function. My question is since plugins gets loaded before themes i.e., WC would have created the function first, shouldn't the attempt to override the function fail because the 'if (!function_exists('woocommerce_template_loop_add_to_cart'))' condition isn't satisfied? Appreciate any input!
The WooCommerce file that defines its pluggable functions isn't loaded until after themes are loaded. It does this by hooking a function that includes the file into the `after_setup_theme` hook: add_action( 'after_setup_theme', array( $this, 'include_template_functions' ), 11 ); That's from the `/includes/class-woocommerce.php` file in WooCommerce. The `include_template_functions()` function includes the file that defines functions like `woocommerce_template_loop_add_to_cart()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pluggable" }
Is there a plugin or a way in the wordpress that would let us have different versions of a post or page accessibe to users? I work on a website which talks about and teaches some educational subjects. It happens alot that I talk and explain about a software like a year ago and a new versions comes out. Currently what I do, is I edit the post and add the new explanations, sometimes the old context is lost or summerized into a section at the end of the article. I want to be able to have this old revision accessible to the viewers. Like what we have in the wordpress editor which shows several older versions which we can choose and compare. this way, I can address and navigate users to read about the older version using the revision they can have access to, and then update the main arctile with the newest information. Do we have something like this in wordpress? if not whats other alternative for implementing this ?
It sounds like you are after adding Wiki functionality to your Wordpress site(but with editing restricted to author). See this write up on the topic (complete with revision links above comments). The above article uses the Post Revision Display plugin which hasn't been updated for a while. However, as he is an tech writer and still using it, I assume it is still compatible with latest Wordpress. If not just search wordpress.org for other WordPress Wiki plugins, I'm not sure if or how those alternatives will restrict revisions, but one may fit the bill.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts" }
WooCommerce - Moving Product Price to the Left of Add to Cart Button I am using the theme Salient and want to move the product price to the left of the add to cart button. Currently I have my product price above the button as you can see in the image below: ![enter image description here]( I already moved the price element around by adding some php to this custom plugin called "Snippets". It puts it right above the button rather than above the "Acrylic on Canvas" text. Here is the code: remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 ); add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 25 );
So I think that now you just have to add the proper css. On both elements (price and button) place: display: inline-block; You can also try: float: left;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, woocommerce offtopic" }
Inserting additional &nbsp; into menu item text I'd like a specific menu item to have more spaces between words. **For example:** Word Word **Needs to be:** Word Word In the menu editor, WP strips-out any additional spaces added with the spacebar or using the HTML code `&nbsp;`. What's the next most efficient method?
Previously I assumed WP would strip HTML, so I never tried it. The HTML below works like a charm, using the WP menu editor: `Word <span style="margin-left: 20px;"> </span> Word` (however, inputting `&nbsp;` didn't) Alternatively, the CSS trick mentioned by Jacob and Linda would work well too: `word-spacing: 3px;` My menu item actually has 4 words, and I just needed to increase the middle spacing. In the end, it's nice avoiding a PHP function or JS client-side. I just wonder is there any issue down the line having HTML in my menu title. Other than my menu rendering in the page layout, I can't think of where else I may output the menu items to.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus" }
Is it possible to remove the posts_per_page limit on a specific post type? I'd like to know if I can remove the limit on the posts_per_page for a specific post type. In the archive.php page I'm displaying different post type, and for the specific "publications" post type I want to display all the posts. How can I achieve this without impacting the traditional "post" type?
You can hook into the `pre_get_posts` action, to access the `$query` object. You should use your action hook inside your functions.php. An example of what your function could look like: add_action( 'pre_get_posts', 'publications_archive_query' ); function publications_archive_query( $query ) { if ( !is_admin() && $query->is_main_query()) { if ( $query->get('post_type') === 'publications' ) { $query->set( 'posts_per_page', 5 ); } } Narrow down what is the query you are modifying by using conditional checks. `$query->get('post_type')` to get current's Query post_type to check against. `is_main_query` to make sure you are only applying your query modification to the main query. Read further and find more examples: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "custom post types, custom post type archives" }
Woocommerce - Adding row to cart table I would like to add an extra row to the Cart Table in Woommerce, but I can't find the right action. From this file < I would expect the 'woocommerce_after_cart_contents' action to be the right one (line 149), but it prints the content above the cart table. Am I missing anything? Here's the code (in `functions.php`): function quality_certificates(){ echo '<tr>TEST</tr>'; } add_action('woocommerce_cart_contents','quality_certificates'); And this is the output: <form class="woocommerce-cart-form" action="..." method="post"> TEST<table class="shop_table ..."> etc.
You already have the right "action", which is `woocommerce_after_cart_contents`. But when I tried the markup you used: function quality_certificates(){ echo '<tr>TEST</tr>'; } this was the visual output: _(I actually initially tested with the Twenty Seventeen theme; sorry about that. But this one is tested with Storefront)_ ![]( Then I started thinking that the problem _might_ be the markup, so I changed it to: <tr><td colspan="6">TEST</td></tr> and voila! I got the expected visual output: ![]( So, **use the proper markup/HTML**. =) _PS: Those are **actual** screenshots. ;-)_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, hooks, actions" }
woocommerce_new_product action doesn't fire I am trying to run a function every time a new product is added on woocommerce, for so I am using woocommerce_new_product action. For this I add a new action function uniqueNameFunction($id) { wp_die("event worked"); } add_action('woocommerce_new_product', 'uniqueNameFunction', 10, 1); I suspect maybe I do not register it correctly in my plugin, so to make sure I do it right I regenerated a plugin using this tool and add it along with other actions already in the template. In order to test it I just add a new product using admin UI. This does not fire, and I have no idea why and how to debug it. Would be nice if someone gives me some ideas. Thanks!
Try like function add_this_to_new_products( $new_status, $old_status, $post ) { global $post; if ( $post->post_type !== 'product' ) return; if ( 'publish' !== $new_status or 'publish' === $old_status ) return; add_post_meta( $post->ID, 'total_amount', '0', true ); // This is the action to take } add_action( 'transition_post_status', 'add_this_to_new_products', 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, actions" }
Printing HTML codes I'm pretty new in PHP, this is a code in the comment.php file: printf( /* translators: 1: title. */ esc_html__( '<hr><Thoughts about '. get_the_title() .'<hr>', 'rainbowcats' ), '<span>' . get_post_meta($post->ID, 'usp_title',true) . '</span>' ); As you probably can guess, it prints the `<hr>` Anyway around this? (Remember, I'm pretty new, never used the command printf before..
If I understand your question well, your result shows your `<hr>` in text form. When you're using `esc_html__( string $text, string $domain = 'default' )`, the returned output is escaped, it means : * `"` is replaced with `&quot;` * `&` is replaced with `&amp;` * `<` is replaced with `&lt;` * `>` is replaced with `&gt;` So your `<hr>` are returning as text, not as html markups. To fix that, you can simply move your `<hr>` outside of your `esc_html__()` : <?php printf( '<hr>'.esc_html__( 'Thoughts about '. get_the_title(), 'rainbowcats' ).'<hr>'; ); ?> Furthermore, I don't understand what you are trying to achieve with `'<span>' . get_post_meta($post->ID, 'usp_title',true) . '</span>'` as an argument of `printf(format,arg)`, you should have called your arg with `%s` in your first parameter. But keep in mind to keep it outside `esc_html__()` ! For more information, see : <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, html" }
How to show some of category in wordpress I listed all category in front page with **get_categories()** function But i dont want show all category in output For example i dont want show catgegory with id=25 How to should i do that? This is my code <?php foreach (get_categories() as $cat): ?> <a href="<?php echo get_category_link($cat->term_id) ?>" class="post-cats-item"> <div class="post-cats-thumbnail"> <img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" alt="<?php echo $cat->name; ?>"/> <div class="post-cats-cover"></div> <h3 class="post-cats-name"><?php echo $cat->name; ?></h3> </div> </a> <?php endforeach; ?>
Try like $args = array( 'hide_empty' => 1, 'exclude' =>array(1,2,3) // desire id ); $categories = get_categories($args ); Hope it will help!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, theme customizer, categories" }
%20 in URL in archive page shows error 404 on page I have made a custom archive page, so the page is working for single words like - **National** Category. For this the archive page works as it should be but when it comes to two words like - **Economy and Business** , now in this case the archive page shows error and the URL has **%20** which means space (searched on google). But why is the error 404 showing up ? **< \- This shows error 404 **< \- This works
Without the actual URL that you are having difficulties with, it's hard to answer. But, I suspect that the URL really **doesn't** exist. Which is why you get a '404' not found error. If you edit your question to include the actual URL (put it in a 'code' block), you might get a more specific answer.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "404 error, custom post type archives" }
How to use PanelColorSettings in custom Gutenberg block? I'm working on a custom Gutenberg block. I have used `<PanelBody>` `<BaseControl>` and `<ColorPalette>` to create some custom color pickers, however, it seems like it would be more efficient to use the built-in `<PanelColorSettings>` component. Has anyone used `<PanelColorSettings>` component in a custom block? The only discussion of this technique I could find was here: <
First you need to import the component - const { PanelColorSettings, } = wp.editor; then inside the **InspectorControls** you call the component <PanelColorSettings title={ __( 'Color Settings' ) } colorSettings={ [ { value: color, onChange: ( colorValue ) => setAttributes( { color: colorValue } ), label: __( 'Background Color' ), }, { value: textColor, onChange: ( colorValue ) => setAttributes( { textColor: colorValue } ), label: __( 'Text Color' ), }, ] } > </PanelColorSettings>
stackexchange-wordpress
{ "answer_score": 12, "question_score": 8, "tags": "plugin development, customization, block editor" }
How to use update_option() without replacing/losing the old value? I want to update an option, but instead of replacing the old value with the new one, Ì want to add new value to existing one. So the new value should be $oldvalue + $newvalue. I read about pre_update_option filter, but haven't understand how to do what I need.
Use `update_option()` in conjunction with `get_option()`: $old_option = get_option('blogdescription'); $new_option = 'My new blog description'; $new_option .= $old_option; // This is the same as $new_option = $new_option . $old_option; update_option('blogdescription', $new_option); If they are integers, obviously use something like `$new_option += $old_option`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "options" }
Dynamic_sidebar inside wp_nav_menu I have Menu created by wp_nav_menu. Inside it, I want to set dynamic_sidebar but wp_nav_menu instead of displaying the content, throws 1. Have everyone some tips for display sidebar inside wp_nav_menu? I have to add dynamic_sidebar inside menu it's important. Inside walker I placed the code: $item_output .= ' <div class="recipes__dropdown"> <div class="container"> <div class="dropdown__content"> <div class="row">' . dynamic_sidebar( 'recipes-dropdown' ) . '</div> </div> </div> </div>'; Have you any suggestions how include dynamic sidebar inside wp_nav_menu?
You can add extra items in menu like add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 ); function your_custom_menu_item ( $items, $args ) { if ($args->theme_location == '[YOUR-MENU-LOCATION]') { $items .= '--YOUR EXTRA STUFF HERE--'; } return $items; } Hope it will help!
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "menus, sidebar, walker" }
Problem adding column to WC Subscription I am having trouble adding custom column to Woocommerce Subscription. My codes are as below: add_filter( 'manage_shop_subscription_posts_columns', function ($columns) { $columns['my_field'] = __('My Field'); return $columns; }, 10); What could be wrong with my code? I fail to understand why it is not working.
Alright, so since WC Subscriptions is creating it's own array for columns. Any filter priority lesser than their function will simply make your code non-functional. So what I did is I changed priority from 10 to 1000 so that my codes fire after their code. add_filter( 'manage_shop_subscription_posts_columns', function ($columns) { $columns['my_field'] = __('My Field'); return $columns; }, 1000);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, woocommerce offtopic, columns" }
Plugin recommendation for directory site I am developing a site that will allow artists to sign up to a directory of artists to showcase their work etc. I can handle all the bespoke coding but I have one issue that I can't take care of and need a plugin recommendation for I think. What I need is to create a process whereby a prospective artist can register for a normal WP user account but which will then only let them login when they have paid a recurring subscription via paypal. Once the payment has been authorised, I need the solution to grant them access.
Recommendations for plugins are 'out of scope' here. But you could do a search for 'paid subscriptions' in the WP plugin directory. Then you can contact the plugin's support area with your questions, and/or try them out on your site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "user registration, paypal" }
How to find php variable of wordpress theme settings I'm new to PHP and WordPress, but I have some experience with python, for my site I use the traveller theme. How can I find the exchange rate variable that exists in theme settings (the red square on the screenshot)? I need to change it automatically with another function, not manually via theme settings. What are possible ways to find such variable, or is there any convention where all theme variables stored? The only closest piece of code I found is on screenshot #2 (wp-content/themes/traveler/inc/st-theme-options.php), but I'm not sure if that's what I need & how to reassign it. Thanks ![theme settings screenshot]( ![enter image description here](
Plugin options are normally stored in the wp_options table. If you look at the plugin code (and reference the Plugin information in Codex; you can start here: < ), you will see how the plugin names the option. Then you can create a function that will change that option value. Note that most plugins store their options in one row of wp_options table, so you will need to make sure you don't bork the other options that the plugin uses. You might also want to contact the plugin's support area, which is the proper place for questions about plugins.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, theme options, variables" }
How to override the "inc" folder (or any folder) in a theme using child theme? I am using Storefront theme (But question isn't specify to this theme, I am asking question for any theme). I can easily override files like header.php, footer.php using child theme(just copy and paste the file). But I can't override any files which is on "inc" folder (any folder). How can I override those files?
WordPress only looks for the default template files while loading the child theme. So does woocommerce. Any extra folder or file that exists in your parent theme **can not** be overridden, unless the developer is using actions and filters that allows you to hook into them. Therefore, a simple `require()` or `include()` can't be overridden by a child theme. What you can do is to track the template file that is calling the files from the `inc` folder, and then override those in your theme's folder. You might need to go as back as `functions.php`. For a complete list of default template files, take a look at the template hierarchy.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "themes, templates, child theme" }
How to include jQuery into my plugin so I can use it on plugin page? How can I include jQuery file into my plugin so I can use it on plugin page?
JQuery is a part of Wordpress core, so it is automatically there for you to use (i.e. you do not need to register it). However, you still need to enqueue it. This can be done as follows: function my_script() { wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', 'my_script'); This loads jQuery from Wordpress core, the jQuery files can be found at /wp-includes/js/jquery/jquery.js if you are interested. Alternatively you can include jQuery as a dependency when you enqueue your own JavaScript file as follows (notice the 3rd argument): wp_enqueue_script( 'my_script_handle', plugins_url(('js/some_script.js, __FILE__), array('jquery'), '1.0', true); where some_script.js is your own JavaScript file which is assumed to be in the 'js' directory of your plugin in the example. You can find out more about the wp_enqueue_script parameters on the Wordpress Developer Help.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, jquery" }
Get Top parent url I have the following structure: * TOP PAGE * SUB PAGE 1 * \--- SUB SUB PAGE 1 * \--- SUB SUB SUB PAGE 1 * \---- SUB SUB SUB SUB PAGE 1 * \--- SUB SUB SUB PAGE 1 * \--- SUB SUB SUB PAGE 1 * \---- SUB SUB SUB SUB PAGE 1 How can I get the TOP PAGE url from any of the SUB PAGES? For example: Get TOP PAGE url from ---- SUB SUB SUB SUB PAGE 1 With this I can only get the previous page url and not the Top parent ulr if ( $post->post_parent ) { $parent_page_link = get_permalink( $post->post_parent ); // getting parent URL } There are many topics with related question but I can not solve my problem. Thanks,
You have to do it in a loop: $p = $post; while ( $p->post_parent ) { $p = get_post( $p->post_parent ); } $parent_page_link = get_permalink( $p->ID ); Another way is to use `get_ancestors` function: $ancestors = get_ancestors( $post->ID, 'page', 'post_type' ); $root = ( ! empty( $ancestors ) ) ? end($ancestors) : $post->ID; $parent_page_link = get_permalink( $root );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "urls, child pages" }
Save uploads directly in the uploads folder (on a multisite) on my current page I want my uploads to be saved directly in the uploaded folder. So their links should be something like ` instead of ` I remember reading somewhere, that this can be set under Settings->Media. However, the option doesn't appear there on my installation. ![enter image description here]( I should probably mention that this is a multisite installation. So maybe the named option can be found somewhere else there. But I couldn't find it yet. Do you know where to find this setting or how to change this?
Now here is how you can disable it in WordPress Multi-sites: * Login to Dashboard * Go to _Network Admin_ * Go to _Sites_ tab * Click on _Edit_ link for particular site. * Toggle to 4 tab under it – _Settings_ * Look for **_"Uploads Use Yearmonth Folders"_** * Change the value in text field from **1** to **0** * Save the settings.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, uploads" }
Limit home post to 10 without creating pagination? I'm trying to display the last 10 posts only on the home without wp creating /page/2, /page/3, archives. I've been testing and it seems if you disable pagination it will just grab everything crashing the server. (Don't do this at home). if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'posts_per_page', 10 ); $query->set( 'nopaging' , true ); } Someone suggested " no_found_rows=true" that doesn't do it either. Is this just impossible to do? It seems like it will either create the pages or show all, there's no way to "LIMIT" it?
This is a mistake it will retrieve of posts: $query->set( 'nopaging' , true ); What you should do instead is: if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'posts_per_page', 10 ); $query->set( 'paged', '1'); // Makes /page/2/, etc links redirect to home $query->set( 'no_found_rows', true ); // Avoid counting rows, faster processing. } If your theme is still rendering the navigation buttons you'll have to add some logic to hide them on the pages you disabled pagination, for me it was the home page: if (!is_home()) { // show pagination buttons }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
How to Get Rid of Unwanted Backslashes in WordPress Form Input inside admin menu option I'm building a simple plugin that allows adding custom scripts to header and footer. Everything seems to work fine, but there is a 'bug'. When I add Google Analytics script to header, it shows with backslashes before apostrophes. I tried: if ( get_magic_quotes_gpc() ) { $_POST = array_map( 'stripslashes_deep', $_POST ); $_GET = array_map( 'stripslashes_deep', $_GET ); $_COOKIE = array_map( 'stripslashes_deep', $_COOKIE ); $_REQUEST = array_map( 'stripslashes_deep', $_REQUEST ); } but that didn't solve the problem. Any advice?
In the documentation page for **get_magic_quotes_gpc** you can read: _Returns 0 if magic_quotes_gpc is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0._ I guess this can cause the first problem (that your code not works). Next **stripslashes_deep** You can use code like this: $_POST = stripslashes_deep( $_POST ); But just check the WordPress docs for the function because you can break functions of the core or other plugins that expect their values slashed. So it is probably better to work only on your own input vars: $my_value = stripslashes( $_POST['value'] );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, scripts" }
woocommerce add a new bulk action in the bulk actions dropdown in the orders list I'm trying to add a custom bulk action in the WooCommerce orders list that will a piece of code I've made for individual orders but need to make it work recursively. I'm aware of that: Custom bulk_action but it is referring to wordpress bulk action menus and not specifically for woocommerce. could you please help me get it working in my plugin for woocommerce orders list? Furthermore, I'm also a bit stuck about how, after adding that action, to scan which orders are checked and apply the bulk action only on the selected orders.
As LoicTheAztec commented, the post here Using custom bulk actions on admin orders list in Woocommerce 3 helped me to make the code for my plugin. Although it mentions that you should use the functions.php to make it work, I was able to implement it perfectly in my own plugin code. Thanks, Loic. I appreciate it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, woocommerce offtopic, bulk" }
Domain Pointing to www.domain.com:8888 I have uploaded my website through FTP and database to mysql, the domain is now showing www.domain.com:8888 and seems to be pointing to my local host still. how do i redirect this to tell it to now locate the active domain online, what file do I need to correct? Any help appreciated. thanks.
Moving a site is more than moving the database. And it is more than updating the wp-options table's URLs (although that is important). You also have to change any references to the old URL in the database. I use a plugin called "Better Search and Replace" to update the URLs in the database. (There are other similar plugins; this is the one I prefer. YMMV.) But I also use my own procedure, developed over many site moves, to properly move a site from one place to another, whether that be a development-to-live move, or a move to a new hosting place. The process is too long to post here. Here's the link: < . If you follow all parts of that procedure, you will have a successful site move.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "localhost, domain" }
Simple way to add custom class and ids to individual Gutenberg blocks Is there a simple way to add classnames to individual core Gutenberg blocks? Blocks is a great step toward moving to a web where HTML structurally/functionally describes elements, which are styled elsewhere in CSS. However, this is limited in that blocks cannot be easily classed? I'd be happy with a plugin that extends existing (or custom) block functionality to include classes and ids.
Every block has a field for custom CSS classes in the 'Advanced' panel: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, html, block editor" }
Are there Gutenberg container blocks? In web design, a key design element is the container that may contain various other content and blocks and is styled in CSS. Is there a Gutenberg container block that may contain other blocks? If so, I haven't found it yet. It looks like the Gutenberg editor now supports representing nested blocks. Some folks have been requesting section blocks. Any love there yet? I WAS able to change the Columns block to one column, but that feels like a clunky hack.
There's a new core "Section" block that will be available in an upcoming Gutenberg update which is intended to serve the role you're looking for I think: Add Section block
stackexchange-wordpress
{ "answer_score": 2, "question_score": 9, "tags": "css, block editor" }
Starting with tabbed metabox I need a tabbed metabox for my plugin. Actually they are 5 metaboxes each one in a tab. I found these scripts: < Which one is best for using in meta boxes? It's better to have only CSS ? JS must be registered ? I want to start testing these scripts but would like advice on where to start. thank you
I've founded the best solution and used redux framework. It really provides what I was looking for.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox, wp register script, tabs" }
How do I customize the post page I'm currently trying to add an post page on my Wordpress website. I put my new post page as the default post page, on Settings -> Reading. The id of my page is 353. So I created a new php file named `page-353.php` based on `page.php`. But the current template is still `index.php`. Is there a way I can customize the HTML/PHP of the default post page? Thank you.
I'm answering my own question, since I found the solution: this page have a default name, since it's a key page for Wordpress. Considering this chart its name is `home.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, pages, page template" }
Bulk upload images in upload folder does not show in media library my website currently in staging site and I host it locally. Today, I upload some pictures from Live website to `wp-content > upload` folder but It does not show in Media library, however if I use link `domain.com/wp-content/uploads/year/month/img`, I can see the picture. I've tried several things like changing the directory permissions to 777/775 but it does not work. Any ideas?
Welcome to WordPress Stack Exchange community. Actually adding media directly to uploads folder, will not be shown in WordPress Media Library as those images which you have added manually in upload folders are not stored in the database. However, if you manually use image path then they will be accessible but it will not get displayed in Media Library. WordPress stores all uploaded media files as a media post in the database and displays them in Media Library. So please upload all images in 'Media' in your website backend, instead of manually uploading them in the upload folder. Hope this helps!! ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media library" }
Is there any action /filter hook I can use to disable login for some user role? I want to block user role called "pending" loging to the site. (pending is a custom user rolled created by me). Is there any action/filter to block all users who are in "pendin" user role?
Yes, there is. You can use authenticate hook: add_action( 'authenticate' , 'check_custom_authentication', 20, 3 );
 
 function check_custom_authentication ( $user, $username, $password ) {
 if ( is_a($user, 'WP_User') && in_array('pending', $user->roles) ) { return new WP_Error('pending', 'Your error msg'); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, login" }
Redirect to other page if login I have a home/static page with login button. Currently I've set the button url as "< How can I set the login button to redirect to a specific page IF/WHEN the user is logged in? I do not know much about coding. I found some solution about add_action or something and added to theme's function.php. But I can't get it work. Summary: if non-login user: login button url ---> login page if login user: login button url ---> specific page
Add below code in your **functions.php** file of active theme directory in order to restrict the login page to logged-in users and redirect them to core user page (user profile). You can replace **"um_get_core_page( 'user' )"** with any page URL where you want to redirect logged-in users. /* Restrict Login page to logged-in users and redirect to core user page (user profile) */ add_action( 'template_redirect', 'um_restrict_login_page_logged_in' ); function um_restrict_login_page_logged_in() { if ( um_is_core_page('login') && is_user_logged_in() ) { wp_redirect( um_get_core_page( 'user' ) ); exit; } } Hope this works!!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, redirect" }
When does the Yoast SEO filter hook wpseo_sitemap_urlimages fire? I am trying to attach a simple function to the Yoast SEO filter hook `wpseo_sitemap_urlimages` and get the function to run, but I cannot do so. My code is: function tp_filter_wpseo_sitemap_urlimages($images, $post_id) { error_log("test message"); return $images; } add_filter('wpseo_sitemap_urlimages', 'tp_filter_wpseo_sitemap_urlimages'); To get this function to run, I have tried opening the following Yoast XML sitemaps: * sitemap index (< * post sitemap (< * page sitemap (< My eventual goal with this is to add additional images to the Yoast post and page sitemaps (per these Yoast instructions). The only support Yoast has offered for this is to direct me to this page.
What I wanted to say in my previous comment: This hook is only fired when the sitemap is being **built**. After that, it's **cached** and always served from cache. That means you'll never see any change on the frontend because it's all cached. To disable the cache you can use the following code during development: add_filter( 'wpseo_enable_xml_sitemap_transient_caching', '__return_false' ); After that, the sitemap is never served from cache but always built when viewing the sitemap in the frontend. Then you'll see some changes.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin wp seo yoast, sitemap" }
Non editable custom taxonomy I have reviewed Creating a non-removable taxonomy term but it has not answered my question. One of the built-in Taxonomy terms is the "post formats". This cannot be edited. What I would like to do is register a taxonomy for which my plugin will provide the terms that, likewise, cannot be edited. How do I do this? Is it possible to hook whatever in core keeps the format taxonomy locked down?
When doing register_taxonomy, set the `public` parameter of the `args` argument to false. Most basic example: register_taxonomy( 'my_tax, 'post', [ 'public' => false ] );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, custom taxonomy, taxonomy, register taxonomy" }
How to update mu-plugin I'm managing a wordpress site that was developed by another party, and they put a bunch of plugins in the mu-plugins folder. These plugins can't be updated via the default interface of WordPress, and must be updated manually. I can't find any details on how to correctly update these plugins. Is it just a matter of replacing the current files with the updated version of the plugin? An additional question: can I just transfer these plugins to the plugins folder, or would there be a risk of the plugin/site breaking? Assuming all these plugins are correctly programmed and available in the WP plugins directory.
First, please check this out: < In most cases mu plugins consist of a singular php file in that directory. In that case you could just replace the file. In any case, there is neither a process for installation nor uninstallation, you simply drop files in that dir or delete them from it. It's as it is always with updates: Back the directory up, replace the plugin files one by one and check if everything's still working as expected. Never used the mu-plugins dir to store regular plugins. As e.g. activation hooks don't fire in there, not every plugin is suitable to be put there. IF a regular plugin was put there, I would try to remove it (again, backup!) and install the latest version as you would any other.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, updates, mu plugins" }
Counts Posts ( custom post type ) by Author in author.php Here is the code that I use to counts posts for one post_type, I would like to use multiple post_type ( post_type_1, post_type_2... ) anyone can help me doing this ? Thanks for the help. <?php global $wp_query; $curauth = $wp_query->get_queried_object(); $post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'"); ?> <h2>Post Count: <?php echo $post_count; ?></h2>
OK, so there are some problems with your code... 1. Your SQL isn't very safe. It would be much nicer, if you used prepare method: $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_author = %d AND post_type = %s AND post_status = %s", $curauth->ID, 'post', 'publish' ) ); 2. You clearly say, that you want to count only posts `post_type = 'post'` is the part that is responsible for that. So just remove that part or modify it according to your needs. 3. Be careful counting different post types - remember that attachment (and so on) is also a post type. 4. Use built in functions. It would be much nicer to use `count_user_posts`. <?php $curauth = $wp_query->get_queried_object(); ?> <h2>Post Count: <?php echo count_user_posts( $curauth->ID, 'post_type' ); ?></h2>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Creating a child theme from Twenty Seventeen I need to create a child-theme from Twenty Seventeen on a site that has been running for a while so I can make some modifications. If I switch it to the child theme will I loose all the menus, widgets and other things set in the customizer? Are there any other issues I might run into?
Yes,the Customizer settings will not carry over from parent to child. Activating a new child theme essentially means you are starting from scratch with regards to the Customizer. Perhaps, try cloning the site and run it on a development server or local machine, and make the switch, then see what is lost. I did find a free plugin that i tested out, and successfully exported and imported the customizer settings on the twentyseveteen theme/child theme. Super easy. Maybe give that a try. Customizer Export/Import <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "child theme, theme twenty eleven" }
How to get data about category in category.php I have to make custom `category.php` template, but how do I get data about category in `category.php`? I need these: * Category name and id * Category's parent name and id * All category's items Let's say our link is www.website.com/category/sub-category and what we want is to display category and sub-category fullname + all sub-category items.
OK, so there are many ways to solve this. You can use special template tags for some of these (for example `the_archive_title` to show the title of current category, and so on). But to achieve all of these, you'll need to get `get_queried_object`. If you're viewing category, this function will return current category object. So after: $current_cat = get_queried_object(); You can get its name using: echo $current_cat->name; And its id using: echo $current_cat->term_id; To get its parent: if ( $current_car->parent ) { $parent = get_category( $current_car->parent ); echo $parent->name; echo $parent->term_id; } And to get all subcategories of `$parent`: $categories = get_categories( array('parent' => $parent->term_id) ); foreach($categories as $category) { echo $category->name; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, theme development, themes, terms" }
how do prevent wordpress from creating permalinks for media files Could one please explain how can I prevent `WordPress 4.9` from creating permalinks/slugs for Media files without the need of installing another plugin? It's also important that the solution won't get overwritten by consecutive WordPress updates.
In a plugin or in your functions.php file put this : if ( !function_exists( 'xxx_remove_attachment_permalink' ) ) { function xxx_remove_attachment_permalink( $rules ) { foreach ( $rules as $regex => $query ) { if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) { unset( $rules[ $regex ] ); } } return $rules; } add_filter( 'rewrite_rules_array', 'xxx_remove_attachment_permalink' ); } if ( !function_exists( 'xxx_remove_attachment_link' ) ) { function xxx_remove_attachment_link( $link ) { return; } add_filter( 'attachment_link', 'xxx_remove_attachment_link' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, media library, slug" }
Use same page-mypage.php template for several pages How can I use the same `page-mypage.php` file for different pages, without resorting to page templates?
To re-use the same template for different kinds of pages you can use the `template_include` filter. Example given from the docs: add_filter( 'template_include', 'portfolio_page_template', 99 ); function portfolio_page_template( $template ) { if ( is_page( 'portfolio' ) ) { $new_template = locate_template( array( 'portfolio-page-template.php' ) ); if ( !empty( $new_template ) ) { return $new_template; } } return $template; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, templates, page template" }
Omit specific product categories from WooCommerce shortcode I _assumed_ this would be simple, but I'm having a hard time sorting it out. All I want to do is use the standard `[product_categories]` shortcode from WooCommerce to show all of my product categories _except_ for a few. Basically I have two types of categories: location based (basically sales lot inventory) and style based (different types of products), so I want to show a list of the _style_ categories (which could change or have additional styles added at some point) and leave out the locations, which are unlikely to change anytime soon. So therein lies the problem. I know I can use the shortcode to only display certain categories by slug or ID, but I'm hoping to avoid having to modify the short code every time we need to add a new style. If I could do something like `[product_categories category!="inventory1, inventory2, inventory3"]` that should fix my issue! Is this possible?
I submitted this question to the WooCommerce devs as well and they've officially confirmed it's not currently possible without modifying the shortcode. I will be submitting a feature request, though, so should anybody else find themselves in need of this, please track down that feature request and give it some props or submit it again on your own. I don't think the functionality should be difficult for them to include, so I would image it will have a decent likelihood of being adopted for a future release (if it gets enough steam, of course). I'm not sure exactly what kind of platform they're using for their feature requests, but I may come back and link it here if it's like a popularity- or vote-based system.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, woocommerce offtopic, shortcode" }
How to add a class to the <html> element? I'm using the X-Theme in Wordpress and I ran into an issue where I needed a CSS class in the `<html>` tag, but only on one page. This is the code I added into my child theme header file: <!-- If page#=103, add this class --> <?php if( is_page( 103 ) ) { ?> <html class="html-homepage"> <?php } ?> The code went into the _header.php file and appears to be working with no issues. My question is wondering if this method will break anything or if this is a super hacky way of doing this? I was unable to find a different solution that worked for me. It looks like since Wordpress is doing the processing, it should be fine, but I wanted to make sure that this won't interfere with other Wordpress functionality. Thanks! **Edit:** The code I added is in the child theme files, not the Wordpress core files.
Here is a way of adding the class. Replace `blog` withe the slug of the page. Example - This class will be added only on `example.com/blog`. Put this code in your `header.php` <?php if($post->post_name === 'blog'){ ?> <html class="html-homepage"> <?php } else { ?> <html> <?php ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "html, headers" }
Wordpress default audio playlist - how to add custom caption? The wordpress default audio playlist shows the caption of the media file in the list. Is there any way I can add custom title while creating playlist? I am using the same audio file in 2 playlists, and I need the playlists to display different captions for it. What can I do?
If I'm not mistaken, then you can't do that with the playlist shortcode by default. How often does this case happen? If it rarely happens, it might be easiest to upload the file a second time, and change the caption, information as needed. Create your own playlist shortcode code based on the default one found in `wp-includes/media.php`. As for the approach, for example, if custom shortcode attribute is present, then replace caption (title or whatever), secondary information can be saved in custom fields, else keep the default. You can deregister the default shortcode and then register your custom code to `[playlist]`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "audio, playlist" }
Dynamic image for Jumbotron on WordPress Custom Theme What is the correct process to make your jumbotron image dynamic (user changeable) via the WordPress customizer. Currently on my customers custom theme www.windupgram.co.uk I am using a static image, which I have to change when required. I would like to give the client an option to change the image whenever they want. Many thanks Andy
You can add support for the built-in Custom Header feature: < Or use the Customize API to add your own control to the Customizer for selecting the image: < The Custom Header feature is basically just a shortcut for using the Customize API to add a control, but you have less control over what the field is named etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, theme customizer" }
Make CSS Changes To Only Affect Mobile Browser Trying to make some CSS changes, that will only affect view on mobile phones. I made changes below, but it also affects desktop views. nav { margin-top: 140px; } & ownmenu { background-color: white; }
Try **media query** like @media only screen and (max-width: 768px) { /* For mobile phones: */ /* YOUR MOBILE STYLE HERE */ } Hope it will help!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, mobile" }
what is `get_section()` and how to use it? i saw `get_section()` being used in WordPress. what is this function and how can i utilize it for theme development?
If you check the code reference entry for `get_section()`, you can see its description: > Retrieve a customize section. "customize" means the customizer, the theme handbook has a complete chapter for using the customizer API, and one paragraph explaining sections: > Sections are UI containers for Customizer controls. While you can add custom controls to the core sections, if you have more than a few options you may want to add one or more custom sections. Use the `add_section` method of the WP_Customize_Manager object to add a new section:
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, theme development" }
Render the published date/time formatted in ISO 8601 using Timber (.twig) I am setting up Google Tag Manager's Data Layer and I have a .twig as my header file. I need to produce the date and time of the post in ISO 8601 format. "datePublished": "{{post.date}}" This produces the date but not in the right format. How do I format the date/Time to this standard? Thank you.
Thanks Kero, That was correct. Here is the final code that works "datePublished": "{{post.date|date('c')}}", Here is the link How to format a datetime object to ISO 8601 in Twig Thank you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "date time" }
How to add site logo to wordpress displayed on the top left of the site name on the chrome tab or any other web browser? I want my site to have logo like when i go to google.com it shows the google logo with google at the tabs on top of browser. How can I achieve this for my wordpress site ?
A favicon? You can set it in _Appearance > Customize > Site Identity > Site Icon_.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, logo" }
How to display author meta and count numbers for each user in comment.php? All users are registered to comment on the site, so what I want to achieve is, to display user details like the _meta info_ , _description_ , _url_ , etc... So, if possible also the number of posts and comments published in the `comment.php` template. Any help will be appreciated.
Getting user's metas values : $user_meta = get_user_meta($user_id, 'YOUR_META_KEY', TRUE); //You have to set the $user_id / And the "YOUR_META_KEY" can be description, name, custom meta... To get user's comments count function commentCount($userId = null) { global $wpdb; if($userId == null) return 0; $count = $wpdb->get_var(' SELECT COUNT(comment_ID) FROM ' . $wpdb->comments. ' WHERE user_id = "' . $userId . '"'); return (int)$count; } Finally, to get user's posts count $user_post_count = count_user_posts( $userId , 'post' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, theme development" }
Wordpress function, Run using Crontab I have disabled cronjobs on my nginx server, as it is better to run from crontab. define('DISABLE_WP_CRON', true); How could I run a custom wordpress function using Crontab, once per day? This thread seems to offer a solution but it is not explained well enough in my opinion and might pose a security risk: execute function in wordpress plugin using crontab On another note even if I disable WP_Cron, would `wp_schedule_single_event()` still work? As it would be easier to implement a solution this way.
define('DISABLE_WP_CRON', true); This line disables the **default** behaviour of WP Cron. Which is being triggered by a user that visits the site. This is bad for a couple of reasons (nobody might visit, tasks are started via apache handler instead of PHP CLI, ...). Now, if you have disabled it, you **need** another way to run WP Cron. Using crontab you could add an entry like so */5 * * * * php /absolute/path/to/wordpress_instance/wp-cron.php Now wp-cron.php will run every 5 minutes via PHP CLI. This way your scheduled tasks will still run. **If you disable the default cron and don't have an alternative as mentioned above, various WordPress functions may fail to execute!** * * * If you want to run a specific task once per day, you can `wp_schedule_event()` with the recurrence being `daily`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, wp cron, cron" }
How to run query inside a class with namespace? I tried to run a query inside a class this was the structure namespace NCK{ class Runquery{ public function execute(){ $query= new WP_Query(array(..............)); return $query; }}} But when i used $getvalue = new NCK\Runquery(); var_dump($getvalue->execute()); It throws an error > Fatal error: Uncaught Error: Class 'NCK\WP_Query' not found in is there any way i can make it works?
You need to add a `\` in front of the `WP_Query` call to tell PHP that it's in the global namespace and not the namespace of this class. Try this: `$query = new \WP_Query($args);`
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "wp query, oop" }
Gutenberg change/remove "Write your story" placeholder in custom blocks When created a new page or post or columns blocks we get the "Write your story" placeholder. Can this be removed or replaced, in custom blocks? How? ![enter image description here](
There does seem to be a filter to modify the default: < 'bodyPlaceholder' => apply_filters( 'write_your_story', __( 'Write your story', 'gutenberg' ), $post ), So you should be able to use the WordPress add_filter() function.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "block editor" }
How to check the terms in single custom post type template I have custom post type called **events** it has **event_type taxonomy** with two **terms namely past-events, upcoming-events**. I want to check my single post's term whether it's under past-events or upcoming-events Based on that i can display message. Thank you All
If I understand you correctly, then `has_term` should be solution for your problem... if ( has_term( 'past-events', 'event_type' ) ) { // do something }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, custom taxonomy, taxonomy, terms, single" }
How to change the link structure of the homepage? There are "your last posts" on the homepage. Under normal circumstances, the page proceeds as follows: < < e.t.c I want to change this link structure. For example, like < So I want to replace the term "Page" with something else or delete it completely. How do we edit a Wordpress blog perma link?
No need to change core files: add_action( 'init', 'wpse316713_pagination_base_rewrite_rule' ); function wpse316713_pagination_base_rewrite_rule() { global $wp_rewrite; $wp_rewrite->pagination_base = 'image'; } Go to permalink options page, and press save to flush the rewrite rules, changes should apply afterwards.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, blog, blog page" }
Home icon is not showing correctly using font awesome i have added this class in css classes `fa fa-lg fa-home` in appearance > menu >secondary menu home. but its icon is not showing correctly using font awesome, i want to show only icon instead of home text on both menus i.e primary top menu and secondary menu home button The page I need help with: <
This is because your the icon is being output outside of the anchors. To fix this issue, add another class, for example `my-class` to the menu classes. Now, try to position the icon absolutely, and fix the padding: .fa.my-class::before { position: absolute; left: 0; top: 50%; transform: translateY(-50%); } .fa.my-class { margin-left: 10px; padding-left: 10px; position: relative; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "fonts" }
I want to change the Wordpress comments file In the standard structure of Wordpress, a warning page appears when the user makes spam or goes too fast. The link structure of the warning page is "/wp-comments-post.php". Briefly (see images) < < I want to link this link structure to a special page like "error" to hide it. Or, I just want to make a little warning window inside the page. How can we do that Thank you in advance!
You can change the URL for the `action` of the comment form like this: add_filter( 'comment_form_defaults', 'wpse316762_comment_form_defaults' ); function wpse316762_comment_form_defaults( $defaults ) { $defaults[ 'action' ] = site_url( '/error.php' ); return $defaults; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, functions, comments, spam, comments template" }
How can I get all values from my array in a loop in php? I've following array: Array ( [0] => Array ( [0] => 585 [1] => 596 ) ) Now I want to print all values (585 & 595 .....) row for row in a loop. I need this an a loop because I need to to something with every value before the output. The problem is that I don't get all values, just one: foreach ( $entries as $entry ) { echo $entry[ 0 ]; } What am I doing wrong?
If all your entries are nested, then you need to run another loop inside your first loop, but I'd test it to see if it's an array and that it's not empty. foreach ( $entries as $entry ) { if ( is_array( $entry ) && !empty( $entry ) ) { foreach ( $entry as $sub_entry ) { echo $sub_entry; } } } I know there are other ways of being more complete about this, but this is the simplest answer I can think of off the top of my head.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, array" }
How to get time difference between publish date and now? I want to get time difference like "posted 2 days ago". I know you can use the following to get the difference. human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago'; But I don't want to use that date_default_timezone_set('Australia/Melbourne'); // set the time zone $timestamp = strtotime( $post->post_date ); // get timestamp $now = time();// get the curren time $time_passed = $timestamp - $now; // get the differnece // display time $min = $time_passed / 60; if( $min < 60 ) { return sprintf( avantgardia__( '%s min. ago', 'newspeak' ), intval( $min) ); }
Try the `date_diff()` / `DateTime::diff()` function in PHP: // Object-oriented style. $datetime1 = new DateTime( $post->post_date ); $datetime2 = new DateTime(); // current date $interval = $datetime1->diff( $datetime2 ); echo $interval->format( '%a days old' ); // .. or procedural style. $datetime1 = date_create( $post->post_date ); $datetime2 = date_create(); // current date $interval = date_diff( $datetime1, $datetime2 ); echo $interval->format( '%a days old' ); In PHP 5.2.2 or later, you can compare the date ("ago" vs "later") like so: if ( $datetime1 < $datetime2 ) { echo $interval->format( 'Published %a days ago.' ); } elseif ( $datetime1 > $datetime2 ) { echo $interval->format( 'Will be published in %a days later.' ); } else { echo 'Published today.'; } you can see the `$interval->format(...)` in <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "date time, timestamp" }
Create an article from another Java application I'm trying to find a way to create an article in a Wordpress portal using a Java application I developed. I have some clients that need to publish on this portal, but it should be something automated by this Java application. Is there any way (plugin or api) that I can send a JSON to the Wordpress portal (POST) and publish the article? I thought about creating, inside my Java application, a JSON and sending it to the Wordpress portal, something like: {"author": "John Doe", "title": "New article", "Content": "Lorem Ipsum ...", ...} How can I do this?
Yes, there is a REST API at `/wp-json` with core content endpoints for posts pages etc For example, my current latest blog post: < Is available via a `GET` request as a JSON object at: < And I can send a similar object via an authenticated `POST` request to create a new post to ` or a HTTP `UPDATE` or `DELETE` request. Note that WP includes an auth method out of the box that requires a nonce and a cookie of a user capable of creating posts in order to do this. For external applications, you will need a plugin to implement OAuth1/2 or another authentication scheme of your choosing
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts" }
How to show theme on front end before sign up for multisite I am working on new project which based on Wordpress Multisite I have done with the wp multisite set up and site creation functionality from front end. now what I need to do is to show the theme at front end to user and user will select the theme and after the theme select user will sign up and the new site is created with the theme active which the user select. Please provide and suggestion
Use below code to get the theme screen shot and theme name at front end for multi-site sign-up page. $themes = wp_get_themes(); foreach( $themes as $theme ){ echo '<b>Theme Name: </b>' . $theme -> name; echo '<div class="area"><img src="' . esc_url($theme->get_screenshot()) . '" /> </div>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
how to handle multiple forloop? I have and order_id as array but `wc_get_order` accepts only one id at a time how to loop through order_id and let the list of item id and item name? i am using this inside a class. it works fine if single id is passed as shown below public function getStuffDone() { order_id =array(358,368) $order = wc_get_order(358);//only single id is passed here $items = $order->get_items(); foreach ($order->get_items() as $item_key => $item_values): $item_id = $item_values->get_id(); $item_name = $item_values->get_name(); endforeach; return $item_name; } please help .thanks
You can do something like this public function getStuffDone() { $order_ids = array( 358,368 ); $items = array(); // contains the names foreach ( $order_ids as $order_id ) { $order = wc_get_order( $order_id ); foreach ( $order->get_items() as $item_values ) { $items[ $order_id ][] = $item_values->get_name(); // add the name to the array } } return $items; // array containing all the names }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "functions, loop" }
How to add rewrite rule to custom post type with parent in url with cpt ui? I'm trying to create custom post types but i need the posts of custom post type to have the url along with parent category. Example for now i have custom post types science, tech, business. The url of each post is mysite.com/science/postname. what i need is mysite.com/articles/science/post name. I tried giving articles/science in rewrite rule of cpt ui but it gives 404 error. Can you guys point me to right direction? Thank you
hierarchical must be set to true and make sure you have the Article post type set as the parent of the science post type ....and be sure to flush the permalinks after making changes
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, permalinks, url rewriting" }
Passing data outside of Wordpress possible? We're exploring some possibilities to upgrade our web development tools in using Wordpress, but we're concerned whether or not there is a good plug-in to build custom forms in WordPress and pass data outside of Wordpress?
I'm not an affiliate of Gravity Forms and I'm sorry if this offends someone, but based on my own custom form development experiences I can recommend it. Gravity Forms has very good API documentation that helps when customizing forms. For example on one site I used Advanced Custom Fields metafields as Gravity Forms radio field options. Gravity Forms also has different hooks you can use to manipulate form entries before/after the form/email notifications are saved/sent.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "api" }
Overwrite a file with the content of a textarea I’ve tried to solve my problem all day now and hopefully someone can help me here. This is my goal: Beeing able to edit and save files located in the uploads directory (for example wp-content/uploads/myplugin/style.css). I already managed to create a site with a textarea that contains the code from the style.css. I did it this way: <textarea><?php include([dynamic_path_to_file]) ?></textarea> This is working fine. I also managed to integrate the codemirror-editor which is looking and working really nice. Now I want to save the file after editing its content. How can I do that? I already tried some AJAX-Functions, for example as it is explained here: < I was also thinking of something like putting it in a form and send it somewhere on submit but I did not manage to get any good result. If you can help me with my problem you’d really make my day. Thank you in advance, Oliver!
I got answer to that question in the wordpress-support-forum: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How strip the quotation from the meta descrption? I checked the HTML validator. But, the message is the following. > Quote " in attribute name. Probable cause: Matching quote missing somewhere earlier. The meta description is automatic from the content. So, if the content includes the quotation, it is also included in meta descrption. I would like to strip the quotation. Currently, I inserted the code in header.php as below. $description = strip_shortcodes($description); $description = wp_strip_all_tags($description); What should I add?
Probably, it works for HTML5 Validator. > $description = str_replace(array("\r\n","\r","\n"," ",'"',"'"),'',$description); > > $description = strip_shortcodes($description); > > $description = wp_strip_all_tags($description); First quotation is removed, but second one is not removed, though.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "description" }
Is there a way to dynamically get URL as a path to plugin root, not a local path? Is there a way to get path to the root plugin folder as a remote URL instead of a local path. For Example: Instead of: `c:\xampp\htdocs\wordpress\wp-content\plugins\my_plugin\` I want to get: `localhost/wordpress/wp-content/plugins/my_plugin/` Is there a way to get the 'web' path instead of local one?
Check out the `plugins_url()` and `plugin_dir_url()` functions.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugins url" }
Mouse Wheel Anchor Scrolling on Wordpress I would like to implement the type of anchor scrolling as used on this site Oath on a Wordpress website. I have found a plugin that works when you click on the anchor links, but none so far that works with the mouse wheel or when you scroll back up. I need a code-snippet or Wordpress plugin that implements anchor-based mouse-wheel scrolling for scrolling up and down a Wordpress site.
If you're developing a custom theme, then you could perhaps take a look at pagePiling.js on GitHub. I bumped into this js library some time ago and I think you should be able to achieve the effect you've described with it. Some pagebuilder plugins might have a similiar feature incorporated in them, but I'm not quite sure. You have to do some research on this one yourself. But, if you're just looking for some copy-and-paste solution, then I'm afraid you might be out of luck. Unless you end up using that fullpane theme you linked on one of your comments.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins" }
Custom field metabox not showing in back-end I recently updated my website after a while, and the custom fields meta box is not showing in the editor anymore. It isn't showing under "Screen Options" either. Any ideas why this could be, and how to get it back? ![enter image description here](
It turns out the latest Advanced Custom Fields update (from version 5.6.0 on) removes the core custom fields metaboxes by default. The way to restore it was to add a filter in `functions.php`: add_filter('acf/settings/remove_wp_meta_box', '__return_false');
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "custom field, metabox, post meta" }
Default Wordpress menu content I have several menus in my theme, but if I don't create menu in dashboard, then in those menus is displayed default menu. How can I avoid that? I don't want any menu content until I create one. This is my code: <?php wp_nav_menu(array('theme_location' => 'main_menu_4', 'depth' => 1));?>
Use the `fallback_cb` argument of `wp_nav_menu()`: > _(callable|bool)_ If the menu doesn't exists, a callback function will fire. Default is 'wp_page_menu'. Set to false for no fallback. <?php wp_nav_menu( array( 'theme_location' => 'main_menu_4', 'fallback_cb' => false 'depth' => 1, ) ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus" }
Woocommerce remove menu item on myaccount dashboard I'm doing a redesign of the woocommerce dashboard. I had copy the dashboard.php from woocommerce folder to my theme folder. So now I want to get rid of the side menu from dashboard only(Remain on other pages eg. account detail page) ![enter image description here]( Tried this code in dashboard.php, doesn't work. add_filter ( 'woocommerce_account_menu_items', 'remove_my_account_links' ); function remove_my_account_links( $menu_links ){ unset( $menu_links['edit-address'] ); return $menu_links; } Understand this should be in function.php, but I only want to remove it from dashboard. How should I do that?
Thanks everyone I have solved this.. On myaccount.php remove do_action( 'woocommerce_account_navigation' ); also remove if you want your content to be on the center of pages <div class="woocommerce-MyAccount-content"></div> then, on my-order.php, edit-address.php etc add in above code in the correct position, then upload to your theme folder so any update of woocommerce won't override this change
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, woocommerce offtopic" }
Sidebar visibility in {WordPress template Hyerarchy, Newspaper Theme, TagDiv Composer} I have to admit that I often find Wordpress not so intuitive but let me explain what I mean in this specific case: The right sidebar is not whowed on the homepage? Why? How can it be? ![enter image description here]( But ok.. let me investigate.. ![enter image description here]( Does this means that PageBuilder delete the Widgetized Side Areas? And this is what happens if I try to add the Widget Sidebar (which makes no sense to me.. a sidebar shouldn't be related to the whole page?) ![enter image description here](
> The right sidebar is not whowed on the homepage? Why? How can it be? The theme author has opted not to include it in that template. It's that simple. > Does this means that PageBuilder delete the Widgetized Side Areas? Possibly. Although the theme might be responsible for this. You would need to ask the developers of each. > And this is what happens if I try to add the Widget Sidebar (which makes no sense to me.. a sidebar shouldn't be related to the whole page?) This appears to be a feature of your page builder, and something you should ask them about. Your issue here is ultimately how your _3rd-party_ theme and page builder have decided to handle sidebars. If the way they have change the default behaviour is confusing to you, all I can suggest is that you ask them for help. Since this is not standard WordPress behaviour, the broader community is unlikely to be much help.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
Different output from WP-CLI in bash vs PHP exec() I installed this package on WP-CLI. When I run `wp login create` in **bash** it works fine, but when I run `exec("wp login create")` in PHP script **WP-CLI** return this error: > Error: 'login' is not a registered wp command. See 'wp help' for available commands. > > Did you mean 'plugin'? I checked the user from `exec("whoami")` and it's the same. How can I find the problem? **EDIT** when I run `wp package list` in PHP it returns: > Error: Composer directory '/.wp-cli/packages' for packages couldn't be created: mkdir(): Permission denied
According to Alain Schlesser in wordpress slack: The folder that the packages are installed into is set to use your server user's home folder. When you try to execute this command from PHP, however, it is being executed by the webserver's user, which probably has a different home folder, and the package is not installed in there. You can either load the package manually as part of the system (requiring it in the site's Composer stack, for example), or set the package folder to a location that is shared by both your user and your webserver (and reinstall it afterwards). You can set the packages folder with the `WP_CLI_PACKAGES_DIR` environment variable: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, wp cli" }
Uninstall WP-CLI I have WP CLI installed on my server. Is there a command to uninstall the package? Here's where it's been installed on my server: ![Server Setup]( I'd rather uninstall the package vs using rm -r.
You can remove the `wp-cli.phar` file (and also the `.wp-cli` directory). I don't think there is an installation as such for you to un-install since typically you just download and move the wp-cli script to a directory such as `/usr/local/bin`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp cli" }