INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Display custom fields on post excerpt or teaser I have a custom Post Type I've created, and it also has some custom fields I created. For full disclosure, I used the Pods framework to do this. The Post Type can be tagged using a custom taxonomy. When I visit the tag page for a given term in the taxonomy, e.g. `mysite.com/my_taxonomy/term`, the posts of Post Type show up as expected in an excerpt / teaser type of display. What I would like to accomplish is to add my custom fields to this view. Right now the only field that shows up is the title, author, and date (there is no 'body' field). How can I add my custom fields to show up on this excerpt / teaser view of the content?
The way to retreive some meta data is knowing the name of the custom field, for my example I will use: listing, property and address; normally this can be done after **while (have_posts()) : the_post();** $listing = get_post_meta($post->ID, 'listing', true); $property = get_post_meta($post->ID, 'property', true); $address = get_post_meta($post->ID, 'address', true); then you can print the output like **echo $listing;** according your needs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom field, excerpt" }
How can I load 2 random pages? My problem is quite simple: I want to show a different page each time a visitor comes to my page. There are 2 pages for now, but it could be more. I have found this code: $rand = rand(1,2); switch($rand){ case 1: get_template_part('template1'); break; case 2: get_template_part('template2'); break; } but I don't want template parts, I really need to make it go through 2 (or more) complete pages I can define by URL or slug. Or it could be posts as well, as long as I can make them completely different (this is for multivariate testing of completely different pages which include some user interaction I want to measure) **How can I achieve this?**
You can redirect users from home page to random page with this code (paste it to your functions.php) function my_homepage_redirect() { if ( is_home() || is_front_page() ){ $page = get_posts( [ 'post_type' => 'post', 'posts_per_page' => 1, 'category' => 1, // your category ID 'orderby' => 'rand', 'fields' => 'ids' ] ); if ( empty( $page ) ){ return; } wp_redirect( get_permalink( $page[0] ) ); exit; } } add_action( 'template_redirect', 'my_homepage_redirect' ); If you want to pick random page OR random post, you can modify the 'post_type' parameter: `'post_type' => [ 'post', 'page' ],`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "page template, homepage" }
How to replace wp-admin login page to another location? // This will replace the login url add_filter( 'login_url', 'custom_login_url', 10, 2 ); function custom_login_url( $login_url=' $redirect=' ) { // Set your $login_page_id return get_permalink(207); }
if you dont want to add plugin * First of all, To be safe than sorry take a backup of wp-login.php and store in a safe place just in case of any wrong step. All you need is access to your site’s files and should have a text editor (I’m using VS Code). Now choose your ideal login UR, for example, /newlogin.php Go to your public_html directory where you can find wp-login.php. You can open it Once you find, Name this file whatever you want your login URL to be. In this case, I named it newlogin.php. Next, open up the newlogin.php and find and replace every instance of "wp-login.php" in the file – then replace it with your new file name as newlogin.php Now you should be able to log in by navigating to your new URL. In my case, it’s localhost/wp/newlogin.php. If any HTTP requests to the /wp-login.php, or /wp-admin directories will lead visitors to a 404 not-found page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, wp admin, login" }
How to Redirect huge numbers of URLs to another URLs? I am going to move from Blogger to WordPress and I also don't want to set earlier Blogger Permalink structure in WordPress. Now I want to know if there is any way to redirect URLs as mentioned below. Current (In Blogger): After (In WordPress): That means I want to remove my Blogger's year & month from URL from numbers of indexed URL and redirect them to WordPress generated new URLs.
If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod_rewrite could be used. This should be placed _before_ the existing WordPress directives in `.htaccess`: RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L] This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`. The `$1` in the _substitution_ is a backreference to the captured group in the `RewriteRule` _pattern_. ie. `(.+\.html)`. Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "htaccess, blog, blogger" }
Admin access to Wordpress site with installing plugin Third party Wordpress dashboard tools like ManageWP or InfiniteWP have access to entire Wordpress site by installing theirs plugin on that site. This way they have admin access to my Wordpress site so they can update plugins, do site backup etc. **How this is possible and is it safe?** I know that I can access Wordpress with XML-RPC but then I will need to supply administrator credentials.
It's safe if a) the management interface is only accessible by trusted users and b) there are no bugs. You can take care of a), but you'll have to trust them for b). How it's done: they send you to a special URL on your live site and pass a signature by which the plugin on the site can tell that this request has been triggered by the management interface, then set the same session cookies WP would set if you logged in regularly, and finally they'll simply redirect you to the admin dashboard.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "plugins, plugin development" }
Is it possible to select and edit the way the most recent post from a certain category is displayed on the page? To explain... I have a loop that is getting the posts from a few different categories and for one category, I want to change the link that gets wrapped around the title. For example: I have 3 posts from the category "Events", I want the first 2 Events posts to link to their specific page and I want the latest, event #3, to link to a different page on the website (NOT the individual post's page like event #1 & 2). So in the loop, I have something along the lines of: <a href="<?php echo get_permalink();?>"><h1>Title</h1></a> And I want to change switch 'echo get_permalink' to '/events/signup' the latest Events posting at the same time, keeping 'echo get_permalink' for all the other category posts in the loop. What's the best way to approach this?
You can retrieve the index of the post in the loop with `$wp_query->current_post`. From that, you can check with a simple if-statement: /*Check if post index is 2 (you referred to the 3rd post, given indexing starts from 0, the 3rd post index would be 2 */ if ( $wp_query->current_post == 2 ) : /* Do something */ else: /* Do something else */ endif;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, loop, links" }
How to dequeue theme's RTL stylesheet? I'm developing a plugin that has its own templates to render the page. This includes header, content, footer, etc. Therefore I have to dequeue every other style added by either theme or plugins, in order to keep the page clean. Right now I'm using this piece of code: add_action( 'wp_enqueue_scripts', 'remove_all_styles', 1000 ); function remove_all_styles() { global $wp_styles; $wp_styles->queue = array(); } It almost does what I want. This dequeues every CSS file, except the theme's `rtl.css`. I'm using the default Twenty Seventeen theme. How can I achieve this?
RTL stylesheet is not loaded with `wp_enqueue_style()` so it wouldn't appear in global `$wp_styles` variable. Wordpress loads it with `get_locale_stylesheet()` function. You can remove loading locale scripts completely: function abort_loading_rtl_stylesheet() { remove_action( 'wp_head', 'locale_stylesheet' ); } add_action( 'init', 'abort_loading_rtl_stylesheet' ); or filter its output to load your custom rtl stylesheet: function override_default_rtl_styles(){ return 'path/to/custom/rtl.css'; } add_filter( 'locale_stylesheet_uri', 'override_default_rtl_styles', 1000 ); I hope that's what you're looking for, cheers!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp enqueue style" }
Can i legally remove a credit from a free plugin on wordpress.org? I am using this accessibility plugin: < I didn't like to logo in the bottom of it that adds a link to the plugin site so I removed it via css. But I couldn't find anywhere any clarification on this, how the plugin is licensed, and can I just remove the logo without worrying of getting in trouble if I do it in my client's site?
That plugin is licensed under the GPL (GNU General Public License), so you can modify it as you please. You can even redistribute your modified version, as long as you do so under the GPL and adhere to its requirements. That said, even if it wasn't, I believe you would be allowed to add CSS, since you are not even modifying the plugin in any way. I personally would look for a way to actually remove that link from the output, though, not just via CSS.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, licensing, accessibility" }
WooCommerce doesn't show UK countries in the shipping options For some reasons, when I’m on the front-end, in the cart page, I cannot find any countries in the UK for the shipping estimation. No England, no Ireland, etc. But I got pretty much every other countries in the world. I haven’t put anywhere that I don’t want to ship to UK. The selling point is set to “Sell to all countries”. Other than that, is there any reason this can happen? I am using a plugin called “WooCommerce Shipping Per Product v2”, to handle shipping pricing per products, but the only thing I do is setting the price per regions, and I cannot modify regions in the system so, this shouldn’t be an issue. I know there's the WooCommerce plugin forum, but nobody is responding to my question there. I would really appreciate if someone here could help me with that issue. Thank you very much in advance
You won't be able to find England specifically in their list. The UK treats several areas as separate countries, and other regions can only be separated by postal code. * United Kingdom * Republic of Ireland * Jersey * Guernsey * Isle of Man < I should also mention that the "Sell to countries..." field controls the Billing side of the form. There is still an option of countries you "Ship to", and this alters the countries in the Shipping form (or the Billing form if you are shipping to the billing address). Make sure you haven't narrowed down that list without United Kingdom being list. And lastly, it is possible to modify the countries and regions through filters. Go to the General tab of your WooCommerce settings page and try to modify the Sell to or Ship to settings. If you cannot find the UK in that list either, then it's been removed through its filter.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, woocommerce offtopic" }
how to execute some code after a post is published in Wordpress I have written a simple code to do something after a post is updated or published (its related to the varnish purge). I put my code inside post.php file. Everything was just fine before the latest update (4.8.3), after that all my codes were vanished!! of course it is a normal behavior because the post.php file has been replaced with a new one from update patch. I want to know how can I execute some code after a post is updated or published and my codes do not disappear after a Wordpress update? I don't want to use plugins too :D. Thank you.
You're looking for the `save_post` action. This allows you to add a function when a post is saved (updated). You can hook into it like this: function your_save_post_function( $post_id ) { } add_action( 'save_post', 'your_save_post_function' ); Remember to not change WordPress Core files, as these will be overwritten when WordPress is updated. You can put this code in your `functions.php` file, or anywhere else in your theme folder.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts, actions, publish" }
Replace dynamically content in a custom database table when a custom post is created I use a third party plugin that saves events locations addresses as a custom _locations_ post type in a separate table - _wp_em_locations_. Because events are created by multiple authors, they write sometimes differently the name of the same town, using different languages. **How can I filter dynamically that names when the post is created and replace them with a default one?** For example, the Kiev town name can be written as Kiev, Киев, Kyiv and Київ, but I want to save only one of them. Town names are saved in the _location_town_ column.
This is something that creates one common question for all **SW engineers**. How you can do this “guide the user to select” and also “provide the capability” so the user can add their own data. Well, there is **not an easy way to do it**. You can try different technics like live searching, recommendation for the input and all short of miracles but the end result will always be dictated by the user. If you restricted to the user role if not high enough will be only allowed to add preexisting “towns” this can solve few miswrites but will have a significant drawback which is the review process or the request to add this user-defined inputs. I would suggest allowing the users input after the couldn’t find the “town from the list”. The “darker” path will be creating mapper for all towns and cross-checking to the user input.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, database, customization" }
Woocommerce: How to override core functions in functions.php? Is there a way to override woocommerce core functions in functions.php ? for example file location in: wp-content/plugins/woocommerce/includes/class-wc-order-item-shipping.php there is a following public function public function set_method_title( $value ) { $this->set_prop( 'name', wc_clean($value) ); $this->set_prop( 'method_title', wc_clean($value) ); } How to change it to this: public function set_method_title( $value ) { $this->set_prop( 'name', $value ); $this->set_prop( 'method_title', $value ); }
You can't replace just any plugin function with your own code, _unless_ : 1. The plugin is wrapped in a `function_exists()` check. This makes the function _pluggable_ , which means that if you define it first the plugin won't try to define it again, and yours will be used. This function is not pluggable. 2. There is a filter somewhere, indicated by the use of the `apply_filters()` function, that lets you replace a value. That value might be the output of a function, and by using the filter you could replace the output with your own. The specific function you identify does not have either, so cannot be replaced. I'd consider that WooCommerce probably has a very good reason for applying `wc_clean()` to these properties, and if it weren't there things might not function as expected, or it could pose a security risk.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "php, woocommerce offtopic" }
Why we use if with while loop? if(have_posts()): while(have_posts()): the_post(); the_content(); endwhile; endif; Without if condition this below code also works fine: while(have_posts()): the_post(); the_content(); endwhile; Thanks.
You only need the `if ( have_posts() ) :` if, as the name of the function suggets, you need to do something different if you don't have posts. This would be something like displaying a "No posts found." message. But you'd only need that on templates that _could_ show no posts, like archives and search. For single post and page templates the `if` is unnecessary.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "loop" }
Show this code if user has previously left a comment Below is my code which is inserted into the comment template, It should show the comment form, if the user has never posted a comment on a particular post. Or if they have posted a comment on this particular post, they should see a star rating selection. <?php if ( 1 < wp_count_comments( get_the_ID() )->approved ) : ?> <?php if(function_exists('the_ratings')) { the_ratings(); } ?> <?php else: ?> <?php comment_form(array('class_submit'=>'button')); ?> <?php endif; ?> The problem is its showing the ratings all the time and hiding the comment form all of the time. Is there a better way of accomplishing what I need ?
This will be the main code global $current_user, $post; $user_comment_count = get_comments(array('user_id' => $current_user->ID, 'post_id'=>$post->ID) ); if($user_comment_count) { the_ratings(); } else { comment_form(array('class_submit'=>'button')); } Also you may want to first check is the user is logged in with the `is_user_logged_in()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional content, comment form" }
db converts decimal number wrong Custom form is taking decimal but db inserts whole numbers but with a .0 behind. Why won't it give me the correct decimal number ? Db field fiske_vaegt DECIMAL( 2,1 ) NOT NULL, Form input field <p><input type="number" step="any" name="fiske_vaegt" id="fiske_vaegt" />kg</p> CHECK the fiske_vaegt field if i Input 2.4 it changes it to 2.0 and 2.7 to 3.0 ![enter image description here]( Anyone who have any experience with this goddamned problem? post if ( isset( $_POST['submit'] ) ){ $fiske_vaegt = $_POST['fiske_vaegt']; } insert $registrering = $wpdb->insert( $wpdb->prefix . 'registreringer', array( 'fiske_vaegt' => $fiske_vaegt ), array( '%d' ) );
Within `$wpdb->insert`, you are using `%d` which is used to store integer, use `%f` instead which will store float/decimal values. $registrering = $wpdb->insert( $wpdb->prefix . 'registreringer', array( 'fiske_vaegt' => $fiske_vaegt ), array( '%f' ) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php, database, forms" }
How to add data attribute to all images in posts I want to use his image zoom function on my wordpress site: Medium's Image Zoom in vanilla JS but I'm not sure how to add data-action="zoom" attribute to all images attached in posts. What function I need to use? Can somebody help me?
You have a number of options. You could use the `add_filter( 'the_content', 'add_data_attributes' );` And after that find the images attached to the post. Or you can use the `image_send_to_editor` filter more here.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images" }
Set the value of custom field when post is published or updated I'm trying to set the value of custom fields when a custom post type ('film') is published or updated. The end goal is to get meta-data from an API based on a URL field when the post is published or updated. I tried to use `add_action( 'save_post_film', 'get_film_data', 10, 2 );`, with the following function : function get_film_data( $post_id ) { // If this is just a revision, don't send the email. if ( wp_is_post_revision( $post_id ) ) return; $value = 'something'; // The value depends in fact on the value of another field update_post_meta($post_id, 'some_custom_field', $value); } This only works when a new post is created. The custom field's value is already set when the edit form opens. But for some reason it doesn't work once the post has been published. What am I doing wrong ?
It looks to me like `save_post` doesn't work the way you currently have your `add_action`. According to the Codex, you need to run your function on `save_post` and check the post type in the function. function get_film_data( $post_id ) { if ( get_post_type($post_id) == 'film' ) { // If this is just a revision, don't send the email. if ( wp_is_post_revision( $post_id ) ) return; $value = 'something'; // The value depends in fact on the value of another field update_post_meta($post_id, 'some_custom_field', $value); } } add_action( 'save_post', 'get_film_data', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "save post, post meta" }
Why is Heading tag Auto applied to Post data? why this heading tag is applied to my article, i mean instead of article showing in paragraph its showing in h4 tag because i applied it to date and it auto applied to my content too. echo '<h2>'.get_the_title().'</h2>'; echo '<h4>'.get_the_date().'<h4>'; echo'<br/>'; while(have_posts()): the_post(); the_content(); endwhile;
Your second h4 tag is again an opening tag. This echo '<h4>'.get_the_date().'<h4>'; should be this echo '<h4>'.get_the_date().'</h4>';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "tags, html5" }
Is there a way to get a file URL from the relationship ACF field? I have a relationship acf field that displays posts from a custom post type that are then displayed on the front end. The post type is publications and I want to link to the publications uploaded file as opposed to the single page link, how would I do this? Here is the code for the relationship field I have: $posts = get_sub_field('download_existing'); $existing_link_url = ''; foreach ((array)$posts as $link_posts) { $existing_link_url = get_permalink($link_posts->ID); } I know I am getting the posts permalink in the for each loop but I have tried wp_get_attachment_url and it doesn't seem to link through the file. Is it possible to do what I am trying to do, I have looked on the ACF website and searched for this but I can't find anything.
$posts = get_sub_field('download_existing'); $existing_link_url = ''; foreach ((array)$posts as $link_posts) { $existing_link_url = get_field("your_field",$link_posts->ID); } This will **overite** in the loop the **$existing_link_url** so you may want to save it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom field" }
Proper Way to Load stylesheet on Condition I am creating a child theme for my site and inside my functions.php I added a code to load a specific css file ONLY where it is the HOME page: // enqueue styles for child theme function wowdental_enqueue_styles() { // enqueue parent styles wp_enqueue_style('Divi', get_template_directory_uri() .'/style.css', get_the_time() ); // Flip3d css wp_enqueue_style( 'flip', get_stylesheet_directory_uri() . '/css/flip.css', get_the_time() ); // flip3d only on home page if( is_home() ) { wp_enqueue_style('flip'); } } add_action('wp_enqueue_scripts', 'wowdental_enqueue_styles'); I placed the condition for if is_home() but the stylesheet gets pulled in ALL pages regardless of whether home page or not. I have also used if (is_home() || is_front_page() ) but I get the same result. What am I doing wrong here??
You'll need to put the if statement around the line that enqueues in the first place. // enqueue styles for child theme function wowdental_enqueue_styles() { // enqueue parent styles wp_enqueue_style('Divi', get_template_directory_uri() .'/style.css', get_the_time() ); // Flip3d css // flip3d only on home page if( is_home() ) { wp_enqueue_style( 'flip', get_stylesheet_directory_uri() . '/css/flip.css', get_the_time() ); } } add_action('wp_enqueue_scripts', 'wowdental_enqueue_styles'); To do it like you have it in the original code, you'd need to use wp_register_style first, then keep the enqueue in the if.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, wp enqueue style, css" }
How to use different assets if local or live When building locally I want to use an unminified version of my JS. On the live site, I want to use the compiled and uglified version. In my theme, what's the best way to output the correct one?
WordPress has constants that can be defined in the wp-config.php. Have a read here Something like this might help //setup the production names for the files $js_file = 'scripts.min.js'; $css_file = 'styles-compressed.css'; //check for WP_DEBUG constant status if( defined( 'WP_DEBUG' ) && WP_DEBUG ) { //check for SCRIPT_DEBUG constant status if( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) { $js_file = 'scripts.js'; $css_file = 'styles-development.css'; } } //load the files wp_enqueue_script( 'plugin_scripts', $basepath . '/js/' . $js_file ); wp_enqueue_style( 'plugin_styles', $basepath . '/css/' . $css_file );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development" }
dynamic name of the style for wp_enqueue_style I want to use a variable inside the function wp_enqueue_style(), right now the only way i figure out to do so is to define a constant but it needs to be variable define( 'NAME', 'mystyle' ); wp_enqueue_style(NAME .'-style', ABS_URL . /includes/box.css' , false ); How could I add that variable to this function ? I tried this and it doesnt work, any insights on this? $name="mystyle"; wp_enqueue_style($name .'-style', ABS_URL . /includes/box.css' , false );
this syntax doesn't seem right to me. First of all what is `ABS_URL`? If it's a constant that you've defined earlier, then there is an `'` missing before `/includes/box.css'`. The code should look like this: $name = 'mystyle'; wp_enqueue_style( $name .'-style', ABS_URL . '/includes/box.css', false ); It works as it should, the output is: `<link rel='stylesheet' id='mystyle-style-css' href='whatever-there-is-in-ABS_URL-constant' type='text/css' media='all' />` Also, make sure if you need to define this constant at all - if you want to load stylesheet from your theme's folder or its subfolders, use `get_stylesheet_directory_uri()` function: $name = 'mystyle'; wp_enqueue_style( $name .'-style', esc_url( get_stylesheet_directory_uri() ) . '/includes/box.css' , false );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, functions, wp enqueue style" }
Allow user edit widgets I have user who can edit and delete posts. I want give him access to widgets too, but not to whole Appearance, like theme change, menu,... Is there some solution? Thanks and sorry if my english is not good.
The `edit_theme_options` capability controls access to the widgets page but also to the menus page. You can then remove the menus submenu from appearance for a specific role, and if someone tries to get there by url, redirect it : /** * Remove the "Menus" submenu from Appearance */ function remove_menus() { if (in_array('administrator', wp_get_current_user()->roles)) { remove_submenu_page('themes.php', 'nav-menus.php'); } } add_action('admin_menu', 'remove_menus'); /** * Redirect nav-menus.php to the dashboard */ function redirect_menus() { global $pagenow; if ($pagenow === 'nav-menus.php' && in_array('administrator', wp_get_current_user()->roles)) { wp_redirect(admin_url()); } } add_action('admin_init', 'redirect_menus'); Of course, replace the `administrator` role by the one you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles" }
How can i remove blank area caused by theme's post meta boxes? I have a problem with my theme's post screen metaboxes. When i add new portfolio items, there is some meta boxes which i dont need to use in my post screen. And if i leave them blank and publish the post, it leaves a blank area on the top of my page. And anything i place with visual composer stayes under of this blank area. How can i remove these empty area caused by these meta boxes? Thanks for your time.. ![Theme's meta boxes in my add portfolio post page ]( ![Blank area in my posts](
Here is few steps: 1. Right click on your area what you want to change/remove and inspect in console. 2. Find in console HTML part what you want change/remove 3. Look if have some ID or unique class. 4. If you find some unique ID or class, just simple add custom CSS in your template with property `display:none !important;` 5. If you not find any kind of unique ID or class, try to find some parent ID or class and find in CSS right route to your element you want remove/change and add CSS property to it. The worst thing you can do also is to go inside PHP and find that element and remove inside template or plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "metabox, post meta" }
Check if the value of a field has changed on save_post I have a custom post type where the user can set a video 'url' custom field. I need to download meta-data about the video (e.g. title, description, thumbnail) and store it along with the rest of the post's data. Since downloading this data can be a bit long, I'd like to do this only when it's necessary, i.e. when the 'url' field has changed. Is there a way to check whether a field's value has changed on `save_post` ?
Usually there is no way to check if the meta data is updated or not, but you can use `updated_postmeta` and `added_post_meta` to get kinda similar functionality. Please have a look at the below code- add_action( 'updated_postmeta', 'the_dramatist_updated_postmeta', 10, 4 ); add_action( 'added_post_meta', 'the_dramatist_updated_postmeta', 10, 4 ); function the_dramatist_updated_postmeta( $meta_id, $object_id, $meta_key, $meta_value ) { // check meta key with $meta_key parameter if ( 'your_meta_key' !== $meta_key ) { return; } // better check with the exiting data with the $meta_value to check if the data is updated or not. // then do what you want to do with the data } Hope this above helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom field, save post" }
How to compare a date in custom field with today's date in custom WP_Query? I have a list of competitions for which I set deadlines using Wordpress' built-in custom fields, in a YYYYMMDD format. I want to create a custom loop to display only the competitions that are now closed, meaning that their deadlines are older than today's date. I tried doing the following, but this displays all competitions, both open and closed: $args = array( 'meta_query' => array( 'key' => 'deadline', 'value' => date( 'Ymd' ), 'compare' => '=<', 'type' => 'DATE' ) ); $open_comps = new WP_Query( $args ); Any ideas?
Found the answer on my own. You also need to specify the 'meta_key' parameter in the query's arguments, like so: $args = array( 'meta_key' => 'deadline', 'meta_query' => array( 'key' => 'deadline', 'value' => date( 'Ymd' ), 'compare' => '>=', 'type' => 'DATE' ) ); $open_comps = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, custom field" }
What's the _wp_desired_post_slug value for? I'm trying to debug a 301 redirect that is causing me lots of trouble. I renamed a page from `/blog` to `/old-blog` and created a new page with the `/blog` slug. Now I'm getting 301 redirects from `/blog` to `/old-blog`. I already tried to look for the value in the `wp_postmeta` table with the `meta_key` `*_wp_old_slug*` but it isn't showing up. I did found 2 entries with the blog `meta_value` under the `*_wp_desired_post_slug*` meta_key. What are these values supposed to be for?
See this line in WordPress core. **Explanation:** When you move a post to the trash, `_wp_desired_post_slug` holds the slug that was desired for that post (now in the trash); i.e., when you move a post to the trash, WordPress suffixes the old slug so that it becomes available again, but it remembers the slug that you desired, just in case you decide to move it out of the trash and restore it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, redirect" }
Grandchild Term Things Grandfather Term is It's Parent I've got the following product categories: > Pricing Tagging > >> Monarch Supplies >> >>> Labels But when I do get_term( $labels_id ); It says that it's parent is the Pricing Tagging id, not Monarch Supplies. How can I get just the sub categories of pricing tagging excluding sub-sub-categories.
Use `get_terms()` and the `parent` argument. > 'parent' (int|string) Parent term ID to retrieve direct-child terms of. $parent_term_id = 123; $direct_child_terms = get_terms( array( 'taxonomy' => '[taxonomy]', 'parent' => $parent_term_id, ) ); Don't forget to replace `[taxonomy]` with whatever the taxonomy is; e.g., `post_tag`, `product_cat`, etc. _Additional arguments for further customizationhere._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, woocommerce offtopic, taxonomy" }
How to upload all media to one folder, with no year/month subfolders Prior to version 3.5 (or thereabouts), WP had a checkbox to select if all uploaded media went into sub-folders of /uploads, named by month and year. If checkbox was unchecked, all media ended up in one folder - no subfolders. How can I restore that feature? I.e., I want all my media to go into one folder and NOT be further divided into year and month. Is there some easy programmatic way to achieve that? Or is there some reliable plugin to do the job? Thanks!
Pop this tiny code snippet into a file located here: `wp-content/mu-plugins/upload-dir.php` (a must use plugin file). _Create the`mu-plugins` directory if it does not exist already._ <?php add_filter( 'pre_option_uploads_use_yearmonth_folders', '__return_zero'); What you're doing here is filtering an option value at runtime, which is picked up internally by `_wp_upload_dir()` and therefore uploads are no longer nested into date-based subdirectories.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "uploads" }
Wp Super Cache - Function to reset cache of a specific page I looked for a solutin like more than hour, but not chance. There is a function to reset cache of a specific page manually? I'm using wp super cache. I'm updating some posts meta values using API, and I want when I update something, I reset the cache of this page only. There is a function for that? Thanks
The function you're looking for is `wpsc_delete_post_cache()` $post_id = 123; wpsc_delete_post_cache($post_id);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "codex, plugin wp supercache" }
Debugging slow Wordpress Theme Customizer (Any option similar to Query Monitor)? Just wondering what people use for debugging in the customizer? I use BugFu, Debug Bar and Query Monitor along with Simply Hooks for theme development, but only Bugfu works in customizer and that is not the kind of debugging I need to do. I tried using this plugin: Customizer Dev Tools however, it does not seem to work with the current version of Wordpress. I am new to theme development, and I have jumped into developing a child theme using the Theme Customizer.
It turns out Query Monitor is, in fact, present in Customizer view. For some reason, I never once scrolled down to the bottom (or just didn't pay attention). Just the debug/admin bar is not visible. Also, you can do this to get the admin bar in theme customizer: add_filter('show_admin_bar', '__return_true'); Source Another useful tool is WP Customizer Dev Tools (at this writing, it's only upgraded for up to WP 4.9 on the Git branch. The wordpress.org plugin is outdated) Keep in mind, Debug Bar and Query Monitor especially can slow down the Theme Customizer tremendously.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, child theme, theme customizer" }
Wordpress Redirects When a Query String Contains a Number I have a URL query string containing a number and it redirects and gives a 404 error as the page does not exist. If I change the value of the parameter to characters it works. I'm guessing it's something to do with wordpress pagenation. Examples < 'redirects 404 error < 'does not redirect - works as required I need to pass the number variable to the page. It comes from a standard NTAG feature on smartcards that automatically appends the card serial number to the URL so I don't have many options to change the URL appearance. (the code on the landing page is not correct, but I will fix that once the parameter is passed)
`m` is the built-in query var for year/month, see Reserved Terms for a list of query string vars that you should avoid.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "url rewriting, query" }
shortcode - multiple instances of same parameter name in one shortcode instance I'm looking to include a shortcode that builds a table of items and groups of items. For this I wish to be able to include an attribute multiple times or chain them together in some way. An example is I would like to do something like this: [testcode item="item1" group="group1" item="item2" item="item3" group="group2"] alternatively something like this could work: [testcode item="item1"&group="group1"&item="item2"&item="item3"&group="group2"] The order the parameters appear must be maintained and multiple entries must be allowed. Any suggestions on how to accomplish this without writing completely custom shortcode handler routines? An array does not seem to maintain the order between items and groups and associative arrays do not seem to be allowed in shortcodes. What I'm looking for is identifying and maintaining item1,group1,item2,item3,group2 order when I process it.
Shortcodes are intended to be used by humans, to be some kind of macro that even the most techno-phobic author can use. If you need to have arrays of attributes, or any other complex structure for which the author has to attend CS 101 in order to understand its use, your shortcode is just a fail. If you need a shortcode with complex data, the more sane way to do it is by separating the placement and the actual data input. Create a meta box section in which users can have a nice UI in inputting the data, and use `[myshortcode]` in the text just as an indication where that data should be displayed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, shortcode, customization, parameter" }
Embedded pages by ID are not respecting Private and Draft status Have an issue where I have a series of pages loaded into a websites index using code shown bellow: <?php $id = 1767; $p = get_page($id); echo apply_filters('the_content', $p->post_content); ?> But the information from these pages are not respecting Private and Draft status. Normally this is fine with me. But a couple of them are either to me scheduled updates. But no matter what the pages status is it's visible to an unlogged in reader of the page in all browsers I've tried. I have done some reading about the `page_status` code but I'm too much of a layman to work out how to get it to work. Help and advice most welcome. Thanks Ok thanks Piyush Rawat. I implemented the follow. Works correctly as far as I can tell. <?php $id = 2841; $p = get_page($id); if ( get_post_status ( $id ) == 'publish' ) { echo apply_filters('the_content', $p->post_content); } ?>
You can use the get_page() to get the current status and do something based on its output. $id = YOUR_ID; $p = get_page($id); $status = $p->post_status; if($status == 'publish'){ //Do something }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Problem with Woocommerce REST API Authentication I am using the postman for the check the REST API Call in WooCommerce. When I call the Woocommerce Defaults API. It displays the error like. { "code": "woocommerce_rest_cannot_create", "message": "Sorry, you are not allowed to create resources.", "data": { "status": 401 } } The above error displays when the Basic Authentication and POST method of Create Customers API. And when I am Trying to Call the Display products API with the cURL Using the GET Methods from postman it will display the following error. { "code": "woocommerce_rest_cannot_view", "message": "Sorry, you cannot list resources.", "data": { "status": 401 } } It would be great if anyone saving me from this headache. Thanks..
I got the solution for it. Use the Basic Authentication from the Postman. Thanks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "php, woocommerce offtopic, rest api" }
How to use index.php as a template for archives? My archive pages are very much like my home page, except of course for the posts that are loaded. But design-wise, they're practically identical. So I would like to use index.php for both my homepage and my archive pages. How do I do that? I know I could copy the code in `index.php`, paste it in `archive.php` and use `/* Template Name: Archive */` but I'd rather use one file so that if I need to change something, I can change it in one place only. I also know (or at least, I think), if there's no `archive.php` Wordpress will automatically look for `index.php`, but the problem is I'm in a child theme, so it will go looking for the parent theme's `archive.php`, which is not okay because I do have and need an `archive.php` there. So how can I explicitly tell Wordpress to look for `index.php` when an archive page is requested?
I haven't tested this but in your archive.php file in the child theme use the following command to output the index.php file contents. <?php get_template_part( 'index' ); ?> This way you can have all the code in your index.php file but use it elsewhere preventing the duplication. If you don't want to create an archive.php file then use this filter. add_filter( 'template_include', 'archive_home_page_template', 99 ); function archive_home_page_template( $template ) { if ( is_archive() OR is_front_page() ) { $new_template = locate_template( array( 'index.php' ) ); if ( '' != $new_template ) { return $new_template; } } return $template; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates, archives" }
How to pass user meta_key and meta_value (values as array) I want to pass user meta_key to meta_value, but the meta_value array is like this: $user_biodata = array( 'register_facebook_id' => 1311064406686333, ); I want check if user is already registered through this function; $wp_users = get_users(array( 'number' => 1, 'count_total' => false, 'fields' => 'id', 'meta_query' => array( array( 'meta_key' => 'user_biodata', 'meta_value' => array( 'register_facebook_id' => 1311064406686333 ), ) ), )); But the result is always 1 even when the value not exist, how do I fix it?
What you are doing is not a valid way of retrieving and checking serialize data from the WP. You may insert array as a user meta but this array behind the scenes is transformed to serialize string something the MySql can handle. There are options for searching with the LIKE operator but I don't endorse this use as it can lead to unexpected results. $args = array( 'number' => 1, 'count_total' => false, 'fields' => 'ID', 'meta_query' => array( array( 'key' => 'user_biodata', 'value' => 'yourValue', 'compare' => 'LIKE', ), ), ); $users = get_users($args);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "meta query, user meta, users" }
How do I display the taxonomy for a custom post type in an array I am trying to display the terms from a taxonomy on my archive page but I am struggling to display the terms name, here is what I have so far: if ($post->post_type == 'cpt_saving') { $categories = get_the_terms($post->ID, 'cpt_saving-type'); if ($categories) { $categories['name']; } $stack = [ 'title' => get_field('savings_headline', $post_id), 'image' => get_field('savings_supplier_logo', $post_id), 'reference' => get_field('savings_reference', $post_id), 'date' => get_the_date('l j F Y'), 'link' => get_the_permalink(), 'term' => $categories->name, ]; get_template_partial('partials/savings/savings-item', $stack); } As I have $stack as my array how would I call the taxonomy terms name to display it on the front end?
I was able to display the taxonomy term for each post using the following: $savings_terms = get_the_term_list($post->ID, 'cpt_saving-type'); $stack = [ 'term' => strip_tags($savings_terms), ]; This output the current term for each post and doesn't throw an error when a post doesn't have a term assigned to it, it worked best for my situation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, custom taxonomy, taxonomy, terms" }
post_thumbnail_html only for specific thumb size I'v created a custom thumbnail size (in my function.php) called 'thumb-bookmark' and wanted to add a permalink to all of them but I don't know how to target only this specific size with this code: function thumb_bookmark_html( $html, $post_id, $post_image_id, $size ) { $html = '<a class="MyClass" href="' . get_permalink( $post_id ) . '" alt="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>'; return $html; } add_filter( 'post_thumbnail_html', 'thumb_bookmark_html', 10, 3 ); I've tried to add something like $size = get_the_post_thumbnail('thumb-bookmark'); but, as I'm a ~~noob~~ beginner with php, it doens't worked of course :p I've been searching on Google for hours without successs so any help will be much apreciate :) Thanks
You're getting the size as the `$size` as the 4th argument of your callback function. You just need to use an if statement to check it: function thumb_bookmark_html( $html, $post_id, $post_image_id, $size ) { if ( $size === 'thumb-bookmark' ) { $html = '<a class="MyClass" href="' . get_permalink( $post_id ) . '" alt="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>'; } return $html; } add_filter( 'post_thumbnail_html', 'thumb_bookmark_html', 10, 4 ); Also note that I changed `3` to `4` in the `add_filter()` function. This ensures that I get all 4 arguments in the callback function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "post thumbnails" }
WordPress Scheduled Event Request Blocking This is a question about WordPress architecture, that I wasn't able to fully understand by reading WordPress documentation. I have a scheduled event that can take more than 1 minute to finish because it's a heavy stored procedure that create a few caches on my database. As far as I know, scheduled events in WordPress (`wp_schedule_event`) are triggered only when a request is made on the website. So, I imagine that if I schedule this event to run every day at 3:00 AM (which is the less crowded hour of my website) it'll trigger after 3:00 AM on the first request and it can happen a few minutes after this time if nobody is visiting it. Am I right? Still, if I'm right, let's say a user opens my website at 3:01 AM and it triggers my scheduled event... will this user have to wait 1 minute until it ends so the website is loaded? Or this scheduled event happens in a thread?
Yes, WP Cron won't run if nobody visits your site. You can also run into the PHP execution time limits There are ways to mitigate this however: * Manually ping the cron URLs via a real cron job using curl * Run cron via WP CLI on a real cron job, letting cron jobs run arbitrarily * Use a job manager plugin such as cavalcade to manage cron tasks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, plugin development, database, events" }
Hide/Show content based on cookie I have code to add a cookie to a page, it is very simple: function setup_user() { if (is_page(21)) { setcookie("user_type", "advanced", time()+157680000); } } add_action( 'get_header', 'setup_user'); if the user goes to a certain page, they are an advanced user and do not need to see basic help items. So now I want to hide some content on some pages. I currently use the Quotes plugin to manage the content that should be shown/hidden. I know I can add conditional logic: if(!isset($_COOKIE["user_type"])) { // then the content should not show. } How can I check that cookie, and based on it show/hide content on any page of the site?
An idea is to use some CSS if you want to apply this logic to many elements on different pages. You can add this code to `header.php` for example : if(!isset($_COOKIE["user_type"])) { <style>.hide_content {display:none!important}</style> } Then you can simply add the CSS class to all elements you want to hide when cookies are set.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "cookies" }
How to use REST API to send user metadata? I'm developing a Wordpress 4.8 site using Angular in a custom theme and needing to save data from my registration Angular model to the Wordpress API for server side storage in the database. All of the forms, routes and user interface is built within the Angular 5 theme I'm creating. I'm at the point where I need to send data to the WP REST API but need guidance in terms of which endpoint(s) to use for proper storage of this custom data? Fields are over and above typical user metadata and will also need to know which endpoint to use in sending payment data through the REST API. Should custom endpoints be created to handle the registration and payment processes? If so, does Wordpress have a designated database table structure and the ability to extend the API to handle these use cases?
_I'm not a WP API expert._ It sounds like you want to store more information than the API supports, so you will need to add an endpoint - < If you are doing payment processing, I assume you are using a service or plugin + service for that, so you may want your custom endpoints to interact with those DB structures that the plugin creates. (maybe you are using < for instance?) In addition to that, you probably want to update something else on your site, like what they purchased, or what abilities they have now that they have purchased it. So that might mean more endpoints and more DB structures. \-- Wordpress does not have API endpoints that save/load data (like parse or something would.) So you would need to create that by hand.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rest api" }
How to add new page to wordpress theme through coding? I am developing a WordPress theme and my theme contains multiple pages. I have added the static pages as templates and I know that in order to import these templates I have to go to the admin panel and using the Pages -> Add New option I can import the template. But I don't want my client to undergo this tiresome process. Instead, I want to do some coding so that the pages are automatically created. I guess I have to add some code in `functions.php`. Please advise.
> If you are creating a new theme either for sale of for a client you may want to have it create a custom page or pages when the theme is activated. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development" }
Admin Login Checks Where does WordPress perform the check as to whether or not a user is logged in when aaccessing admin? i.e. When I access /wp-admin/edit.php, if I am not logged in I am redirected to the login page - where (which file) is that process taking place?
It begins on this line in the `admin.php` file, which is a part of all admin-related backend pages in WordPress. That line calls upon the `auth_redirect` function, which handles the redirection.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, admin, login" }
Avoid taxonomy-%term%.php if more than one taxonomy I have a site with multiple custom taxonomies which are used for filtering posts. One of the taxonomies has a `taxonomy-%term%.php` template file. `/?country=the_country` shows the country taxonomy template but `/?topic=the_topic&country=the_country` uses the country taxonomy template as well. Is there a simple way to avoid loading the `taxonomy-country.php` template if more than one taxonomy is being queried?
The solution here was found by (as jaswrks has mentioned) removing the `taxonomy-country.php` file entirely. The contents of `taxonomy-country.php` are then loaded conditionally within taxonomy.php Custom post_types & taxonomies have an option to "rewrite" the urls. In this case, the same url parameters that are filtering the taxonomy archives were sometimes colliding with this url-schema and causing unwanted results. The simple answer would be to disable rewriting the urls of the problem taxonomies. But a cleaner option turned out to be to remove_filter( 'template_redirect', 'redirect_canonical' ); ... which can be used to disable the `rewrite` attribute from custom post_types or taxonomies
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, templates, template hierarchy" }
How to place script in footer? I have a script I want to place in my site's footer. It's not actually a file, just a single line of code (the script source is located at an external URL). So my question is, should I enqueue the script or just copy and paste it into the footer?
If you want to output a single line of javascript, you might not need to put it in a js file and go through enqueuing it and stuff. Simply output it by using the `wp_footer()` action hook: add_action('wp_footer','print_my_script'); function print_my_script(){ echo '<script> // Your script here </script>'; } However, this is good just for small scripts. For larger script and js files, use `wp_enqueue_script()` instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "javascript, wp enqueue script, footer" }
Confused over wp-config.php and 'database user + database password + name' I have a domain with a subdomain. Each of those has a different install of WordPress. When I created the databases I made the following: Main Domain = database called: maindomain Sub Domain = database called: subdomain I applied the SAME database username to both databases.... So all nice and simple.... However, why is the Database Password the same? /** MySQL database password */ define('DB_PASSWORD', 'passwordhere'); When I reset the password for the database username (which I had forgotten) it made my main domain crash? So I guess my question is - have I just merged two databases together? Is that even possible? Hope thats clear!
> I applied the SAME database username to both databases > > Why is the Database password the same? > > When I reset the password for the database username it made my main domain crash? It sounds like you created a single MySQL user which is allowed to access both `maindomain` and `subdomain` databases. When you change the MySQL user password, you need to update the password in any `wp-config.php` files where that user is set. > Have I just merged two databases together? Is that even possible? Based on your description, it sounds like you just need to update the password in the `wp-config.php` on your `maindomain` site. It is possible to make your `maindomain` and `subdomain` sites point to the same database but you would do that by setting the `DB_NAME` define and `$table_prefix` variable exactly the same.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, wp config" }
Redirect user if it's not logged in can you help me with little problem. I need to find a solution, how to redirect user to login page when he wants to download file over link in post content, so, I have some files and I want them to be available only for users that are logged in, otherwise they should be redirected on login page, for example I want to forbid access (download) for all files from wp-content folder, keep in mind that I have several of those folders in the root, I tried with `.htaccess` file file but its not working RewriteEngine On RewriteCond %{HTTP_REFERER} !^ [NC] RewriteCond %{REQUEST_URI} !hotlink\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov) [NC] RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC] RewriteRule .*\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov)$ [NC]
Thanks to Marcelo Henriques answer i figured out how to make this work with `.htaccess` file and here is the code: RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} ^.*(mp3|m4a|pdf|doc|xlsx|docx|xls)$ RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC] RewriteRule (.*) place .htaccess file in folder you want to protect from non registered users and it will do the job, last line is redirect. So, if you want to protect file access over anchor link, from specific folder (uploads/media) make .htaccess file inside folder and paste this code. If you want just `403`(forbiden) change `RewriteRule (.*) with `[R=403,L]`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "permalinks, htaccess, links" }
Theme showing incorrect update We have a totally custom theme that we have built in house, recently the WordPress updater has started saying the theme is out of date. ![Update suggestion]( When I investigated this supposed update it links me to a similarly named theme in the WordPress theme directory but one that is not developed by us. ![Theme]( We normally update our themes manually either through the filesystem or FTP. We have never submitted our theme to the WordPress directory nor do we have a mechanism or infrastructure to allow our themes to "phone home" to check for updates. What is going on here? How do I stop it misreporting the theme update? I really want to stop this behaviour to prevent an over eager customer trying to update the theme to this one and breaking their site.
When it comes to developing your own stuff, it is always the best to make the code yours too, not just the copyright and such. As @Rarst already pointed out, the first thing to check if the theme's folder. I faced the same issue before and changing the theme's folder fixed the issue for me. But for future goods, you should start prefixing your code. It means that you should prefix your theme's name, functions, classes, etc ... by your or your company's name. It's less likely if someone ever will publish a theme named `burgi-professional`, but a general name such as `professional` may exist anytime. This also applies to class names and functions to. Prefix your functions like this: function burgi_get_theme_options( ){ ... } So there is a lower chance of running into such issues. Same goes for CSS classes, and HTML ID attributes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, updates" }
Add the ability of changing background color of a theme I am trying to teach myself developing wp themes and I am wondering how I can add the ability of changing the **header background color** at customize section of the theme. Details: I have started with _underscore and I notice that there is no color setting for background of the header section. There is a "Color" section that allows me to change the text color of the header but there is no option for the background color or the headers.
You can start off by studying about Theme_Customization_API here. For your specific problem follow this link.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "theme development" }
Custom post meta box as a sub form I have a custom post type with meta boxes existing already. I'm in need of a feature which would be called a sub-form in the MS Access word. It's section 2 in the below image: ![enter image description here]( I have one row of post meta fields already, and I need a way to allow the user to add as many "rows" of those fields as they want: ![enter image description here]( I could hack together some javascript which changes the name attribute of those fields, and add some previous and next arrows, but I hope something is readily available.
What I ended up doing is not worrying about reloading the page. I have one row of `input` tags, with a `select` tag on top that I use to navigate rows. On change, the page reloads. Server side, the select box acts as an index for the `input` tag names and post meta.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp admin, post meta" }
How to prevent plugins from being uninstalled The following filter works great for preventing plugins from being deactivated... `add_filter( 'plugin_action_links', 'disable_plugin_deactivation', 10, 4 )`; with... // array_key_exists( 'edit', $actions )... // array_key_exists( 'deactivate', $actions )... ...But is there a similar filter or array_key, that prevents plugins from displaying their uninstall link on the plugins.php file? Thanks
Yes, you can use the same filter, just remove the `delete` key of the $actions array. If you want to remove the "delete" link for the plugin "myplugin", you'd go for something like this: add_filter("plugin_action_links", function($actions, $plugin_file, $plugin_data, $context) { if($plugin_file == "myplugin/myplugin.php") { unset($actions["delete"]); } return $actions; }, 10, 4); Obviously, you cannot put this into the plugin itself, since it will have been deactivated or the delete link will not show up (link to deactivate the plugin will be in its place). Also, be aware that this will only remove the link, it will not stop a determined user with the appropriate privileges from sending that request manually.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permissions" }
Is it possible to change a term slug before being saved to the database? We have a situation where we need to be able to do some categorization like this: Root Category |-- Child Category |-- **Non-Unique Category** Next Category |-- Next Level |-- **Non-Unique Category** Another Category |-- **Non-Unique Category** The problem we have found when creating categories is that the Slugs are unique. In our use-case, the slug doesn't get used in a URL so it could be a GUID for all we care, according to WordPress it just has to be unique. If the slug is not unique WordPress throws an error saying that same name exists already. **How can we use a filter/action to change the term slug value before it commits to the database?** **Bonus** : Can this be done with Custom taxonomies as well as builtins?
You can use the `pre_insert_term` filter to do just this <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, categories, customization" }
How do I skip wordpress's 404 handling? I want to extend my website in a way that is parallel to the wordpress theme. Example: My website with wordpress is at: `www.mywebsite.com` By ftp I added a directory named `test`, in which there is a php file `test.php` The problem is that if I write in the url: `www.mywebsite.com/test/test.php` it redirects me to the "page not found" of my theme. How can I deactivate this behavior? Posting .htaccess: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # # av:php5-engine AddHandler av-php5 .php # # av:Toolbar SetEnv AV_TOOLBAR 1
Native WordPress rules are designed to ignore any existing files and directories, including arbitrary PHP scripts. This is literally what this part of directives mean: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d So under normal circumstances WP just shouldn't be involved with your request in any way. You may have some other rewrite rules interfering, possibly from a different place in web server configuration.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "redirect, htaccess, 404 error" }
Hook on slug generator I'd like to change the slug that is automatically generated when creating a post. ![enter image description here]( I'd like to add a meta before, making a thing like [meta]-test-slug-2 I guess there's a hook on when WP automatically creates a slug, and if I could find it, I could inject that meta before the title when creating the slug. So is there a hook that exists? If so, how can I use it?
I think you should be able to do this using the `wp_unique_post_slug` filter (which is applied in the function of the same name): add_filter("wp_unique_post_slug", function($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) { if($meta = get_post_meta($post_ID, "my-meta", true)) { $slug = $meta . '-' . $slug; } return $slug; }, 10, 6); As this is applied at the end of that function and I believe WP expects and relies upon that slug to be unique, you will have to make sure that it is. I believe that it will be generated (and saved) as the post is published, so you'll have to have your meta values ready by then.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "slug" }
Difference between `is_serialized_string` and `is_serialized` I have read the codex, but it is not quite clear to me: what's difference between is_serialized and is_serialized_string and
If you check the source code of `is_serialized()` and `is_serialized_string()`, the difference will become clear. `is_serialized()` checks if the data is serialized, whereas `is_serialized_string()` checks, if the serialized data is of type string. var_dump( is_serialized( serialize(NULL) ) ); // true var_dump( is_serialized_string( serialize(NULL) ) ); // false var_dump( is_serialized( serialize(array(1,2,3)) ) ); // true var_dump( is_serialized_string( serialize(array(1,2,3)) ) ); // false var_dump( is_serialized( serialize("hello") ) ); // true var_dump( is_serialized_string( serialize("hello") ) ); // true (fiddle)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "codex" }
filter a list by gender I am very new to WordPress and I want to filter a list by gender. Selecting a male option should filter the list to show only males with the relative information. How can I achieve that? $list = array( (object) array( 'name' => 'John', 'gender' => 'male', 'job' => 'Farmer' ), (object) array( 'name' => 'Paul', 'gender' => 'male', 'job' => 'Blacksmith' ), (object) array( 'name' => 'Adam', 'gender' => 'male', 'job' => '' ), (object) array( 'name' => 'Mike', 'gender' => 'male', 'job' => '' ), (object) array( 'name' => 'Jane', 'gender' => 'female', 'job' => 'Baker' ), (object) array( 'name' => 'Jill', 'gender' => 'female', 'job' => 'Farmer' ), );
There is a convenient helper function in WP core called `wp_list_filter()`. Easy as: $male = wp_list_filter( $list, [ 'gender' => 'male' ] );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "filters" }
How to return a foreach inside a shortcode I have the following code function stock_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); return '<table class="table"> <thead> <tr> <th> Title </th> <th>Content</th> <th>Date</th> </tr> </thead> <tbody> '. foreach($days as $day){.' <tr> <td>'.$day[0].'</td> <td>'.$day[1].'</td> <td>'.$day[2].'</td> </tr> '. }.' </tbody> </table>' ; } How to I assign it to a shortcode? If I write `foreach` inside the `return` method I get an error.
As I said in the comment you can use buffering like this function stock_agenda() { $days = json_decode(file_get_contents('json_file')); unset($days[0]); ob_start(); // start buffer ?> <table class="table"> <thead> <tr> <th> Title </th> <th>Content</th> <th>Date</th> </tr> </thead> <tbody> <?php foreach($days as $day) { ?> <tr> <td><?php echo $day[0]; ?></td> <td><?php echo $day[1]; ?></td> <td><?php echo $day[2]; ?></td> </tr> <?php } ?> </tbody> </table> <?php $output = ob_get_clean(); // set the buffer data to variable and clean the buffer return $output; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, shortcode" }
How to create URL parameters to run custom queries? I'd like to filter by Custom Fields, my goal is to have links with url parameters like: domain.com/?custom_field=white I think i can create the custom query by tweaking this examples: < But how can i put all together in a site plugin or functions.php so when someone clicks my URL parameter it actually runs my query? I can't seem to find the answer to that step.
What you want to do is access the query_vars and use them. Base code: **Page to access the fields** $custom_field = get_query_var('custom_field'); var_dump($custom_field); And the function or custom plugin to save the magic: add_filter( 'query_vars', 'my_custom_query_vars' ); function my_custom_query_vars( $vars ) { $vars[] = 'custom_field'; $vars[] = 'custom_awesome_field'; return $vars; } > yourawesomesite.awesome/?custom_field=white string 'white' (length=5)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, custom field" }
Don't allow JavaScript in the content area Is there any way to disable or remove JavaScript in the page/post content area? So if there was any `<script>` tags it would remove them or ignore them when outputting `the_content();`
You could use the_content filter: add_filter( 'the_content', 'remove_script_tag' ); function remove_script_tag( $content ) { return strip_tags( $content, '<script>' ); } When you also want the content of the tag to be removed you could use this one: add_filter( 'the_content', 'remove_script_tag_and_content' ); function remove_script_tag_and_content( $content ) { $striped_text = preg_replace('@<script>.*?<\/script>@si', '', $content); return $striped_text; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "javascript, the content" }
ACF: using two loops, the_field returns field content from another loop Essentially on my single.php file, I'm querying the current post directly into the template, while having also having a related posts section. The issue is that when ACF tries to retrieve the field of the post inside the related post query loop, it retrieves the current displayed post instead. while(have_posts()){ the_post(); echo the_field('field1'); echo the_field('field2'); echo the_field('field3'); } $recent_posts = wp_get_recent_posts(); foreach( $recent_posts as $recent ){ ?> <img src="<?php echo the_field('field1')?>"> <?php echo the_title(); } So essentially it grabs field1 from the current post instead of the recent_posts query. I've been very confused about this issue. the loop and query are out of the scope of the while loop, so it should be fine right?
I'm not fun of helper functions so I would write it like this: $args=array( 'post_type' => 'post', 'posts_per_page' => '20', 'post_status' => 'publish', 'order'=>'DESC', 'orderby'=>'ID', ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $current_id = $post->ID; echo the_field('field1', $current_id); } wp_reset_postdata(); } else { // no post }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, templates, advanced custom fields" }
How to get all tags collections in woocommerce? I need to display all tag names in front end,I have tried `$terms=get_terms('product_tag');` But it returns null. Can anyone please help me How to get it?
You need to loop through the array and create a separate array to check in_array because get_terms return object with in array. $terms = get_terms( 'product_tag' ); $term_array = array(); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $term_array[] = $term->name; } } solution from stackoverflow click for more details
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "tags" }
What is Wordpress' custom post type 'Logs'? I'm in index.php and I'm trying to create a list of links to the archive pages for three custom post types I've registered. Here's what I have so far: // Get custom post types, excluding Wordpress' built-in ones $cpts = get_post_types( array( '_builtin' => false )); // Get a name and a link to the archive page of each custom post type foreach( $cpts as $cpt ) { $name = get_post_type_object( $cpt )->labels->name; $link = get_post_type_archive_link( $cpt ); echo "<a href=$link>$name</a>"; } The code works well except that, in addition to the three custom post types I've registered, a fourth one comes up whose `$name` is Logs and the `$link` is my site's homepage url. What is this 'Log' post type? Is it Wordpress' default Post? Shouldn't the `_builtin => fakse` parameter for `get_post_types` exclude it already? If not, how do I exclude it?
Like mmm suggested in the comments, 'Logs' is a custom post type created by a plugin I'm using, which means that the correct answer is there is no default Wordpress' custom post type. I hope it's clearer now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Best Way to Change a String in a Wordpress Post I have a date value inside a WordPress post's content that I need to be replaced every day with the current day. The string looks like this: **2017-11-11 00:00** I was thinking of building a simple PHP script that would access the MySql wp_posts and find/replace that string, then run the update SQL query to change the required value. $pattern = '/201\d{1}-\d{1,2}-\d{1,2}\s00:00/'; $today = date("Y-m-d"); $replacement = "$today '00:00'"; $finalString = preg_replace($pattern, $replacement, $originalString); The post content doesn't change so the regexp doesn't need to be more elaborated than this and also the hour:mins can remain 00:00 Now the ugly part is that I will need to run a chron job, once per day to run this PHP that updates the SQL database. Is there a better/safer/easier way to solve this issue?
You can create a new shortcode with this code add_shortcode("currentDay", function ($attr, $content, $tag) { $date = current_time("Y-m-d"); return $date; }); and you just have to put `[currentDay]` in the content
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
What is This esc_html_e() i wordpress php? why do developers use <?php esc_html_e() >? in 404 pages, what does it mean, how does it works?
It's a combination of `_e()`, which echoes a translatable string, and `esc_html()` which is for outputting text so that the text is not interpreted as HTML. You would use it to prevent HTML being smuggled into a translation and breaking your markup or causing security issues. For example, if your theme had: _e( 'My translatable string', 'my-text-domain' ); Then it's possible for a translation for `'My translatable string'` to be something like `'<script>alert('Bad!');</script>'`. If you don't use `esc_html_e()` then that script will be executed. If you use `esc_html_e()` then it won't be, because the `<` & `>` characters will be escaped as `&lt;` & `&gt;`, which out output as < and > and not interpreted as HTML tags.
stackexchange-wordpress
{ "answer_score": 17, "question_score": 11, "tags": "php, functions, loop, 404 error" }
If search results empty then execute certain code If search results are empty then I want that some code be executed, but how to write such situations programmatically? If !is_search() { certain code } But above doesn't work.
Your code will check whether you are on a search page or not ( You also forgot to wrap your conditional in parentheses ). In order to check if there is any result for your search, use `have_posts()`: if( have_posts() ) { // There is a post } else { // No results } This works for global queries. If you wrote your own instance of `WP_Query()`, you need to do as follows: $my_query = new WP_Query($args); if( $my_query->have_posts() ){ // There is a post } else { // No results }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, functions, search" }
Use the page title in the plugin I have many WordPress pages, I am using only one shortcode in those pages, For example the content of page1 is [shortcode name="page1"], content of page2 is [shortcode name="page2"], content of page3 is [shortcode name="page3"] Is it possible that I don't need to specify the name attribute in the shortcode and I can just specify [shortcode] and it takes the title of the page as the name attribute automatically For example, in plugin, i could write something like this function shortcode($atts) { extract(shortcode_atts(array( 'name' => "**title of the page**", ) , $atts)); ...... } add_shortcode('short_code', 'short_code');
You can simply use the `get_the_title()` function to get the current post's title in your shortcode. If you want it to work only on pages, you can combine it with `is_page()`: function shortcode($atts) { extract( shortcode_atts( array( 'name' => get_the_title(), ) , $atts) ); // Rest of your code } add_shortcode('short_code', 'short_code'); You can use a PHP shorthand conditional as follows: 'name' => ( is_page() ) ? get_the_title() : 'Your else goes here' ;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins" }
Disable text tab on WordPress text-editor I'm looking for a way to disable text tab on wordpress text-edito (red square on the pic) for all my users roles except ADMINISTRATOR because i don't want them to have the possibility to add javascript code on the pages. I also looking for a way to add justify icon to the text-editor (like you see on the pic in red too). now i found a way to hide text tab for all users with the code bellow function my_editor_settings($settings) { $settings['quicktags'] = false; return $settings; } add_filter('wp_editor_settings', 'my_editor_settings'); How can add an exception for ADMINISTRATOR role? ![enter image description here](
For disabling the text tab for all users except administrators, you can add the following: function my_editor_settings($settings) { if ( ! current_user_can('administrator') ) { $settings['quicktags'] = false; return $settings; } else { $settings['quicktags'] = true; return $settings; } } add_filter('wp_editor_settings', 'my_editor_settings');
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "plugins, user roles, tinymce, editor, visual editor" }
Disable most recent & view all (TABS) on nav-menu.php I'm looking for a way to disable Most recent & View all (TABS) on nav-menu.php (in red on the picture). I want to have only the search bar for my pages and posts. Thanks. ![enter image description here]( UPDATE : that what i have now : ![enter image description here]( and that what i want to have : ![enter image description here](
You can introduce a js file exclusively for admin panel doing this in functions.php: //Admin JS add_action('admin_init', 'custom_admin_js'); function custom_admin_js() { wp_register_script( 'admin-js', get_stylesheet_directory_uri() . '/js/admin.js' ); wp_enqueue_script( 'admin-js' ); } And in admin.js file: jQuery(document).ready(function($) { $('*[data-type="tabs-panel-posttype-page-most-recent"]').fadeOut(); $('*[data-type="page-all"]').fadeOut(); $('*[data-type="tabs-panel-posttype-page-search"]').trigger("click"); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, menus, pages, navigation" }
Old robots.txt file not changing, can't update to the current robots.txt While my wordpress website was in production, I created a robots.txt file to disallow everything. When the site was ready, I deleted the robots.txt file through cpanel and never thought much about it. Recently, I realized that the website was not showing up on google search results, upon further investigation, i realized that the old robots.txt file was still there (even though I can't locate the file in my root folder). < I inserted another robots.txt file in my root folder, this time with the allow option instead of disallow. But it doesn't update and still blocks google from accessing the site. ![Current robots.txt in root folder]( ![Current robots.txt content]( ![Old robots.txt as you type the url \(this file was deleted a long time ago\)]( ![Even in the yoast editor it's the current file, but the url still brings up the old file](
Just delete file **robots.txt**. WordPress is generating virtual robots.txt file, and Yoast SEO plugin (and other plugins too) allows you to customize it. But, if you have an actual **robots.txt** file, it will prevent virtual one to work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "google, robots.txt" }
Custom fields with wordpress I've a custom field for a date, written like: yyyy-mm-dd How can I extract only the **day** to display in PHP ? For the moment, I display the full date:`'. get_post_meta($post->ID, 'event_start_date', true).'` Thank you :)
You can try the date() function: $date = get_post_meta($post->ID, 'event_start_date', true); $day = date('d', strtotime($date)); //01-31 Another way will be DateTime: $date = get_post_meta($post->ID, 'event_start_date', true); $date = DateTime::createFromFormat('Y-m-d', $date); $day = $date->format('d');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field" }
How do I get the url slug inside the dashboard for a custom post type? I have added some custom fields inside my blog posts, I need to insert in one of them my permalink from dashboard, how do I do it? How do I get this permalink inside the dashboard? ![enter image description here](
You can retrieve the permalink using `get_permalink()` To retrieve the edit link for a post, use: `get_edit_post_link()`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom field, permalinks, dashboard" }
I am trying to rewrite urls in Wordpress, but its not working add_action( 'init', 'wpse26388_rewrites_init' ); function wpse26388_rewrites_init(){ add_rewrite_rule( 'us-dot-numbers/([0-9]+)/?', 'index.php/?page_id=642&dotNumber=80806', 'top' ); } add_filter( 'query_vars', 'wpse26388_query_vars' ); function wpse26388_query_vars( $query_vars ){ $query_vars[] = 'dotNumber'; return $query_vars; } I am using this code in function.php . I am using flushing function to flush rewrite rules. I want to redirect www.domain.com/us-dot-numbers/80806 to point to www.domain.com/index.php/?page_id=642&dotNumber=80806 Can you please tell me what I am doing wrong. Also please let me know the regex for "Alphabets, Numbers and hyphen only", Thanks in Advance !
You can try add_action( 'init', 'wpse26388_rewrites_init', 10, 0); function wpse26388_rewrites_init(){ add_rewrite_rule( '^us-dot-numbers/([A-Za-z0-9-]+)/?', 'index.php?page_id=642&dotNumber=$matches[1]', 'top' ); } add_filter( 'query_vars', 'wpse26388_query_vars' ); function wpse26388_query_vars( $query_vars ){ $query_vars[] = 'dotNumber'; return $query_vars; } Remember to `flush_rewrite_rules();`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, url rewriting" }
Create unordered list from custom field type entires separated by a comma I have a custom field type set up and need a way for a client to add a list of links that I can then output as a UL with each being an LI. I am hoping they can enter a comma separated list in the input and I can output the list with php where each value in between the commas can be separated out.![enter image description here]( or maybe it can be done if they put each link on a new line? Or maybe there is a better way to tackle this, it's my first attempt at using/creating custom post types.
If I understood you correctly, this should be pretty straight forward: $rawcontent = get_field("myfield"); $rawcontent = preg_replace("!</?p[^>]*>!", "", $rawcontent); // remove <p> $all_links = preg_split("/\s*,\s*/", $rawcontent); foreach($all_links as $link) { if(!trim($link)) continue; print "<li>$link</li>"; } A comma certainly would work, but note that this would break if you had commas inside the link text (`<a href="...">hello, world</a>`). You could easily alter the `preg_split` line to split on other things, though, like line breaks (`\n`). I'm not sure what the ACF editor inserts when you just press enter, but I'm sure that you can split it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, php" }
Why does the blog page not take the page template selected? I have a page template called `post-list.php`. This template lists all the posts that I have created with the title, date, author and an excerpt. Now, to list the posts I have created a page called Blog and selected this newly create template(post-list). Now I head over to the reading setting and select the Posts page as Blog. But it seems to have picked the `index.php` as the template and not the newly created one. What am I missing? Any help highly appreciated!
Because the Blog Page isn't an Page for Wordpress, but a Listing, and Takes the "index.php" if there is no "home.php". How to Solve: create a home.php and Insert the code, that you need in there.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, blog page, blogroll" }
How to move wordpress website from hosting account to localhost I'm getting 404 error while accessing relative paths on _Wordpress_ website copied from hosting and deployed locally as _Apache_ vhost. Local website is basically _git clone_ of the existing remote website. The following steps were performed to make it work: * DB urls were searched and replaced with wp-cli to be < * VHost configured according to apache documentation. * _/etc/hosts_ modified. So website can be accessed successfully via < Media in _< can be viewed successfully. Though, accessing a _Wordrpess_ page identified by /relative path (relative to current domain/site) causes **"The requested URL /relative/ was not found on this server" error**. I'm using the same . _htaccess_ from the remote _public_html_ folder. How to achive equivalent to hosting behaviour for local vhost website? Is _.htaccess, apache2_ configuration, _vhost_ configurations should be changed?
The solution was to allow using _.htaccess_ in _/etc/apache/apache2.conf_ by changing from `AllowOverride None` to `AllowOverride All`. More about it here So that section related to my local website now looks like: <Directory /var/www/local.webiste.com/public_html> Options Indexes FollowSymLinks AllowOverride All Require all granted Allow from 127.0.0.1 </Directory>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "htaccess, apache" }
Migrating meta value to new meta value There is a "_thumbnail_id" meta key for our logos and it has each value (Id) by post id. However, we created a new logo field ( meta key = _logo) for logo image ids. We need to move meta value from "_thumbnail_id" to "_logo" in all posts. I have searched and tested some. But there is a problem. Most of the posts have "_thumbnail_id". but posts don't have the new meta key (_logo) by the post ids. Because it's new one. Do I need to add new meta value first in all post? ( _logo ) And then migrate the old one (_thumbnail_id) to the new one (_logo)? How can I move the meta value to new one? Thanks,
Back up your database first, then run this query in phpMyAdmin (or if you don't have phpMyAdmin, run the query out of `functions.php` on an admin hook using `$wpdb->query`): UPDATE wp_postmeta SET meta_key = '_logo' WHERE meta_key = '_thumbnail_id' This will preserve all of the current IDs and just change the name of the meta key. No need to duplicate information or change them one by one.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta" }
Classes CSS (Optional) - how do I reference this in php? I've read an infinite (yes there seems to be more than I care to read) same articles on how to apply a classes to the anchor not the link element using `nav_menu_link_attributes` and a walker. However, none of them implement the custom class option in the menu to be utilized on the anchor. Seems like a nice feature to have to allow the user to add their own class, however, what if I want to apply that class to an specific isolated element in the theme? ![enter image description here]( I have tried but not seen where it documents what this data value is returned in? How can I reference this optional piece of data? My project uses the anchor class attribute to scroll to the section of the page.
You can access those classes like this: // where 'Top' is the menu name, slug or ID. But not menu location. $menu_items = wp_get_nav_menu_items( 'Top' ); foreach ( $menu_items as $menu_item ) { $menu_classes = $menu_item->classes; print_r( $menu_classes ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, links, walker" }
<video> tag is working in chrome but not in firefix..What is the problem? <video> tag is working in chrome but not in Firefox ..I have the Firefox version 56.0.2 ..What is the problem? <div id="myvideo" class="lp-video-wrapper"> <div class="video-wrap hidden-xs"> <video autoplay="" loop="" id="usbvideo" tabindex="0" class="al-img100"> <source src="174125357.webm" type="video/webm"> <source src="174125357.mp4" type="video/mp4"> </video> </div> </div>
First of all, this is not specifically related to WordPress. To answer your question, you need to convert the video in "ogg" format and add it to make it work on Firefox. Here is the code: <video autoplay="" loop="" id="usbvideo" tabindex="0" class="al-img100"> <source src="174125357.webm" type="video/webm"> <source src="174125357.mp4" type="video/mp4"> <source src="174125357.ogg" type="video/ogg> </video> There are tons of converters available for this. I tried < and it works well.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags" }
is_child() function My need is to check if a page is subpage of a page (with ID). I try to get this code working but it doesn't. function is_child($pageID) { global $post; echo $post->post_parent; // display the right ID! if( is_page() && $post->post_parent == $pageID ) { return true; } else { return false; } } It returns always false while **$post->post_parent** returns the right ID! Testing code (which always returns no while $post->$post_parent echoes the good ID in the function): if(is_child(2310)) { echo 'yes'; } else { echo 'no'; } This function takes place in my functions.php file and its purpose is to load CSS through a condition statement (load a particular CSS file if page is X or child of X). This code can be found on many sites around there but was produced in 2012-2013. Thanks a lot for any help. Sources of unworking codes : < <
/** * Return whether the current page is a child of $id * * Note: this function must be run after the `wp` hook. * Otherwise, the WP_Post object is not set up, and * is_page() will return false. * * @param int $id The post ID of the parent page * @return bool Whether the current page is a child page of $id */ function is_child_of( $id ) { return ( is_page() && $id === get_post()->post_parent ); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "child pages, children" }
How run a non-WordPress PHP Program on a WordPress site? I have a question similar to this one: I have created a small PHP program that I want to call as a rest web service to return some data from custom MySQL tables. I can put it anywhere, but I've tried the root folder (public_html), a folder I creatd called custom, and the cgi-bin folder. For the first two, I get 404 not found. For the CGI-BIN it looks like it redirects to my home page. I've set it with CHMOD to 755 (and the custom folder as well). My .htaccess looks like this. I think maybe it needs to change somehow? # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
Okay, I think I was mislead by this... I didn't read the code thoroughly that I cloned. It sets a 404 if the SQL fails. Duh! I also discovered a file called /custom/error_log that I think is going to help debug that. // die if SQL statement failed if (!$result) { http_response_code(404); die(mysqli_error()); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Overwrite a plugin's CSS? I am using a plugin which has the following code for a button: <a class="bwg_load_btn_1 bwg_load_btn" href="javascript:void(0);">Load More...</a> I would like to increase the size of the font used for the text to be 16x. How do I do this? I believe I need to add code to my style.css for my theme but I am not 100% sure what to add. Thank you in advance
You can solve this in two ways # No.1 to find the 'a' tag with class name ' bwg_load_btn_1 bwg_load_btn ' in your plugin and add inline style like this <a class="bwg_load_btn_1 bwg_load_btn" href="javascript:void(0);" style="font-size:16px;">Load More...</a> # 2nd in your style.css add font-size for this class with !important, .bwg_load_btn_1.bwg_load_btn{ /* !important will override the style */ font-size:16px !important; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, css" }
Add custom field to admin area witthout using a metabox I am developing a plugin which uses custom post types. When creating a new custom post, I have a number of custom fields in the admin area within a meta box. Is it possible to display these fields without having them inside the metabox - ideally without having to register a metabox at all? Much like how the title field and content field are displayed in the admin area for posts. Please no suggestions to use a plugin or manually create a custom field using the Wordpress WYSIWYG editor, I wish to implement this with code. Same with hiding the metabox with CSS etc.
You could use the 'edit_form_after_title' action or 'edit_form_after_editor' this would out put your html after the title or content respectively. If i'm working with a custom post type that done not have a content are these are particularly useful and create a really nice look instead of meta boxes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugins" }
Add a TinyMCE Core Plugin Using tiny_mce_before_init TinyMCE has a core plugin called Advanced List Plugin that turns the bulleted and numbered list buttons into dropdowns with different list styles. I'm trying to add this plugin using `tiny_mce_before_init` like so: function my_format_TinyMCE( $in ) { $in['plugins'] .= ',advlist'; return $in; } add_filter( 'tiny_mce_before_init', 'my_format_TinyMCE' ); With this code, the default list buttons don't show up, but the Advanced List buttons don't show up either. There aren't any plugin download links on TinyMCE's site, so I'm assuming the core plugins are autoloaded. I've tried everything I can think of, but can't get this plugin to work.
Sorry to answer my own question, but of course I figured it out right after posting this. Instead of `tiny_mce_before_init` I needed to use `mce_external_plugins`. Also, I had to download TinyMCE from their website and copy the `plugins/advlist` folder to WordPress. I created a folder called `mce` in my WordPress plugins directory and pasted the `advlist` folder into there. function my_mce_external_plugins( $plugin_array ) { $plugin_array['advlist'] = plugins_url() . '/mce/advlist/plugin.min.js'; return $plugin_array; } add_filter( 'mce_external_plugins', 'my_mce_external_plugins' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tinymce" }
How to access theme fonts using custom CSS style? I was looking to change the font in a specific location using a CSS Style. I am using the optimizer theme and I believe the library they us is the following: < I am trying to change the font specifically on to Cinzel on this paragraph but it is not changing. Here is what I have tried: **Attempt 1:** < p style="text-align: center;font-size:300%;font-family: Cinzel;color:#124470">PLEASE CHOOSE YOUR SITE:< /p> Apologies is this has been answered, however my search efforts didn't yield any results. Thanks,
The theme will likely only load a set of specific fonts, or will have options in the back-end to add extra fonts. Your problem is that Cinzel is not being loaded, if you insert the code below (preferably in to the `<head>`) you should find you can then utilise the font. `<link href=" rel="stylesheet">`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css, fonts" }
WordPress plugin update not showing on wp.org I have been maintaining this plugin since quite some time... < But on releasing v5.1.0 update is not showing even after about 20 hours (at the time of writing this)... I don't know what I'm doing wrong... **This is my trunk** `readme.txt` < (I have correct `Stable tag` specified) **This is my tagged version 5.1.0** `readme.txt` < (again correct `Stable tag` specified) Main plugin file < (version correct here too `5.1.0`) I don't see my changelog modifications here either... < I just don't understand why it's not grabbing new version even after 20 hours! It generally works within an hour or so... Can anyone let me know if I'm missing something..?
For those having this problem... It's really rare... In most cases you will be missing something like `Stable Tag:` in your readme.txt file (it should be latest production-ready version). You will also need to make sure, version is correct on your main plugin `.php` file header. Also... version should be tagged to `tags/{your_version}` with `svn copy` for example, to tag version 5.2.0 from master we would want to do... svn copy trunk tags/5.2.0 This should match `Stable tag:` If al this is done and you have like waited for at least 10 hours... And still version ain't live (which is very rare), you can go ahead and do another commit with maybe just another line break to like ping WordPress again... Do this only when everything above doesn't work and you have waited like 10 hours and do it only once because this is an expensive operation for wp.org servers... Hope that helps (somebody).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, wordpress.org" }
How to check User Role and redirect to specific page according to Role when login in Wordpress? Can anyone tell How to check User Role and redirect to specific page according to Role when login in Wordpress? Thanks.
you can do this redirection with this filter : add_filter("login_redirect", function ($redirect_to, $requested_redirect_to, $user) { if ( is_a($user, "WP_User") && user_can($user, "role_to_test") ) { $redirect_to = home_url("/page_slug/"); } return $redirect_to; }, 10, 3);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, redirect, login" }
Show custom post with custom categories with specific slug I'm trying to pull through a custom post with a custom categories and show only a specific slug. e.g. Custom Post (Job Board) - Custom Category (Job Sector) - Specific Slug (Industrial) What I have show far is; $args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'job-sector', 'field' => 'industrial', //can be set to ID ) ) ); Yet nothing seems to be showing...can anyone help or suggest where I'm going wrong? Thanks
Try something like this: With the post_type the name of your CPT $args = array( 'post_type' => 'your_cpt_name', 'tax_query' => array( array( 'taxonomy' => 'job-sector', 'field' => 'slug', 'terms' => 'industrial', ) ) ); $query = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, customization, slug" }
Wamp Server error on running wordpress theme on localhost. How do I fix this error? I am getting an error while running a wordpress theme on wamp server. This error does not appear when I use the default theme but when I run it using a custom theme I getting an error. This custom theme is from one of the tutorial that I am taking. The codes in the respective files which I followed from the tutorials and the error are shown below Error: ![error]( index.php: ![index]( header.php: ![header]( footer.php: ![footer]( I saved this new custom theme inside the C:\wamp64\www\wordpress\wp-content\themes as explained in the tutorial. How do I fix this error. I am unable to learn visually as I can't see how codes are working.
It be better if you have paste the code and not images but here you go: Correct in `index.php` <?php get_header(); if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <h2>.... Adding some context to above, the error telling that it found a character that doesn't belong in that position. `line 7` **<** h2. This is why You add the closing php tag above. `the_post(); ?>`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Javascript asset not enqueuing with the rest I am working on a project that uses the child-theme's functions file to enqueue a stylesheet and a single javascript file. These two resources are enqueued well. However, when I add a new compiled javascript file, it doesn't seem to enqueue past the original two scripts at all, as if it is completely ignoring my addition to the functions.php file. Any idea why this is? <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles_and_scripts' ); function theme_enqueue_styles_and_scripts() { wp_enqueue_style( 'fonts', get_stylesheet_directory_uri() . '/assets/fonts/icons/style.css'); wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/assets/js/main.js'); wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/assets/compiled.js'); }
Your second `wp_enqueue_script()` contains the same handle (the same ID) as the first `wp_enqueue_script()`. The handle is the ID by which a registered script is known to WordPress internally. If you use this ID a second time, the second script won't be registered. A working example could be this one: <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles_and_scripts' ); function theme_enqueue_styles_and_scripts() { wp_enqueue_style( 'fonts', get_stylesheet_directory_uri() . '/assets/fonts/icons/style.css'); wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/assets/js/main.js'); wp_enqueue_script( 'compiled-script', get_stylesheet_directory_uri() . '/assets/compiled.js'); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, child theme, wp enqueue script, scripts" }
Get Post's Excerpt Without the Wrapping <p> tags and the Read More link I want to get the post's excerpt TEXT ONLY. Currently, I'm using `get_the_excerpt()`, but it returns a string in the following format: <p>LOREM IPSUM!&hellip; <a href=" class="read-more">Read More</a></p> I need to get the `LOREM IPSUM` (real excerpt text) only, without the wrapping `<p>` tags or the `<a>` link inside. Is there any way to get this string, using WordPress and PHP functions? Thank you!
You can try this one: $string ='<p>LOREM IPSUM!&hellip; <a href=" class="read-more">Read More</a></p>'; $string = preg_replace('/<a[^>]*(.*?)<\/a>/s', '', $string); echo wp_strip_all_tags($string); > //return LOREM IPSUM!…
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, tags, excerpt" }
Fetching Initials of the Commentator in the Wordpress Website function getInitials($str) { $words = explode(" ", $str); $initials = null; foreach ($words as $w) { $initials .= $w[0]; } return $initials; //DT } echo $str = getInitials('Donald Trump'); # Objective → # I want to fetch the initials of the commentator's name. Suppose the commentators' name is Donald Trump then I should get → > DT I have tried something, but I guess that this is not a complete one and won't work fully. can someone help me in making this edifice an effective version?
Here is function that return you the comment author initials by the comment id function get_comment_author_initials($comment_id) { $author = get_comment_author($comment_id); $words = explode(" ", $author); $initials = null; foreach ($words as $w) { $split = mb_str_split($w); // to cover unicode char $initials .= $split[0]; } return $initials; } function mb_str_split( $string ) { return preg_split('/(?<!^)(?!$)/u', $string ); } And you can use it in your code like this <div class="class2"> <?php echo get_comment_author_initials($comment->comment_ID); ?> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, comments, comment form" }
Update javascript URL in header - Domain Mapping Plugin I am seeing the following script being called in my `wp_head();` it is associated with the Domain Mapping plugin. <script type="text/javascript" src="http:/mywebsite.com/dm-sso-endpoint/1510878861/?dm_action=domainmap-setup-cdsso"></script> I need to update that src to be ` based on some research this is a known bug. What I am trying to do is find where this url which I am sure is dybnamically created can be found at. **What I have done so far:** I have been inside the Domain Mapping plugin but not sure which file would be responsible for creating this javascript call that happens in the header.
I was able to find the file responsible for building the URL placed in the header: wp-content/plugins/domain-mapping/classes/Domainmap/Module/Cdsso.php I was able to update `line# 391` and statically set the protocol to HTTPS which for my use case works. Obliviously we would want to check if SSL is being forced or if the current URL is https and then set it dynamically. I may work out a fix that includes that and post it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, multisite, wp head, domain mapping" }
Get a default customizeAction text for a section using Customizer JS API What is the best way to get a default **customizeAction** label for the Customizer sections added via JavaScript? Here is a code with a custom action label: customSection = new api.Section( 'my_section', { priority: 1, panel: 'my_panel', title: 'Testing Section', customizeAction: 'Custom Action' } ); The default value of **customizeAction** is an empty string. Is it possible to display a default text \-- "Customizing" ?
You're right. There's currently no default value for the `customizeAction` param. You can add your own default value for all controls with something like this in PHP: add_action( 'customize_controls_enqueue_scripts', function() { wp_add_inline_script( 'customize-controls', sprintf( 'wp.customize.Section.prototype.defaults.customizeAction = %s;', wp_json_encode( __( 'Customizing', 'default' ) ) ) ); } ); This isn't in core yet because the default value is actually variable based on whether there is a `panel` defined. This is something we should figure out and improve in core. See #42635.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "javascript, theme customizer, api" }
Where to store the images of a custom WordPress theme? I am creating a custom theme. If I add a picture to the footer for example and the picture is in the folder of the theme, the picture does not display. If I put it in the main wordpress folder it does display. What is the appropriate way to store all images from my theme?
You need to include the path to the theme. bloginfo('template_url'); get_bloginfo('template_url'); So: <img src="<?php bloginfo('template_url'); ?>/footer-image.jpg">
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, images, localhost, local installation" }
Customizer: How to change Header Image description In the Header Image panel, there is a description that says: _Click “Add new image” to upload an image file from your computer. Your theme works best with an image with a header size of 1200 × 280 pixels — you’ll be able to crop your image once you upload it for a perfect fit._ I'm trying to change this text with this: $wp_customize->get_control( 'header_image' )->description = 'New text here'; But its not working. Am I missing something here?
The `description` param unfortunately is not used in this control. You can see that the message is hard-coded in the control's template. That should be changed in core, but in the mean time, you can enqueue some JS at the `customize_controls_enqueue_scripts` action with the dependency of `customize-controls` which does this: wp.customize.control( 'header_image', function( control ) { control.deferred.embedded.done( function() { var el = control.container.find( '.customize-control-description' ); el.html( control.params.description ); } ); } ); This JS will continue to work if the control's `description` param starts to be used in core in a future release.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, theme customizer" }
what is "theme_setup" method for? I can always find some class contains `theme_setup` methods like below, but I never see this methods been called. I don't what's this method for. <?php final class InfiniteScroll extends Package { protected static $single_instance = null; public static function theme_setup() { $is = self::get_instance(); add_action( 'wp_enqueue_scripts', array($is, 'infinite_scroll_js') ); } /** * AJAX Function for infinite scroll */ public function infinite_scroll() { ...some implement.... } /** * Register js for Infinite Scroll */ public function infinite_scroll_js() { ...some code here... } }
Methods in 3rd party plugin and theme classes can be called whatever the author wants them to be called. `theme_setup()` doesn't mean anything special, and doesn't even necessarily mean the same thing in different plugins. And since it's not a special method to WordPress, they're never going to be called automatically by WordPress, so the plugin _would_ be calling them somewhere, you just haven't found it. If I had to guess, `theme_setup()` is a logical name for a method that might be being hooked to `after_theme_setup`, but there's no guarantee.
stackexchange-wordpress
{ "answer_score": 5, "question_score": -1, "tags": "themes" }
How to override parent theme template files? I'm trying to edit some template files located in my parent theme. I was able to successfully edit some of the template files but changes made to the other files did not take effect. After saving the changes I cleared the cache and restarted my browser but I was still unable to get the changes to take effect. The template files in question are not core Wordpress template files but are located in the root directory of the parent theme and were copied to the same location in the child theme.
Core WordPress templates (listed here) can be overwritten by placing them in the child theme (because WordPress itself loads them it knows to do it in a child theme friendly way). Any other template files your theme might be using can only be overwritten if they're included using the correct template functions, like `get_template_part()`, which will check child themes for files first. If the parent theme is using a generic `include` to include template files, you won't be able to replace them in a child theme. That's something you'd need to take up with the author
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "child theme" }
wp_query not working with post_type I have two machines: local and deployment. On my local machine I have the code: $all_prods = array( 'posts_per_page' => -1, 'post_type' => 'product', ); dump(query_posts($all_prods)); The result I'm getting is my three products, that I've created earlier. But the same code on deployment machine returns an empty array despite of the website has many products in it. I thought that somehow deployment machine has the other prefix for it's post type, than my local one, but when I type on deployment machine: $prod = wc_get_product(440); dump($prod); I get **WC_Simple_Product** object with field **"post_type"** equal to **"product"**. How can I debug it?
I've found the solution. $query = new WP_Query(); $all_prods = array( 'posts_per_page' => -1, 'post_type' => 'product', ); $query = new WP_Query($all_prods); echo $query->request . '<BR>'; The output was different on 2 machines, there was a problem with a multilanguage plugin that automatically added a second table and made inner join with it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, woocommerce offtopic" }
Mixed content warning on doctype in admin I'm getting a strange error on my live WordPress website. On the admin homepage, I'm getting a mixed content warning that points to the doctype. If I copy this entire website and database to my local machine, I'm unable to produce the error. It only occurs on the home page of wp-admin, and prevents other things from working - for example, when hovering over Posts or other links on the left-nav, I don't get the sub-navigation on hover - but if I right click, they appear. The warning seems to point to itself: `Mixed Content: The page at ' was loaded over HTTPS, but requested an insecure script ' This request has been blocked; the content must be served over HTTPS`. This error started to appear after upgrading to WordPress 4.9. ![WordPress Mixed Content Error](
It turned out to be Wordfence causing the issue.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, wp admin, https" }