INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to get Custom Taxonomy ID from the post ID In my setup, I have two custom taxonomy called **Regions** & **Sections**. All the post in site can either be from region taxonomy or from section taxonomy. At certain point outside the loop I have the post details and I need the taxonomy ID. I don't have the taxonomy name at that point to use get_the_terms function. Any help will be very appreciated.
You can use `wp_get_post_terms()` which will return all the terms attached to the post, if any. Then, the first term of the array will be able to tell you which taxonomy it belongs to: global $post; $terms = wp_get_post_terms( $post->ID, array( 'regions', 'sections' ) ); if( ! empty( $terms ) && ! is_wp_error( $terms ) ) { $taxonomy = $terms[0]->taxonomy; } I do not know what your taxonomy slugs are so I guess, you may need to change them to fit your specific setup.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom taxonomy" }
Assets in css dont link properly in pages other than home Hello I have a small issue regarding my linking in my style.css For example: @font-face { src: url('wp-content/themes/mytheme/fonts/font.ttf'); } and .div { background: url('wp-content/themes/mytheme/images/img.png'); } My home page works perfectly, assets link correctly but when I go to another page such as "about" the links are broken because it does this: `www.url.com/about/wp-content/themes/mytheme/images/img.png` Anyone know why this is happening? Thanks
You're using relative URLs that will always look inside the current URL structure. You either need to add a slash before wp-content, or put in the full URL to the resources. So for example: `src: url('/wp-content/themes/mytheme/fonts/font.ttf');` or `src: url('
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "css, linking" }
How can I change the background color of a contact box? ![Contact box]( I want to change the background color of this example contact-box but I haven't been able to do so.
The way to determine what to change is to use browser development tools, like Firebug on Firefox. With those tools, you can determine the CSS that is being used in a specific part of the page. Once you determine the CSS class to change, you can put that CSS in the Custom CSS area of your theme (in the Customizer, if supported). Something like, if the contact box has a class called `contactbox`, then you would use CSS similar to .contactbox {background-color:#888888; } If an 'id' is used, then your Custom CSS would be similar to: #contactbox {background-color:#888888; } If your theme does not support Custom CSS, then you will need to create a Child Theme and put the above CSS in the Child Theme's style.css file. You don't want to modify the theme's CSS, as any changes you make will get overwritten on a theme update.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, contact, bloginfo" }
How can I display list of notifications of buddypress in a single page or post I need to display the notifications that come on hover of the notification in one page I tried to follow this link but I cannot make it Please guid me
You may use `[activity-stream ]` to display notifications
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
Change value of Points earned in product data I have an e-commerce website. I have implemented yith points and rewards plugin and can now see a 'points earned' option under product data tab.I have about 700+ products and I want to fill the option with a value (eg. 5) for all the products. However, I cannot see this option under Bulk edit. I tried using plugins and went through the documentations but could not find any help. How can I resolve this? Please Help. ![enter image description here](
Add following code to your `functions.php` file in theme directory. add_action('init', 'set_point_earned'); function set_point_earned() { global $wpdb; $wpdb->query("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) SELECT ID, '_ywpar_point_earned', '5' FROM {$wpdb->posts} WHERE post_type IN ('product','product_variation') AND NOT EXISTS ( SELECT * FROM {$wpdb->postmeta} WHERE post_id = ID AND meta_key = '_ywpar_point_earned' )"); } Then visit your site. After applying the changes you can remove code from `functoins.php`. If you want every product have a point by default keep code!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
Author Page User id in functions.php for non login user I would like to access author **id** when a visitor come to author page? when I am coding in **author.php** file, I could print author id like below $q_obj = get_queried_object(); $user_id = (int) $q_obj->data->ID; But, if I would like to get **user id** functions.php, How should I print? function zb_user_analyze() { // I would like to access user id here } add_action('wp_loaded', 'zb_user_analyze'); Note: I only want to access author page **user id** for nonlogin user.
wp_loaded hook runs before Wordpress has setup postdata so you won't be able to get there the information you need. The earliest hook you can use to have that information should be wp. You can use is_author() to check if you're on an author page and is_user_logged_in() to check if the user is logged in: function zb_user_analyze() { if( is_author() && !is_user_logged_in() ) { $author_id = get_query_var( 'author' ); // do something } } add_action('wp', 'zb_user_analyze');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, author, id" }
Install translation files that should survive updates Someone prepared me a `.po` and a `.mo` file for a commercial theme we are using. How can I install them in such a way that future updates won't destroy them? Putting them into the `languages` folder was a bad idea. Putting them into the theme folder will make theme updates problematic. I'm thinking of creating a custom plugin that contains the translations. Better ideas?
If you're not already using a child theme, build one and place the translations there. If you are already using a child theme, you can't make a child-of-a-child, so you would need to set up a plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "updates, translation" }
How get Themes list via REST api? I wanted to get a list of all WordPress themes installed, together with their meta info (e.g. name, status, author etc) using WordPress REST api. I also wanted to be able to activate any theme via my API client. I've gone through this documentation but I didn't find any relevant end-point. Is it possible at this moment?
You can write your own endpoint and use `wp_get_themes` to get a list of themes via that. Here is a simple one: add_action( 'rest_api_init', function () { //Path to rest endpoint register_rest_route( 'theme_API/v1', '/get_theme_list/', array( 'methods' => 'GET', 'callback' => 'theme_list_function' ) ); }); // Our function to get the themes function theme_list_function(){ // Get a list of themes $list = wp_get_themes(); // Return the value return $list; } Now you can get a list of your themes by accessing ` I wouldn't suggest activating/deactivating themes via API. It can totally mess up things, such as activated widgets.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "themes, wp admin, admin, api, rest api" }
use get_theme_mod from all sites in network I'm creating a site that shows all sites in the network. Each site in the network has a theme customizer where a user enters text. I was able to get the name and url of the site but need to find a way to get the theme option from that site. This is the code I'm using so far: <?php $bcount = get_blog_count(); global $wpdb; $blogs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->blogs WHERE spam = '0' AND deleted = '0' and archived = '0' and public='1'"));?> <?php foreach($blogs as $blog) :?> <?php if(!(($blog->blog_id == 1)&&($show_main != 1))):?> <a href="<?php echo get_blog_details($blog->blog_id)->siteurl; ?>"><?php echo get_blog_details($blog->blog_id)->blogname;?></a> <?php endif;?> <?php endforeach;?> I've also tried `get_template_part` but that didn't work <?php echo get_template_part( 'twsa_show_about', get_blog_details($blog->blog_id)->blog_id );?>
You will have to switch to your blog using `switch_to_blog( $blog->blog_id );` and the access the data you want from that blog. switch_to_blog( $blog->blog_id ); get_theme_mod('your_key'); This should give you customizer option data for that blog. Also I'm not sure where you are using this code, but instead of using `wpdb` query you can use `get_sites` to get list of your sites. See: < Hope this is what you wanted.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, theme options" }
Automatic Website user password generation I have created a ticketing system on my website, so users can log in and request a call out. However wordpress is currently set so that any new users need an administrator to log in and generate them a password, and then email it out. Is there any way to set up a system where a user has their password automatically generated and sent to them? ideally I am trying to cut out having to log in for every new user. Thanks
I have now realised there was a difference to registering on the site and through wordpress. When registering for the site a user can set up their own password, but through wordpress it asks you to check your email for a password that never arrives. Long story short, problem solved. Thanks to everyone for their input!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user registration" }
Programmatically setting Woocommerce product price I have a product (course) that loses value the closer it gets to the end of term. I've set up 'End date' and 'Weekly price' as custom fields on a page, and can calculate the exact price to pay in PHP. How do I dynamically create a woocommerce product, or change an established product's price based on the 'Time Left' calculation I performed? I've tried changing 'price.php' in Woocommerce's template file, but apparently it's just a cosmetic change, and the price reverts to original at basket and checkout. Haven't the foggiest where else to start, so many thanks in advance.
Ok! This is my solution, and (so far) it works: function return_custom_price($price, $product) { $myPrice = 15; global $current_user; $price = $myPrice; $post_id = $post->ID; return $price; } add_filter('woocommerce_get_price', 'return_custom_price', 10, 2); It does target every single product in the store, but as the site only has one product, this works fine.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
Displaying All Posts of a Custom Post Type in Wordpress Multisite Backend I have been looking around all day for an answer, and I'll post a link that I thought might work, and didn't end up panning out. I want to be able to make a backend menu page on my Wordpress Multisite that displays a list of all my posts from every site of the post type "game" along with various custom fields that go with that post type. Here's the link I have found and what happened with it: Other Stack Exchange question First off, this does not account for my need to display custom post types and custom fields. I'm not exactly great with code, might I add, but I tinkered and tinkered with this and couldn't get it to do what I needed it to do. Anybody got a suggestion? EDIT: Also this I'm pretty sure only works on the front end, I need something for the backend.
I was looking for a similar plugin to display all pictures from all sites. Couldn't find one. Ended up writing my own (Multisite Media Display). Then modified that one for another plugin to display all posts (Multisite Post Reader). You can find that one here: < . There isn't an option to display posts of a particular type, but wouldn't be hard to add. Since my plugin is open source, you might find some useful techniques in the plugin code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, custom field, multisite" }
WooCommerce 3 get custom variation on process order I will try to be precise. What I want to do is next. I want to add a custom field in variable products in variations and then to use it when I order is in process(in gateway settings). That field can see only admin, not user. Now, I find a way to add the field in admin page (with 'WC Fields Factory') but I am failed to get it in order process. Thanks in advance
Okay I find solution for this one!! Add field to the each product variation with this one github Remi Corson And because I have a custom gateway plugin for WooCommerce I found there where products are initiated and use **foreach** to get 'productId' for each product. There I use $variation = $item['variation_id']; $productVariation = get_post_custom($variation); $variation = $productVariation[' **my_added_field** '][0]; **// We need that [0] because it returns array of one key and value** And that is it! Hope that it will help somebody
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, woocommerce offtopic, variables" }
How to create a php variable using Wordpress the_title() function I want to create a php variable which will use the `the_title` function: So if the title of the post is "Style" the variable will name will be `$style` and if the post title is "Dog" the variable name will be `$Dog`. Is it possible? I tried `${the_title()};` But it echoes the title. My goal is to use at as a dynamic variable inside a each loop and increase it's number every time it gets the same title. so for example for each post with unique title it will be set to '1' but if a title repeats a second time it will be set to '2' and so on...
Indeed, the `the_title` function echoes the title, unless you set the third parameter to false (default true). So you start with this; $title = the_title ('','',false); Now, `$title` may contain all kinds of characters that cannot be used in PHP variable names, so we need some sanitization: $title = preg_replace('/[^A-Za-z0-9\_]/', '', $title); // Removes special chars except underscore. Then you use PHP variable variables to turn the content of `$title` into a variable name: $$title = 'something'; So, if `the_title` gives the value "hello world", the `$title` variable after sanitizing has the value "helloworld" and `$helloworld` has the value "something".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, functions" }
Sort / display recent posts by publish date I recently renovated some sites and made many small (usually typos) corrections to several posts. That of course changed the last update date, so that now, if I display recent posts in a widget, they are sorted in a totally useless way. The best sort order would be by publish date, but I don't see such option anywhere. Is it possible to display recent posts by publish date instead of update date?
The Recent Posts widget, and the posts page for that matter, doesn't display ordered by update date, it orders by published date. If it's displaying by updated date then you must have a plugin somewhere that's changing this behaviour, or are using something other than the standard Recent Posts widget.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "date, publish, recent posts" }
Change link for "add new" buttons on custom post type I know how to use capabilities to remove the "Add New" functionality for a custom post type, but what I really need to do is change the target of those links. Does anyone know how I might go about doing that? I would be an "external" link (to the front end of the website) and not a page on wp-admin.
in most of the case WordPress ui uses `admin_url()` function to retrieve administrative urls. so you can use `admin_url` filter to modify that. Example: add_filter( 'admin_url', 'wpse_271288_change_add_new_link_for_post_type', 10, 2 ); function wpse_271288_change_add_new_link_for_post_type( $url, $path ){ if( $path === 'post-new.php?post_type=your_custom_post_type' ) { $url = get_permalink(/*your post ID here*/); // or any other url } return $url; } Change `your_custom_post_type` with your custom post type name. Reference (WordPress Version 4.8): edit.php (Line No. 312) and link-template.php (Line No. 3132)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp admin" }
How to add meta data to WordPress posts? In a clean WordPress installation, how do you add meta keywords and meta description in head tag of my WordPress pages? There aren't any fields for these. I don't want to touch my code since I'm new to WordPress. I want to do this only by WordPress itself.
I assume you are trying to add metadata to the header, such as Open Graph. To do so, you can hook into `wp_head` and output your content there directly. Add this piece of code to your theme's (or your child theme's) `functions.php` file: //Hook to wp_head add_action('wp_head','add_my_metadata'); function add_my_metadata(){ // Echo any content your wish here. Replace this with what you want. echo '<meta name="keywords" content="Keyword1, Keyword2"/>'; } Notice, that your theme must have `<?php wp_head(); ?>` in its `header.php` file in order for you to be able to output any content there. ## UPDATE If you are new to WordPress, you can install a plugin. There are plenty of known plugins that can do this for you, the most distinguished one is Yoast SEO which automatically does this for you.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "post meta" }
Reporting errors in a shortcode plugin I have a plugin that expands a spanning shortcode into a `<table>`, and one of the parameters is the number of columns, eg: [table cols=3] Row 1 Data 33% Row 2 Data 67% [/table] Now, using the raw HTML editor I might forget to add the `cols`, or I might enhance my plugin so that it can make an intelligent guess at the real number of columns, etc, but how can I report to the post editor that there is an error or warning? My usual workflow is to edit the post in a text editor, paste it into the HTML editor, save draft, then preview. What is the recommended way to pop up an error in either the backend or the preview window? If I'm in a hurry, for instance, I might not scroll down to the table to see an error message directly inserted into the stream at the `[table]` tag, so the simple solution is probably not suitable.
Take a look at `admin notices`. If you the cols parameter isn't set use some code like this: function sample_admin_notice_fail() { ?> <div class="notice notice-error is-dismissible"> <p><?php _e( 'You forgot the cols parameter!', 'sample-text-domain' ); ?></p> </div> <?php } add_action( 'admin_notices','sample_admin_notice_fail' ); to display this notice: ![enter image description here]( on top of your admin page. You find some more information about implementing admin notices on this page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, errors" }
Can’t get url_to_postid to work Why does url_to_postid return 0 here? $url = 'https//devapps.somedomain.edu/hr/no-permissions-message/'; (I changed the domain before posting btw) $post_id = url_to_postid($url); I guess I don’t understand how it’s supposed to work. That is a valid page/URL, but no id is being returned. It’s not a page of blog posts, maybe that’s the problem?? If so, is there a way to get the ID of a page (not blog posts), given a URL? Thanks, Doug
Probably because you don't have a colon in the url after `https` (assuming you copied the `$url` parameter correctly). The function will return a '0' if the page does not exist.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Auto update cart after quantity change I am trying to Auto update the woocommerce cart after quantity is changed. The following code within the function.php is working, BUT updates the cart only if I change the quantity twice. Do you know how to fix that? add_action( 'wp_footer', 'cart_update_qty_script' ); function cart_update_qty_script() { if (is_cart()) : ?> <script> jQuery('div.woocommerce').on('change', '.qty', function(){ jQuery("[name='update_cart']").trigger("click"); }); </script> <?php endif; }
Almost one year late, but this question might still get visitors: You trigger the click, but the button doesn't have enough time to become enabled, so that is why, by the time you click the second time the button becomes enabled. Remove the "disabled" propriety before triggering the click: <script> jQuery('div.woocommerce').on('change', '.qty', function(){ jQuery("[name='update_cart']").prop("disabled", false); jQuery("[name='update_cart']").trigger("click"); }); </script>
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "woocommerce offtopic" }
Is it possible to schedule a page edit to go live on a certain date? On one of our websites, we have a page with a text block (Visual Composer) about a special offer which is available until the 1st of July. I, of course, would like that to disappear as soon as the 1st of July comes around... But here in the UK, that's a Saturday, so nobody will be around to make that amendment. So, would it be possible, via a plugin or otherwise, to remove that text block, but then schedule the publication of that amendment to go live on the 1st, similar to how you can schedule the publication of blog posts?
You can use Show/Hide Content at Set Time plugin to to show the content on scheduled time or date. [time-restrict on="2017/06/26 18:00:00"]your content Will show after 06/26/2017 at 6pm[/time-restrict] more examples according to your need can be seen on plugin page
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "scheduled posts" }
Create blog page only to see one category I'm doing a Wordpress blog. The **blog** page has a submenu in which appear the categories of the posts and the idea is, when I click in one category, it displays the posts that are of that category. So the problem is, I have to create a new page and pass url parameters to know which category was selected? What is the best way to do this?
Using the function `<?php echo get_category_link( $category_id ); ?>` I can access to the category pages of the blog. < > Retrieve category link URL.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories" }
How to delete all categories programatically? Simple questions - how do I delete all categories programatically? For instance this returns a list of all categories $args = array( "hide_empty" => 0, "type" => "post", "orderby" => "name", "order" => "ASC" ); $types = get_categories($args); How do I simply delete them so I can replace them with other categories?
Please have look on the below code block- $args = array( "hide_empty" => 0, "type" => "post", "orderby" => "name", "order" => "ASC" ); $types = get_categories($args); foreach ( $types as $type) { wp_delete_category( $type->ID ); } The function `wp_delete_category` will delete a single category. So we need to run a loop through `$types` to delete each single category. Hope that helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, php, plugin development" }
Links open when scrolling on touch devices/mobile On all touch devices both Android and iPhone and iPad, when scrolling with finger over a link the site opens the link instead of ignoring the press and just scrolling as touch devices normally do when scrolling. I'm using WordPress 4.2.15 and building my own child theme off of twentythirteen. Link: joshuachronstedt.dk Plugins: Advanced Custom Fields, Advanced Custom Fields Multiligual, Advanced iFrame, All in one Favicon, Disable Emails, Duplicate Theme, Insert Headers and Footers, Instagram Feed, jQuery Smooth Scroll (I have tried disabling this), No Image Links, Page Animations And Transitions, Simple Custom Post Order, SVG Support, UpdraftPlus, Video Thumbnails, What The File, WP-PageNavi, WP Load More Posts, WPML Multiligual CMS, WPML String Translation, WPML Translation Management. Hope someone can help :)
I could confirm on your shared site that some javascript code is causing this issue. This code may be generated by plugins used on your site so please try temporary deactivating all plugins and see whether everything works fine and then enable the plugins one by one to see which plugin is generating it if any. Also this can be generated by child theme used on your site so to confirm it just temporary use the twentythirteen theme instead of child theme on your site. If everything works fine then it's your child theme generating that code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links, mobile" }
Redeclare slug & name of custom post type? I'm registering custom post type in the plugin, but want to allow users of the plugin modify it afterwards (e.g. if they are installing for clients, etc.) function create_reviews_post_type() { register_post_type('reviews', array( 'labels' => array( 'name' => __('Reviews'), 'singular_name' => __('Review') ), 'public' => true, 'has_archive' => true, ) ); } add_action('init', 'create_reviews_post_type'); What is best way to achieve this? E.g. I want to change **name** , **singular name** and **slug** in future. I understand that there is a similar question, but 1. it 5 years old and I hope there can be an easier way, 2. it doesn't cover the name part
WordPress provides the `register_post_type_args` filter to let users do this: function wpd_modify_post_type( $args, $post_type ){ if( 'reviews' == $post_type ){ $args['labels']['name'] = 'New name'; $args['labels']['singular_name'] = 'New singular name'; $args['rewrite']['slug'] = 'new-slug'; } return $args; } add_filter( 'register_post_type_args', 'wpd_modify_post_type', 10, 2 ); Keep in mind that if the slug changes, the user will need to flush rewrite rules manually for the new slug to start working, which can be done by visiting the Settings > Permalinks page in admin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types" }
Add html code in admin page I'm trying to add floating button in admin page. If I using add_action('admin_footer', 'my_admin_function'); The button will in the bottom of the page and I need to scroll down. I need the button always on the bottom of the screen and I don't have to scroll down. Is there have action API that can add some code in the body?
Try doing little CSS work .admin-button{position:fixed; bottom:20px; right:20px; z-index:999;} add class to your button code, here I am using ".admin-button" for example .This will make your button appear in bottom 20px up and 20px away from right , more do as wherever you want to place. Hope this small thing can work for you
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, actions" }
How to change text depending on the country a few texts fields on the site need to be different in one specific country on (Category & Custom home page) Eg: Class 1 (India) Grade 1 (UK) First Grade (US) Any idea on how I could do this ?
There are several plugins out there that help you to translate your site content. Though you could have googled that by yourself easily, look here to get a brief overview: < WPML is a very powerful translation plugin (not free), in your case qTranslate should be good enough and is easier to implement than WPML I guess.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "localization" }
How to call a function on particular page like 'contact-us' from function.php of child theme I want to call a function on particular page like 'contact-us' from function.php of child theme. i tried this function if( is_page('contact-us')) { echo "hello check"; //either in about us, or contact, or management page is in view } else { echo "Not working"; } But getting else part on every page. if(is_page(37)){ echo "page 37"; } else { echo "Not working" } Getting else part $current_url=" $contactUsId = url_to_postid( $current_url ); if($contactUsId == '37'){ echo "hello"; } But this works , can any one one help me to know why first two function print else part.
The problem is that you're trying to use `is_page()`, a conditional function intended only to run adjacent to the query, too early. Try running your code inside a callback that 1) only fires on the front-end, 2) fires after the page has partially loaded. For instance, `wp_head`. function prefix_run_on_contact_us() { if( is_page('contact-us')) { echo "hello check"; //either in about us, or contact, or management page is in view } else { echo "Not working"; } } add_action( 'wp_head', 'prefix_run_on_contact_us' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions" }
Post query - show posts from specified day and month and whole years I'm looking for widget or php query which I will be able to use as something like "on this day in history". This query I want to show: Posts published in the past on the same day and month, from whole years of publication. Thank you in advance for help.
You can use WP_Date_Query in conjunction with WP_Query to accomplish this. $query = new \WP_Query( array( 'posts_per_page' => 5, 'date_query' => array( array( 'day' => date( 'j', current_time( 'timestamp' ) ), 'month' => date( 'n', current_time( 'timestamp' ) ), 'before' => 'this year' ) ) ) ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); // Do stuff. endwhile; endif;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, posts, query" }
Get multiple term IDs by slug, and then exclude them in get_terms I want to exclude multiple terms in `get_terms`, but the `exclude` parameter only accepts term IDs. So I have to get the term IDs from its slug. This is what I have so far: $pres = get_term_by('slug', 'president', $cat_type); $vice = get_term_by('slug', 'vice-president', $cat_type); $admin = get_term_by('slug', 'admin', $cat_type); $rnd = get_term_by('slug', 'rnd', $cat_type); $ID_pres = $pres->term_id; $ID_vice = $vice->term_id; $ID_admin = $admin->term_id; $ID_rnd = $rnd->term_id; $terminologies = get_terms( $cat_type, array( 'orderby' => 'term_id', 'exclude' => '???' <<<< ) ); I felt there's something really wrong and redundant here but I'm not sure how to put them into an array that can be used in the`exclude` parameter. Any help?
You can get terms, from multiple slugs, with the `slug` argument: $exclude = get_terms ( [ 'slug' => [ 'president', 'vice-president', 'admin', 'rnd' ], 'taxonomy' => $cat_type, 'fields' => 'ids', ] ); where we use the `fields` argument to return only term ids.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "terms" }
Include images from pages in wp search.php results in default wp search Is there a way to include **page images** in wp search? Like I want to search through my sites **images on pages not in posts** by caption/alt text and display them in the results page as thumbnails.
To include the `attachment` (media) post type in search results, use the following code snippet function attachment_search( $query ) { if ( $query->is_search ) { $query->set( 'post_type', array( 'post', 'attachment' ) ); $query->set( 'post_status', array( 'publish', 'inherit' ) ); } return $query; } add_filter( 'pre_get_posts', 'attachment_search' ); Source However, this does not take care of how the search results are displayed but that's a discussion for another thread. This should've worked, but if you want to add pages as well, then replace $query->set( 'post_type', array( 'post', 'attachment' ) ); with $query->set( 'post_type', array( 'post', 'page', 'attachment' ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugins, php, pages, search" }
Adding buttons to wp-admin/edit-comments I want to add my own buttons to the comments editor table: ![enter image description here]( I tried to understand what happens in wp-admin/comment.php , edit-comments.php, includes/class-wp-comments-table-lists.php etc. but I couldn't figure it out.
You can use two filters for that: * **manage_edit-comments_columns** \- to add a column header on comments table * **manage_comments_custom_column** \- to add the content of each row for that column So you would have something like this: function myplugin_comment_columns( $columns ) { $columns['my_custom_column'] = __( 'My Category' ); return $columns; } add_filter( 'manage_edit-comments_columns', 'myplugin_comment_columns' ); function myplugin_comment_column( $column, $comment_ID ) { if ( 'my_custom_column' == $column ) { echo '<a href="' . admin_url('/my-action.php?id=' . $comment_ID) . '">My button</a>'; } } add_filter( 'manage_comments_custom_column', 'myplugin_comment_column', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments" }
How can I make wp default gallery responsive? I want my WP **default gallery** to go from 4 columns on computer screens down to 2 on mobile devices.
You can try using css to control the visual layout. I have tested on my dev server and this was successful. @media only screen and ( max-width: 320px ) { .gallery-item {float:left;width:50% !important;} } what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit. Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor. Try it out and hope it helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "gallery, responsive" }
Cannot dequeue script in child theme In functions.php of my parent theme, I have these function karuna_scripts() { wp_enqueue_script( 'karuna-functions', get_template_directory_uri() . '/assets/js/functions.js', array( 'jquery' ), '20160531', true ); } add_action( 'wp_enqueue_scripts', 'karuna_scripts' ); I am trying to Dequeue 'karuna-functions' in a child theme // BEGIN DEQUEUE PARENT ACTION function remove_parentstickyfunctions() { wp_dequeue_script('karuna-functions'); } add_action('wp_enqueue_scripts','remove_parentstickyfunctions'); // END DEQUEUE PARENT ACTION But I am still getting the sticky menu functionality which I believe is loaded from /assets/js/functions.js of the parent theme. How do I remove the sticky menu functionality in the child theme?
Try increasing the priority of the respective action, otherwise the system will not know what to dequeue: function remove_parentstickyfunctions() { wp_dequeue_script('karuna-functions'); } add_action('wp_enqueue_scripts','remove_parentstickyfunctions', 20);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "child theme, wp enqueue script" }
Wordpress Multisite - When a user signs-up on main site, how to add the user to a subsite I am setting up a Wordpress multisite network, where users may subscribe to one or more services on the main site and may have access to content on subsite. The access on subsite will depend on the service they subscribe on the main site. What I want to do using some code is when a user registers on main site, I can add that user to the subsite and add some attribute/meta-data to define what access the user has on the subsite (may be I will use memberpress to manage the access) My main question is what code can be used to add a user to subsite when he signs up main site?
Run `add_user_to_blog()` after user creation. You can hook on `user_register()` to get newly created user ID and pass it and any conditional assignments to your callback that runs `add_user_to_blog()`.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 6, "tags": "multisite, users" }
White Screen When Includding A Folder With PHP Files So I'm currently working on a plugin using the boilerplate plugin structure. The problem comes up when I try to include a folder full of files that are needed for my project. I go to the admin class and I include everything from this folder using this code: foreach(glob('folder/*.php' ) as $file) { include_once $file; } This produces an error when I create an instance of one of the classes I'm including. If I do not create instances, there is no error. Though, if I use this code on the top of the file everything works as expected. include_once('folder/class1.php'); include_once('folder/class2.php'); include_once('folder/class3.php'); include_once('folder/class4.php'); include_once('folder/class5.php');
By the WP coding guide, please, use WP Plugin API. In your case place the following code into start of the main `.php` file of the plugin. // Working directory definition. define( 'MY_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); // Attaching executable require_once MY_PLUGIN_DIR . 'folder/class-my-class.php';
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, php, include, fatal error" }
How to know if the most recent article I would like to know how to know if the next article is the most recent ? And if is not the most recent, dont' show the content (The right arrow and "Article suivant") please, Here is my current code : For next : <?php $next_post = get_next_post(); if (!empty( $next_post )): ?> <a href="<?php echo esc_url( get_permalink( $next_post->ID ) ); ?>"><?php echo esc_attr( $next_post->post_title ); ?></a> <?php endif; ?> For previous : <?php $prev_post = get_previous_post(); if (!empty( $prev_post )): ?> <a href="<?php echo $prev_post->guid ?>"><?php echo $prev_post->post_title ?></a> <?php endif ?> ![]( Thank you every one !!
Sounds like WordPress does not support this out of the box. However, you can get the most recent post via `wp_get_recent_posts()`, and then check against the result from there. Here I am using `array_shift()` to turn the array containing one post into the post itself. $args = array( 'numberposts' => 1, 'post_status' => 'publish', ); $most_recent_post = array_shift(wp_get_recent_posts( $args, ARRAY_A )); $next_post = get_next_post(); if (!empty( $next_post )) { // is the next post the most recent post? if ($most_recent_post['ID'] === $next_post->ID) { // next post is most recent post } else { // next post is not most recent post } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "conditional content, next post link, previous post link" }
Loading custom post thumbnail into stream I would like to get a hold of the feature image to perform image manipulation on it. First I want to load it, then manipulate it and turn the final image into base64 for displaying it in the HTML. Any idea how can I get a hold of the image?
You can write a function to grab the featured image by post's ID, then manipulate it and return it as whatever format you wish. function covert_thumbnail_to_base64($post->ID){ // Get the thumbnail's URL $thumbnail = get_the_post_thumbnail_url( $post->ID,'thumbnail' ); // Now, process it the way you want // Return the processed image return $data; } Now you can convert the post's thumbnail to base64 by calling `covert_thumbnail_to_base64();`. if you use this inside a loop, you don't have to pass the post's ID to the function. Otherwise, you should feed the function with a post ID. If you need the absolute path to the image, you can use `get_attached_file()` in conjunction with `get_post_thumbnail_id()`: $file_path = get_attached_file( get_post_thumbnail_id($post->ID));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, post thumbnails" }
Can we start session from another php site to wordpress blog site? I have created my site in PHP now My Blog site in wordpress so if user logged in PHP site is also logged in Wordpress site it is possible?
I found the solution for using below function: function auto_login() { // make sure user is not logged in and "user" was POST'd $username = isset( $_POST['user'] )? $_POST['user'] : false; if ( ! is_user_logged_in() && $username ){ // load the user by username $user = get_user_by( 'login', $username ); if ( $user ) { // log user in using the $user object properties wp_set_current_user( $user->ID, $user->user_login ); wp_set_auth_cookie( $user->ID ); do_action( 'wp_login', $user->user_login ); } } } add_action( 'wp_loaded','auto_login' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, authentication" }
Add subcategories posts to the counts column at the admin's categories list By default the `Count` column shows the number of category's own posts only. Instead, I want to see the total number of records taking into account posts in child categories. !screenshot I know that the `get_terms` function has the `pad_counts` parameter: > Whether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false. So I suppose that I can change the same parameter for some query using some hook. But how to find them? Is my guess correct?
You can change an array of `get_terms()` arguments with two filters: 1. `get_terms_defaults` filters the terms query **_default_** arguments; 2. `get_terms_args` filters the terms query **_passed_** arguments. For example, this code will change the default value for the `pad_counts` parameter for all queries related to categories and called from the administrative part of the site. add_filter( 'get_terms_defaults', 'custom_get_terms_defaults', 10, 2 ); function custom_get_terms_defaults( $defaults, $taxonomies ) { if ( is_admin() && in_array( 'category', $taxonomies ) ) { $defaults['pad_counts'] = true; } return $defaults; } !result
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, terms, count" }
How can I comment comma-separated array values? I realise this is perhaps more of a php question rather than WP-specific, but figure/hope it's relevant. I annotate my code probably more than is needed (because I know relatively little about this, and it helps me to better understand). I'm wondering how best to deal with these two instances... In: $query->set( 'post__not_in', array( 41, // page title 43, // /page title ) ); BBEdit syntax highlight is ok, and the code works. Whereas in: wp_list_pages( array( 'exclude' => ' 41, // page title 43, // page title ', ) ); BBEdit syntax highlight is incorrect, but the code works. Is it ok (reliable) to include such comments - and is there a better alternative?
**No, it's definitely not okay to comment your code this way.** It changes the string, and even though WordPress might strip the incorrect characters and yield the correct pages (it wouldn't if your "comments" contained comma's or numbers), it is incredibly unstable. Instead, if you do want to comment them, I would suggest storing them as an array, commenting that in the way you described, and `implode`-ing it with a comma: $exclude_ids = array( 41, // First page title 43, // Second page title ); wp_list_pages( array( 'exclude' => implode( ',', $exclude_ids ), ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, query posts, array" }
How do I track down the origin of the alt text on a particular image? I am trying to change the alt text of a particular image on my homepage. Here is the page, and this is the image in-question. Something is causing the alt text to display as 'Horizon Residences,' and I want to edit it. I've ensured that the media file in the WP back-end has my desired alt-text (screenshot). Also, when I add the image to the page in the WordPress back-end, I've ensured that the alt-text is my desired text (screenshot). Any thoughts on how to track down the origin of this mysterious alt text? To check if any templates have the current alt text hard coded, I used grep to search through my child theme files for the term 'Residence.’ But that search did not return anything. I also tried searching for the string ‘alt,’ but couldn’t see anything relevant. Thanks in advance.
The answer was right under my nose. Right there in the WordPress editor was the relevant line of HTML code (placed there by the plugin "Toolset Types"): <a href=" field="horizon-residences-banner" alt="Horizon Residence condominium" title="Horizon Residences" size="full" align="left"][/types]</a> It was there that I could change the title, and in-turn, the alt text (since the title was overriding the alt text).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "images" }
How to put a date range in a virtual/downloadable product? I've searched for this kind of situation, but couldn't find anything that can help me. We're selling files with daily data (stock prices) on a woocommerce store, and I want something that I can put a date range (e.g 01/01/2016 - 31/12/2017) and have a dynamic price based on this range. Then, I'd call a microservice to create the file for me and put it on the user's inventory. Any ideias how to achieve this?
Hook into add_to_cart hook add_action('woocommerce_add_to_cart', 'create_files_for_cart'); function create_files_for_cart() { // Your code that created the file using the dated the user selected // More code to add the file created to cart } The code to create the downloadable file product is similar to the code in this answer Add the product to cart with the Cart class functions You use this plugin to add the date fields to the product.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Is it better to store images and other files in the root directory or the theme directory I'm wondering what the best practice is for storing images, css, js etc in my file manager. I've come up with these 2 possible options as my preferred options. 1. Create folders (`images/`, `css/`, `js/`) in the root directory And refer to these files like `<img src="/images/image1.png">` for example... OR 2. Create folders (`images/`, `css/`, `js/`) in the specific theme directory And refer to these files like `<img src="<?php bloginfo('template_directory'); ?>/images/image1.png">` for example... I'm wondering if there is a standard or a preferred practice? I'm new to wordpress and php and would like to start off doing things correctly now, rather than trying to fix problems in the future. Thanks!
Of the two option you proposed, the latter is better for maintainability. The reason is, if you ever need to move the site to another server or use the theme on another site, it seems an easier process to move / reuse. If you're not using the image for themeing, consider just using media library for post/page embeds. * * * Instead of: bloginfo('template_directory'); Consider: get_template_directory_uri(); or get_stylesheet_directory_uri(); Source: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, filesystem" }
add_rewrite_rule parameter is not received by the page This doesn't work: add_rewrite_rule('^spor/?','index.php?pagename=search&search_text=spor',top); It goes to the search page but `search_text=spor` is not taking effect. (Like Empty) When I manually browse from browser: www.mydomain.com/index.php?pagename=search&search_text=spor the query works succesfully. What am I missing?
Custom query vars have to be added via the `query_vars` filter to be parsed within rules. function wpd_add_query_vars( $qvars ) { $qvars[] = 'search_text'; return $qvars; } add_filter( 'query_vars', 'wpd_add_query_vars' ); You can then get the value with `get_query_var('search_text')`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "rewrite rules" }
Wordpress redirects non-existing url to existing ones - how to disable I've noticed that when I type: ` _(which does not exist)_ somehow, for some reason I'm directed to ` _(which exists)_ I found that this is default behavior at least in recent versions of Wordpress. How to control-disable this?
This question is a duplicate of Disable ONLY URL auto complete, not the whole canonical URL system Try this filter function remove_redirect_guess_404_permalink( $redirect_url ) { if ( is_404() ) return false; return $redirect_url; } add_filter( 'redirect_canonical', 'remove_redirect_guess_404_permalink' ); Or this plugin: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "url rewriting, redirect, urls, wp redirect" }
Custom Redirect after registration in WooCommerce After a user registers using WooCommerce's registration form, I want to redirect them to a custom page, such as my other website, instead of the `my-account` page. add_action('woocommerce_registration_redirect', 'ps_wc_registration_redirect',10); function ps_wc_registration_redirect( $redirect_to ) { $redirect_to =" return $redirect_to; } The hook above successfully redirects users when the destination is a page on the current site, but when the redirect location is off of the current site, it does not work. Is there any other hook available after the user registration redirection occurs?
Internally, WooCommerce uses WordPress' `wp_safe_redirect()` which does not allow redirects to external hosts. In order to get around this, we must add our desired host to the whitelist. The whitelist can be modified using the `allowed_redirect_hosts` which has been demonstrated below: /** * Adds example.com to the list of allowed hosts when redirecting using wp_safe_redirect() * * @param array $hosts An array of allowed hosts. * @param bool|string $host The parsed host; empty if not isset. */ add_filter( 'allowed_redirect_hosts', 'wpse_allowed_redirect_hosts', 10, 2 ); function wpse_allowed_redirect_hosts( $hosts, $host ) { $hosts[] = 'example.com'; return $hosts; } Use the code above along with your original code (customizing the host as needed) to allow WooCommerce users to be redirected to an external domain after completing the registration process.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "woocommerce offtopic, redirect, user registration" }
WordPress.org: How to add a plugin for certain countries? I wrote my plugin, which I would like to share with the WP community. I would like to post it on the site of `Wordpress.org` for this. But my plugin is intended only for certain countries, since only for users in these countries this plugin may be interesting. Questions: 1. Is there a way to add a plug-in only for certain countries? 2. Description of the plugin and other information about it must be written in English, or I can use another language (Russian)?
There is no formal requirement that your plugin use English as its language. Here is an example of a Russian only plugin. The plugin repository at wordpress.org is global. You cannot restrict distribution to certain countries. And even if you could, the open source license would allow others to do so. If you release your software under a GPL license, which you must agree to to use the repository, you wave certain rights. One of those is the right to control who is using your software and where.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, wordpress.org" }
I don't arrive to do order_by title when i have a conditionnal year in a request I have a problem with this request with `get_posts`,when I want to order by title with year, order by doesn't work but when I do it without year, the request works. $args = array( 'post_type' => 'projects', 'posts_per_page' => -1, 'year' => date( 'Y' )-2, 'orderby'=> 'title', 'order' => 'ASC',); $myposts = get_posts( $args );
I tried your code and is working fine for me $args = array( 'post_type' => 'project','posts_per_page' => -1,'year' => date('Y') - 2, 'orderby'=> 'title','order' => 'ASC'); $myposts = get_posts( $args ); The thing is as you can see he is only fetching the posts from 2015. If you don't have any posts with the **publish date from 2015** you will get nothing, but if you want to grab all posts **from two years ago until the current year** you have to do the following: $args = array( 'post_type' => 'project', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC', 'date_query' => array( array( 'after' => date('Y')-2 . ' year ago' ) ), ); See WP_Query for reference
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "get posts, date, post type" }
How to add a class to term Good day, i am try to add an active class after i choose the alphabet but it's cannot working <?php $alp_list = get_terms(array( 'taxonomy' => 'alphabets','orderby' => 'name', 'hide_empty' => false ) ); foreach ( $alp_list as $alp ) { echo '<a href="'; bloginfo('url'); echo '/?s='.$alp->slug; echo '&section=member_list'; echo '&alp='.$alp->slug; echo '&submit=search">'.$alp->name.'</a>'."\n"; } ?>
Could this be what you're looking for; first get the query string for `alp` and make a conditional statement every item in the loop against the query string `alp` $selected_slug = $_GET['alp'] ? $_GET['alp'] : ''; $alp_class = ''; $alp_list = get_terms(array( 'taxonomy' => 'alphabets','orderby' => 'name', 'hide_empty' => false ) ); foreach ( $alp_list as $alp ) { if($selected_slug === $alp->slug) $alp_class = 'active'; printf('<a href="%1$s/?s=%2$s&section=member_list&alp=%2$s&submit=search" class="%3$s">%4$s</a><br/>', get_bloginfo('url'), $alp->slug, $alp_class, $alp->name); } **Updated** code to add the `active` class on the link. Let me know if that works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "taxonomy" }
Custom template for all woo commerce categories I am new with Woo commerce and want to know that how i can create template that will work for all Woo commerce categories. I am able to find out answer that are working for specific to any category (taxonomy-product_cat-SLUG.php) but i want this for all categories. I have already copied template folder of Woo commerce plugin in my theme but i am not able to locate category template. I will appreciate your help. Thank you!
I am able to locate that file in my theme. For categories woocommerce.php in root directory of my theme is working and i am able to complete my task. Thank you!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
Where to copy woocommerce files to in my custom theme to avoid editing the core plugin? I want to change the loop-start.php so I have copies the entire woocommerce plugin into my theme folder. Then started editing templates/loop/loop-start.php but it does not reflect in my front end. Am I doing something wrong?
To override WooCommerce (WC) templates, put your modified templates in `custom_theme/woocommerce/template-category/template-name.php` Example: To override the admin order notification, copy: wp-content/plugins/woocommerce/templates/emails/admin-new-order.php to wp-content/themes/yourtheme/woocommerce/emails/admin-new-order.php WC Documentation Reference
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin development, woocommerce offtopic" }
Are there procedures to prevent malicious plugin updates? This is a random thought I've had today. Here's the scenario: I've got a plugin on the WordPress store with 100+ active installs. I recently updated the plugin and pushed the changes to the WordPress SVN. Around 60% of users updated the plugin in the first couple of days - but what's not to say that I could have updated my own plugin with malicious code? For example, my plugin lets users create a phone number shortcode - but in the update, I could have changed the code to check if a plugin such as WooCommerce was installed and forward on their customer data to an external location. Are there procedures in place to prevent such things? It worried me slightly because I have many plugins written by other developers on my website and I update them without checking what changes have been made all the time!
**TLDR: No. It's all about trust.** So there are some very basic checks on wp.org but generally this can happen (and probably also does happen from time to time). Of course if something like this happens and people notice it wp.org can block updates or replace them with something safe. Also have a look at the WordPress.org Theme and Plugin Repositories section. What you can do is not really any different than what you'd do whenever you install software, things like: * look at the source code * research on the plugin and/or the developer to decide if they deserve your trust * talk to other people about the plugin * do not randomly install plugins you come along * hire someone to do audits * ...
stackexchange-wordpress
{ "answer_score": 9, "question_score": 7, "tags": "plugins, security, svn" }
How to set status codes such as 401 and 403? Setting a 404 in WordPress can be done quite easily using the `set_404()` method of `WP_Query` and the `status_header()` function. Here's an example taken from `WP::handle_404()`: $wp_query->set_404(); status_header( 404 ); nocache_headers(); If I wanted my tag archive to be accessible to authenticated users only, setting a 404 page for non-authenticated users wouldn't make sense because the resource does exist, it's just not available to logged-out users. **My question** How would I set a 401 in WordPress?
The same way you would in any other PHP program: header("HTTP/1.1 401 Unauthorized"); exit; WordPress has special handling for 404 because there's a 404 template. Usually if something happens such as a 401, there is no special template, but you can make use of `wp_die` which will show a message in a simple UI header("HTTP/1.1 401 Unauthorized"); wp_die( 'forbidden' ); This will show the message in a white rectangle with rounded edges and sans-serif text on a gray background, then call `exit`/`die`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, http" }
Detect inside a custom query the kind of post type to assign custom classes I have created the following query in order to get several post types in a custom page, which so far works: <?php $args = array( 'post_type' => array('things', 'people', 'post'), 'posts_per_page' => -1, ); $query = new WP_Query( $args ); $postcount = 0; ?> <?php if ($query->have_posts()) : ?> <?php while ($query->have_posts()) : $query->the_post(); ?> <?php the_title( '', '', true ); ?> <?php $count++; // Increase the count by 1 ?> <?php endwhile; endif; // END the Wordpress Loop ?> <?php wp_reset_query(); ?> I want to have each post type with a class, or several classes. If it is a people custom post type, add the class people around. How can I do it?
The `post_class` function will do this for you automatically within the loop: <div <?php post_class(); ?>> which will add some combination of these classes: * .post-[id] * .[post-type] * .type-[post-type] * .status-[post-status] * .format-[post-format] (default to 'standard') * .post-password-required * .post-password-protected * .has-post-thumbnail * .sticky * .hentry (hAtom microformat pages) * .[taxonomy]-[taxonomy-slug] (includes category) * .tag-[tag-name] You can also get just the post type within the loop via the `get_post_type` function: <?php echo get_post_type(); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, wp query, customization" }
resize chat bar on mobile Like in the following picture I would like to make the chat bar on shop pages a bit smaller on mobile devices for this page: **ergotopia.de** I tried it with this code, which makes it smaller but the opened window as well (like you see in pic). @media (max-width:849px){ .single-product.zopim{ margin-left: -10px; margin-bottom: 38px!important; width: 37px!important; } } How to adjust this code, so the bar is small, but the opened window as big as normal? I also tried this, but without success: @media (max-width:849px){ .single-product.zopim{ margin-left: -10px; margin-bottom: 38px!important; .single-product.zopim .jx_ui_Widget{ width: 37px!important; } } ![enter image description here](
Use Below CSS to achieve your goal, make min-width of button_bar to auto and hide the button_text @media (max-width:849px){ .meshim_widget_components_chatButton_Button .button_bar{min-width:auto;} .meshim_widget_components_chatButton_ButtonBar .button_text{display:none;} } Thanks
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, mobile" }
create parent and child product structure I ma new in **Worpress** i have product data parent and child structure basically i worked in **magento**. in **magento** i create product **(configurable for parent products)**and **(simple product for child products)**. but in **wordpress** i don't know how to create like parent and child products Products structure Please help me how can i do it? one more thing i have a large catalog so i have to import Data from Csv File I will be very tankful Thanks
It sounds like what you need is WooCommerce. With WC you can create a product, set it as a 'Variable Product', and create individual variations with their own prices, SKUs etc. that customers will be able to choose from a dropdown in your store. As for importing data from a .CSV, there are plenty of plugins out there that will allow you to do this. WordPress isn't like Magento in that all it is is a website building tool. If you want to do more with your site, you need Plugins or custom code, the former being the much simpler solution.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "e commerce" }
Enqueueing scripts and styles multiple CPTS I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far: function fhaac_admin_enqueue_scripts(){ global $pagenow, $typenow; if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') && $typenow == 'fhaac' ){} } The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work. Help would be greatly appreciated. Cheers
There is a built-in function that you can use, instead of globals. The `get_current_screen()` function allows you to get the information associated with the current page. One of its return values is `post_type`. So you can check against an array of post types to see if anyone matches. function fhaac_admin_enqueue_scripts(){ $screen = get_current_screen(); if ( in_array( $screen->post_type, array('fhaac','blabla')) && $screen->base == 'post' ) { // Do something } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, wp enqueue script, wp enqueue style" }
Would deactivating the Simple 301 Redirects plugin deactivate the 301 redirects themselves? One of the websites I'm working on is on the same domain as a previous version that was built with Magento. Due to this, the Google Search Console found _thousands_ of 404 errors. Using the aptly named Simple 301 Redirects plugin however, I've been able to patch these holes in our dinghy, and have submitted the sitemap to the Search Console every time I've gone through and added more redirects, and as of today, it returns only three 404s for desktop and one for mobile. However, the site in question is getting heinously sluggish, and I suspect that storing or acting on the data for this plugin is partly responsible for this, so I would like to either deactivate it for the time being or clear its contents. Will doing either of these deactivate the 301 redirects? And do I have to worry about deactivating them if I have submitted my sitemap?
**Yes** , the redirects will no longer exist if you deactivate the plugin. I've just manually checked in the plugin's files. Your redirects get saved to a option named `301_redirects`, the plugin then hooks into `init` with its `redirect()` function, which does what it is named after. This means once you deactivate the plugin, this option won't be checked anymore and more importantly, no redirects will be issued.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins" }
Different Configuration for the_excerpt() I am creating a basic website with wordpress. here i making some layout for different pages. In different page, i will show different post type. and i need different configuration `the the_excerpt()` function. since in service page i need to show 150 character or 40 words of post content but in blog page i need to show 250 character or 100 word of post content. and then need to show button or only read more text. i tried the following but it changes the function globally: function wpdocs_custom_excerpt_length( $length ) { return 10; } add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 ); function wpdocs_excerpt_more( $more ) { return sprintf( '<a class="read-more" href="%1$s">%2$s</a>', get_permalink( get_the_ID() ), __( 'Read More', 'textdomain' ) ); } add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
Maybe you should simply use the wp_trim_words function to achieve what you want. Simply pass the get_the_excerpt value in it. `<?php $trimmed = wp_trim_words( $text, $num_words = 55, $more = null ); ?>`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, functions" }
Root-relative paths being rewritten on 'Edit Page' I'm helping my wife migrate a WordPress site for an organization that she is a part of. When we exported the database, I ran a `sed` command in bash to convert instances of `//previousDomain/path` to just `/path`, and this has seemed to mostly work. However, whenever we edit a page that has a root-relative link, the link is appended with a domain name, that we believe is related to some previous hosting in the past, but is neither a valid domain anymore, nor is present anywhere in our database files (excepting for the pages we have edited) or the php code itself. (The change is from `/path` to ` It smells like this might have something to do with JetPack, but we cannot find any toggle or field to prevent this from happening, and, as far as we can tell, certain content settings are contingent on JetPack. However, we do not know for certain if this is the case.
WordPress is strongly opinionated about using absolute URLs. It’s not right or wrong, just the way it is. One of the reasons for their decision is exactly the unholy complexity of _migrating_ relative URLs, which can be _very_ hard to adjust when moving levels is involved. If existing WP install is using relative URLs, then someone had to go extra mile to make that adjustment. It is hard to guess what they have done and how. For a long term solution practical recommendation is too comply with WP native approach and normalize to using absolute URLs.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, urls, migration" }
Use wp_update_user to update custom column in wp_users table I've added a new column to `wp_users` table. Now I'd like to update it with `wp_update_user()`, however though the method returns no errors, no value is being saved. `wp_get_current_user` is returning the new column, but the value is empty. Does it mean `wp_update_user()` can handle only standard columns? Couldn't find anything about that in docs. I am aware of the meta key-value table for user defined columns, but it would be more convenient to have new field in user table in my scenario. The code is simple: $user_info = wp_get_current_user(); $user_info->creditBalance = 44; $user_id = wp_update_user( $user_info ); // doesn't seem to update the creditBalance
It is not a good practice to add/remove columns to/from the core tables in WordPress. There is no guarantee that the very next update doesn't change this table's behavior, or even overwrite your column. Your best approach is to use metadata as you mentioned. But, if you need to do this for some reason, you can do it by writing your own SQL query. // Get current user's data $user_info = wp_get_current_user(); // Get its ID $id = $user_info->ID; // Set the credit balance $creditBalance = 44; // Update the custom column function update_custom_column( $id, $creditBalance ) { global $wpdb; $wpdb->query( $wpdb->prepare( " UPDATE $wpdb->users SET creditBalance = %d WHERE ID = %d", $creditBalance, $id ) ); } However, working with Database is tricky, and can be dangerous. Be careful.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "users, user meta" }
Orderby ASC changes to DESC in WP_Query I am trying to get posts in Ascending order using WP_Query, $args = array( 'date_query' => array( array( 'year' => $ppy, 'orderby' => 'post_date', 'order' => 'ASC', ), ), ); $query = new WP_Query( $args ); But I am getting posts in descending order, I var_dumped the query and noticed that order is still DESC, > [request] => SELECT SQL_CALC_FOUND_ROWS wpqk_posts.ID FROM wpqk_posts WHERE 1=1 AND ( YEAR( wpqk_posts.post_date ) = 2017 ) AND wpqk_posts.post_type = 'post' AND ( wpqk_posts.post_status = 'publish' OR wpqk_posts.post_status = 'acf-disabled' OR wpqk_posts.post_status = 'private' ) ORDER BY wpqk_posts.post_date DESC LIMIT 0, 10
You've made "orderby" and "order" part of the date_query sub-array. "Order" parameters belong to the main parameters array. I can't vouch for the part of your code that concerns the year and the above-undefined variable $ppy, but if you want the posts from a specified year in ascending order by 'post_date' (which is the default), you'd try: $args = array( 'date_query' => array( 'year' => $ppy, ), 'order' => 'ASC', ); You can leave off 'post_date', since it's the default, but it doesn't hurt to specify if you've got a lot else going on that may potentially change the query.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, order, date" }
Get ID of current taxonomy in register_rest_field I have a term field created with types plugin and attached to the "category" taxonomy. I need to get this field in the api rest. You cant get the termmeta in types plugin like this types_render_termmeta($slug_term, array("term_id" => $term_id)); I don't know how to get current category id in `register_rest_field` function. register_rest_field( 'category', 'color', array( 'get_callback' => function() { $term_id = "DONT KNOW HOW TO GET IT"; $color = types_render_termmeta('color-de-categoria', array("term_id" => $term_id)); return $color; } )); Thanks in advanced.
The `get_callback` part is generated within the `WP_REST_Controller::add_additional_fields_to_object()` method with: $object[ $field_name ] = call_user_func( $field_options['get_callback'], $object, $field_name, $request, $this->get_object_type() ); That means the callback has four input arguments: 'get_callback' => function ( $object, $field_name, $request, $object_type ) { // ... } and for the requested _category_ object, we can get the term id with: $term_id = $object['id'];
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "categories, rest api, term meta" }
Customizer: How do you add HTML to control labels? I have a simple control that displays a checkbox in the Customizer: $wp_customize->add_setting( 'display_about_text', array( 'default' => true ) ); $wp_customize->add_control( 'display_about_text', array( 'label' => __( 'Display Text', 'my_theme_name' ), 'type' => 'checkbox', 'section' => 'about' ) ); I would like to bold `Display Text` in the Customizer, so I changed the label line to: 'label' => __( '<strong>Display Text</strong>', 'minitheme' ), However, it just outputs the HTML tags in the Customizer like this: `<strong>Display Text</strong>` How do I get it to display bold instead of outputting the HTML? I've run into this problem several times when I try to output HTML in the Customizer. Same problem with `esc_html()`.
You should use CSS for this. For example: #customize-control-display_about_text label { font-weight: bold; } Enqueue the stylesheet for this at the `customize_controls_enqueue_scripts` action. If you must use JS to modify a control, then note that I would not advise using `jQuery.ready` in the other answer. You should instead make use of the Customizer JS API to access the control once it is ready, for example enqueue a script at the `customize_controls_enqueue_scripts` action which contains: wp.customize.control( 'display_about_text', function( control ) { control.deferred.embedded.done( function() { control.container.find( 'label' ).wrapInner( '<strong></strong>' ); }); }); This pattern can be seen in core actually in how the `textarea` for the Custom CSS feature is extended: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "customization, theme customizer" }
Disabling 'posts' in Appearance > Menus I need to 'soft' disable posts in a WordPress site. By that I mean I am hiding the 'Posts' menu item from admin... and not much else. I would also like to disable 'posts' from appearing in the Menu admin. This can already be turned off by deselecting it from 'Screen Options', but is there a way to do this programmatically and, as a bonus, also hide the 'posts' checkbox from the Screen Options panel?
We can use the `register_post_type_args` filter to adjust how the `post` post type is displayed in the backend with e.g.: add_filter( 'register_post_type_args', function( $args, $name ) { if( 'post' === $name ) { // $args['show_ui'] = false; // Display the user-interface $args['show_in_nav_menus'] = false; // Display for selection in navigation menus $args['show_in_menu'] = false; // Display in the admin menu $args['show_in_admin_bar'] = false; // Display in the WordPress admin bar } return $args; }, 10, 2 ); More info on the parameters here in the Codex.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus, admin, screen options" }
Is it better to add to style.css or create your own css when using a template? I downloaded an HTML website template and converted it to a wordpress theme. I know wordpress requires a file called style.css (which came with my template). If I want to make my own custom styling in my wordpress site, is it best practice to just edit the style.css file? Or to create my own css file and add it in functions.php? I know there's also a section in the wordpress editor to add custom lines of css but that seems dangerous to me as I don't know where it's putting that code. Thanks,
It solely depends on you. You can go with both the options. As you are developing the custom wordpress theme from scratch you can add the code into themes default style.css. If you are using any another css file the better way to do it is to insert it directly into the header file in place of calling it via hook in functions.php.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Woocommerce: How to change the add to cart text in a certain category? I already change the add to cart text in global product remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 ); add_action( 'woocommerce_after_shop_loop_item', 'add_cart_button_replace', 10); function add_cart_button_replace() { global $product; $link = $product->get_permalink(); echo do_shortcode('<a href="'.$link.'" class="button addtocartbutton">+show OFFER</a>'); } but, in a certain product category page like here, where I have a _free-products_ term in `product-category` custom taxonomy and I want to change the add to cart text into **+choose me** with add to cart link.
You can use the `has_term` function to check for the desired term. function add_cart_button_replace() { global $product; $link = $product->get_permalink(); $button_text = __('+show OFFER', 'woocommerce'); // check if the current product has a "product-category" of "free-products" if(has_term('free-products', 'product_cat', $product->get_id())) $button_text = __('+choose me', 'woocommerce'); echo do_shortcode('<a href="'.$link.'" class="button addtocartbutton">' . $button_text . '</a>'); } You can also learn more about `has_term` function. **Update** : change `product-category` taxonomy to `product_cat` as per your comment.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom taxonomy, woocommerce offtopic" }
Do I need both jquery.js and jquery-migrate.min.js? I am managing this blog. As you can see, it loads both `jquery.js?ver=1.12.4` and `jquery-migrate.min.js?ver=1.4.1` Do I need both of them, or I can safely remove one of them? Isn't the `jquery-migrate.min.js` the newest version of jquery.js? How do I know if I can remove one of them or not?
As stated in the official blog of **jQuery**. Note that **WordPress** is mentioned in the quote. > # jQuery Migrate 1.4.1 released, and the path to jQuery 3.0 > > Version 1.4.1 of the jQuery Migrate plugin has been released. It has only a few changes but the most important of them fixes a problem with unquoted selectors that seems to be very common in some **WordPress** themes. In most cases Migrate can automatically fix this problem when it is used with jQuery 1.12.x or 2.2.x, although it may not be able to repair some complex selectors. The good news is that all the cases of unquoted selectors reported in **WordPress** themes appear to be fixable by this version of Migrate! A quick answer to your question; **yes** you can remove the _jQuery migration_ script and if you don't see any unwanted behavior after the removal of the script, then it's safe to say that you can completely remove the reference migration script. Can be read in here
stackexchange-wordpress
{ "answer_score": 8, "question_score": 8, "tags": "jquery" }
Remove meta box except on category pages To disable custom fields except on category pages, how would I check if it's a category page? Maybe it would be like this: add_action( 'admin_menu', 'remove_custom_fields' ); function remove_custom_fields() { if( /* code to check if page is not category page */){ remove_meta_box('postcustom', 'page', 'normal'); } But I don't know how to do the check - I tried with $screen = get_current_screen(); if($screen->taxonomy != 'category') { //etc} but that didn't seem to work in the `admin_menu` action, but I could use it with the `current_screen` action, but that's the wrong place to remove the custom fields I guess. \---- EDIT ---- I realized that the category pages does not seem to have custom fields available , so it won't actually matter if I exclude the category pages from the removing of custom fields.
You Can use ACF Plugin to add a custom fields just for categories. Add a new Field Group and set location to any of two settings:![acf](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "metabox, actions" }
How does WordPress create its database during installation? I am new to WordPress and I'm trying to understand it. I searched for a .sql file in WordPress script but couldn't find any. Wm kinda confused and want to know where the database entries and commands that create the database during WordPress installation is located in the WordPress script.
schema.php file holds create the database table on installation You will get that file in wp-admin/includes/schema.php Hope you have get your answer.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "database, scripts" }
Is there a way to have admins that are logged in to wordpress not have to enter the password for password protected pages while browsing the website? The goal is so they can log in to WordPress but then browse the site as a normal user but not have to enter passwords for password protected pages. I am just using the built in password protection WordPress provides on pages and posts, via the visibility setting under the publish options. There are about 80 pw protected pages each with a different password so the cookie that WP uses won't work in this situation either.
Since 4.7 you can filter the post_password_required function: function my_admins_dont_need_password( $required ) { if ( current_user_can( 'manage_options' ) ) { $required = false; } return $required; } add_filter( 'post_password_required', 'my_admins_dont_need_password' ); Replace `manage_options` with whatever capability you want to use to allow users to skip the password form.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "admin, password" }
How do I add one more status as "edited by editor"? How do I add one more status as "edited by editor"? The reporter write an article. Then editor edit the article and set the status as "edited by editor” Is that possible? ![enter image description here](
This feature has been proposed for development over 7 years ago with no results up to now. But, you can scrutinize and/or try the WP Statuses plugin from one of the BuddyPress contributors.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "editor" }
Woocommerce - remove sale price field from dashboard Hello i use woocommerce and i want to remove the field from the admin panel. How can I do it right? ![enter image description here](
You cannot remove the field using a code but you can disable using the sale price across the store. **To disable sale price** function custom_wc_get_sale_price( $sale_price, $product ) { return $product->get_regular_price(); return $sale_price; } add_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 ); add_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 ); **To hide this field,** you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic" }
Adding a section to admin menu for global settings Bear with me a moment as I am still relatively new to WP dev. I am currently building a custom site that loads certain blocks on pages using get_template_part(); . So for example, the home page will have it's own relevant content but will also include generic content (subscribe, contact, awards...). I do not want these sections to be hard-coded but instead leave them as editable, ideally as an additional menu option within the admin area so the user only needs to change it in one place. My current solution is not ideal. I am using the Advanced Custom Forms plugin and placing the required text in the default text area. However, even if this is updated it will not update all pages globally and the user will need to go into each individual page to re-publish the it with the new content. Is it possible to code a new option onto the side menu that will store global settings for template parts?
The Customization API is what you're after. Lets you define site-wide settings for theme/plugin customization.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, globals" }
Should wordpress_logged_in cookie exist while logged out? I noticed that while logged out on my Wordpress site, my browser is sending this `Cookie` header with every request (obfuscated for security): > > Cookie: wordpress_logged_in_OBFUSCATED=flimm%7COBFUSCATED; PHPSESSID=OBFUSCATED; wordpress_logged_in_OBFUSCATED=flimm%7COBFUSCATED;wordpress_test_cookie=WP+Cookie+check > For readability, here are the cookies in separate lines: * `wordpress_logged_in_OBFUSCATED=flimm%7COBFUSCATED` * `PHPSESSID=OBFUSCATED` * `wordpress_logged_in_OBFUSCATED=flimm%7COBFUSCATED` * `wordpress_test_cookie=WP+Cookie+check` Is this normal, that even though I am logged out, I still have a cookie set `wordpress_logged_in_...`, with my old username in it? Is it normal to have more than one `wordpress_logged_in_...` cookie set, whether logged in or not?
The function `wp_logout` (< calls the function `wp_clear_auth_cookie` (< which sets the expiration dates of all involved cookies to something in the past. Also for the `LOGGED_IN_COOKIE`. Hence, what you observe is strange. For sites that I maintain, the cookie will be cleared when I log out.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "cookies, authentication" }
url rewriting for custom post types I have a post-type Collection with custom-post-type categories. I want the following url structure: www.baseurl.com/collection/current-category-name/postname How do I accomplish this?
Yes you can use the rewrite parameter when creating your custom post type: register_post_type( 'example_type', array( 'labels' => array( 'name' => "Example-Type", 'singular_name' => "example-type" ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'the-url-you-want', ) ); } You will need to reset your permalinks for it to take effect as well. EDIT: function custom_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'category' ); if( $terms ){ return str_replace( '%category%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'custom_post_link', 1, 3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, url rewriting" }
How to check if site is created by wordpress? Can anybody tell me that how to check if someone created his site using wordpress?
Yes Probably. Just Type `wp-admin` at the end of your domain like following:
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization" }
Why is wordpress searching for @2x images? I've created some images for my site with the following path: /wp-content/themes/my-theme/images/my-image.png I edited my sites HTML to include this image (and other's like it). Now in my console I have a whole bunch of error messages: Failed to load resource: the server responded with a status of 404 (Not Found) - /wp-content/themes/my-theme/assets/images/[email protected] I looked up @2x and I found that it has to do with different pixel density images. But why is it even trying to find this image? I didn't tell it to. Is this something wordpress does automatically? Do I have to create a @2x image for every image I add to my site? And why is it searching the assets folder?
Despite having no plugins installed through wordpress, I did have retina.min.js being enqueued in my `functions.php` file from the template I downloaded. Retina.min.js (source: < looks for high resolution versions (denoted with suffix @2x right before the extension) of each image in your site and attempts to replace them if any are found. Since I did not plan on using this feature for the time being, I commented it out of my `functions.php` file and I now have a clean console.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "images, templates" }
Feeds are showing where Post archive page should be **The problem:** Archive/category page is showing up as a feed. https:// site-example.com/show/ shows a feed instead of posts. **Details:** Updated WordPress to 4.8. Everything else is updated. The links must stay the same. There is a feed with the same title at: \-- https:// site-example.com/feed/show/ Using wp-forge theme with a child theme. **What I've tried:** Created a template with various names as per the Codex. Disabled and removed all plugins and themes. Deleted and removed cache plugins. Disabled all feeds.. those 2 are still showing up.(/feed/show and /show) I'm sure someone will have an answer already for this. It can't be a new issue... I'm just new to feed management. Thanks in advance for any help! :)
After looking for various solutions I have come up with an alternate solution that has solved my issue. I simply removed the /%category%/ base from the permalinks and installed the "No Category Base (WPML)" plugin and WordPress found my category template and is now showing all the posts from the "Show" category as an archive. :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, podcasting" }
Placing a background image with text over it I'd like to place an image of a blueprint behind a section of text. Things I'm worried about: * Image will be tiled * Image will stretch weird * Image will look bad on different screen resolutions What's the best way to incorporate a background image without it looking bad on different formats? Here is a mockup of what I'm talking about:
Depending on how important the image is, can you do it with CSS. CSS3 has an attribute called background-size:cover. This does not stretch the image,but it will scale it until it fits the whole area. Depending on the sizes some parts could be hidden. w3schools on background-size
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, html, custom background" }
Wordpress menu deletes when trying to add a hook I'm trying to customize the default Wordpress menus. Added this to my functions.php file and it makes my menus disappear. What is wrong? function custom_novice_menu($args) { $defaults = array( 'container' => 'div' ); } add_action('wp_nav_menu', 'custom_novice_menu'); Here is some documentation on wp_nav_menu()
I don't think there's `wp_nav_menu` action. Perhaps you want the `wp_nav_menu` _filter_ (doc)? function custom_novice_menu($args) { if( 'primary' == $args['theme_location'] ) // only apply to the right menu { $args['container'] = 'div'; } return $args; } add_filter('wp_nav_menu', 'custom_novice_menu');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, functions, menus, shortcode, widgets" }
What does this message from WP_DEBUG mean? I have been having server 500 errors on 3 separate WordPress websites over the last while. (The problem BTW does seems to be related to the wordpress_logged_in***** cookie because deleting that always solves the problem temporarily) but this is not really my question ... In the course of investigating this issue I turned on debugging and logging on two of he websites and I got this message in each site > [07-Jul-2017 12:21:51 UTC] WP_Community_Events::maybe_log_events_response: Valid response received. Details: > > {"api_url":" events trimmed."}} Does anybody know what it might be referring to. The IP address is local, and it's from MY IP provider, but it's not my IP, or the IP of my client, plus it's the same IP on both sites ( which have no connection except me ) I couldn't find much information but this page < seems to suggest that it might not be an error. **Could anyone confirm this?**
The log message says "Valid response received" and the response code in the JSON object is 200, which is typically a response for a success request. I think it is not an error. Note that the docs for `WP_Community_Events::maybe_log_events_response()` says "All responses are logged when debugging, even if they’re not WP_Errors". I understand that if `WP_DEBUG` is on, then all responses are logged, even when success. The IP, according with the code comments, _usually_ is the same that made the request. In some cases it can be different (for example when the IP is private). The IP used in the request is the client IP converted to a network ID in order no anonymize the ID. See `WP_Community_Events::get_unsafe_client_ip()`. Update: after viewing the source code, all responses are logged when `WP_DEBUG_LOG` is on, not just `WP_DEBUG`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wp debug" }
Direct link to post when multiple categories are selected I have an custom Permalinks format: `/%category%/%postname%` It works fine as each posts gets link base on category, like `category1/sub-category1/post-title`. The problem is, when I assign the post to several categories, I cannot control which "path" will be chosen for link under direct link: ![enter image description here]( On given example, the post has been added to category `specjalne/produkty` as well as `kosmetyki/do-twarzy`. I would like the direct link to point for `kosmetyki/do-twarzy/...` instead of `specjalne/produkty/...` Also, `get_permalink()` returns the same link as direct link field (and I want it to change to `kosmetyki/do-twarzy/...`). The best solution would be to never create path based on `specjalne/produkty` if there is any other option available - because it should be the lowest priority path.
Install the Yoast SEO plugin to enable this: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, breadcrumb" }
List of all inbuilt Wordpress shortcodes I am newbie in wordpress but not very new. When I came to know that wordpress have inbuilt shortcodes like audio, video, gallery, playlist. I have searched for a list of inbuilt shortcodes that WordPress provides but I did not get anything except above can anybody provide me a link which has a list of inbuilt wp shortcodes. And one more thing if WordPress provide more inbuilt shortcodes are they only work in wordpress.com I know that you guys may thing I am a fool or idiot but I want to know.
You can actually list all of the available shortcodes for your WordPress installation by using the following code: <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
stackexchange-wordpress
{ "answer_score": 9, "question_score": 4, "tags": "shortcode" }
Add custom column for custom field I created a custom field `bookcode` using the code below. So, how I can add a column for this meta data into my post type manager and make it sortable? function save_bookcode( $post_id ) { if ( wp_is_post_revision( $post_id ) ) return; // save custom field 'bookcode' as CFX+ID add_post_meta( $post_id, 'bookcode', 'CFX' . $post_id, true ); } add_action( 'save_post', 'save_bookcode' );
I adjusted the code for you. You can directly use the code in **functions.php** file. Here is more reference that can help you to understand more. Link 1 Link 2 // Adding Custom Column add_filter('manage_stfic_posts_columns', 'ST4_columns_head_only_stfic', 10); add_action('manage_stfic_posts_custom_column', 'ST4_columns_content_only_stfic', 10, 2); // CREATE TWO FUNCTIONS TO HANDLE THE COLUMN function ST4_columns_head_only_stfic($defaults) { $defaults['bookcode'] = 'Book Code'; return $defaults; } function ST4_columns_content_only_stfic($column_name, $post_ID) { if ($column_name == 'bookcode') { // Now you have to garb the meta value and show. $book_code = get_post_meta($post_ID,'bookcode',true); echo '<span>'.$book_code.'</span>'; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, columns" }
What are the requirements to make the admin toolbar show up on the front end I have done some weird things with a few custom theme pages. Namely, i have bypassed the wp_query and obtained data from a different db. I populate the post object with custom data and then inject this into my theme. Since the toolbar shows up fine normally, there must be some sort of trigger that i am bypassing by not calling the wordpress DB. I am 100% sure the theme is not the cause of the issue here, it is the messing that i have done. However, there are no errors in the code, everything works good. What does the admin toolbar require in order to load? Is there some hook i can call manually in order to make it render? I have tried messing around with the code and info from the wordpress docs <
Daves comment to the question was the solution to this. Because i was calling wp-load.php and bypassing the theme, the template redirect hook was never being called and this prevented the admin bar from appearing on the website. Calling the method listed in his linked answer solved the issue. wordpress.stackexchange.com/a/240152/2807 You can make the admin bar show up by calling _wp_admin_bar_init(); Be careful with it though, I ended up calling it and it somehow started getting cached in the html cache meaning the admin bar got served to users that were not logged in.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp admin, admin, tooltip" }
Easy Digital Downloads (EDD) - Purchase Receipt emails couldn't be logged I'm trying to _log the purchase receipt email_ sent out by the EDD plugin, in the database. But I'm unable to do so. The custom plugin that logs emails is hooked on to `wp_loaded` hook and filters all emails by the following filter. add_filter( 'wp_mail', array( $this, 'log_email' ) ); But the purchase receipt emails are not logged. Note: The custom plugin logs others emails sent. Example, if I use WP Mail SMTP plugin to send a test email, the email is perfectly logged into database. I debugged to see if my hook is invoked at a later point, but I found that EDD sends the purchase receipts emails via `init` hook. I further debugged and found that my plugin is **not** hooked into global $wp_filter var. `var_dump( $wp_filter['wp_mail'] );` Reference: WordPress Action hook sequence Any suggestion is greatly appreciated.
`wp_loaded` hook is fired after `init` hook. So by the time you add your filter, the filter is already called by EDD. You can either change your hook to `init` and use a high priority or use an earlier hook like `plugins_loaded`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, hooks, email" }
How to add all existing Custom Taxonomy to Admin Menu Creations Interface? How to add all existing Custom Taxonomy to Admin Menu Creations Interface? ![enter image description here](
For admin menu creation this document help you. BEST Option for you : **Appearance -> Menus -> Screen Options (Up-right corner) -> select Tags/Product tags**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, menus, taxonomy" }
How can I get rid of the automatically generating <span> tags? I am creating a post in Wordpress and every time I switch to the visual editor, a `<span>` tag is generated automatically. Every one of them are the same, except SCXW104349300 in the code below: R<span class="TextRun SCXW104349300" lang="EN-US" xml:lang="EN-US"><span class="NormalTextRun SCXW104349300">equired. Username used to authenticate the proxy server</span></span> For the word "Required", a `<span>` tag between "R" and "equired" is frustrating. The visual editor seems easy-to-use for larger posts with a lot of bolds and italics, but it seems a table cannot be created in the Visual editor, so I am switching back and forth between visual and text editors, and then I noticed this. Is there any way I can get rid of this?
If you use a child theme, just add this function to your functions.php file: add_action( 'after_setup_theme', 'foobar_setup', 11 ); function foobar_setup() { global $editor_styles; $editor_styles = array(); } This works for me for details follow below links which I used as source of this solution : This post and another one
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
WordPress Screen options does not show any fields I have a Wordpress installation with a modified TwentySeventeen theme. When on any page of the admin I can click the "Screen options" tab and it expands but it is completely empty. Nothing in my theme is disabling this feature as far as I can find. If I read the Wordpress manual pages correctly, it should be enabled by default. Anyone have any ideas?
Ok, found it. Not really Wordpress related but might be helpful to someone anyway. It was my browser ad blocker plugin. Apparently it adds CSS to pages upon loading. The CSS showed as "inline" in the dev tools inspector but didn't show at all when viewing page source code. When checking the CSS of the admin page, I found a lot of things being hidden, amongst which this selector: `[id^="adv-"]` which applied to the screen options. A lot of other selectors had "AD", "Google" and "Twitter" in their names. I did not have any plugin that would add these things but finally figured out it might be the ad blocker, which turned out to be correct.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, screen options" }
random display categories - change url This part of my script runs WordPress categories and displays them in a random order. The problem I'm having is that the url is based upon the categories `ID` There's one category that should go to a different page if clicked in stead of the categories page. So I created a variable and kicked in the url. Created a `if`-statement to see when the `$cat_id` is loaded and then change it. But it only outputs the url multiple times (every found category) What can it be? $category_link = get_category_link( $cat_id ); $custom_link = get_option( 'home' ).'/sub/sub-sub'; echo ' <div class="carousel_items"> <div class="category_image"> <a href="'.($cat_id == 5) ? esc_url($custom_link) : esc_url( $category_link ).'"> <img src="'.get_bloginfo('template_directory').'/images/svg/'.$cat_id.'.svg" /> </a> </div> </div>';
As you are concatenating the result to a href you must wrap the ifelse statement inside another set of parentheses so the result is calculated first and then returned: <a href="'.(($cat_id == 5) ? esc_url($custom_link) : esc_url($category_link)).'">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, categories" }
Easing the download of a regularly uploaded pdf I have a Wordpress page. The user of it, who is not a computer expert, weekly uploads a one-page pdf onto a page. The menu has a link to the page, and then the visitors can click on the ever fresh link on the page and get the current pdf. So this is two steps: menu->page->pdf I would like to have it easier: menu entry -> pdf The problem is, due to the weekly upload, the underlying URL is changing weekly. I am not sure if he could edit the link of the menu entry to have the correct URL after upload -- he is not computer savvy. It is important that he could do this so he need not rely on me. Is there an easy solution for this?
I would use ACF (Advanced Custom Fields) to give the option to add the file to the homepage. Then once a week when he needs to update it he can just go in and replace the existing file by uploading the new one. If the description or anything has to change then you can just add the additional field which he can modify too. Advanced Custom Fields Plugin - < Example of file output: $pdf_file = get_field('pdf_file_field'); if ($pdf_file) { echo '<div class="pdf-link"><a href="' . $pdf_file['url'] . '">Download Now</a></div>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "uploads, links" }
Grabbed Post ID under WP loop, but still couldn't Print Post title <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $post_id = get_the_ID(); ?> <?php echo '<h1><a>' . get_the_title() . '</a></h1>'; ?> <?php endwhile; ?> <?php endif; ?> I used the loop to grab the Post ID, but still the title of that post couldn't be printed on the live website page of that particular post. what is wrong with my approach?
Since you're in a Loop, you don't need to grab the post ID or use `get_the_title()`. Instead, replace line 2 and 3 of your code with: the_title('<h1>', '</h1>'); Or, if you want to include a link as well: <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop" }
How to present a div only when the index.php is accessed for/by the single post pages Suppose there is a div → <div class="only-single-page"> some code </div> How to make sure that this div is there only when the index.php is accessed for the Posts single pages. <?php If is_single() { ?> <div class="only-single-page"> some code </div> <?php } ?> But it didn't worked.
The syntax is wrong. Write the condition as: if (is_single()) { your code here }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, single" }
How to add custom tab page in backend? I would like to learn about create page and tab in admin panel. Please let me know useful hook and filter list.
If you are trying to add menu on the WordPress dashboard on the left panel than there are several ways to do that like in the following links add_menu_page add_options_page add_menu_page adds a menu to the left panel of wp-admin dashboard whereas add_options_page will add a menu under the settings menu.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, admin menu" }
WP .js script file not loading I have looked all over the place and did not find a solution to my problem. I have a child theme where I have a functions.php file where I try to register and enqueue the script the following way: function wpb_adding_scripts() { wp_register_script('my_scripts', get_stylesheet_directory_uri('js/scripts.js', __FILE__), array('jquery'),'1.1', true); wp_enqueue_script('my_scripts'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); And here is the script I am trying to load: $(document).ready(function(){ alert("test"); }) I made sure I have a "js" folder in my child directory where my scripts.js is. But for some reason, this is not working for me. Any one got an idea? Thank you in advance for any help.
According to codex, `get_stylesheet_directory_uri()` does not including a trailing slash. So, you might want to use it in the following way: function wpb_adding_scripts() { wp_register_script('my_scripts', get_stylesheet_directory_uri().'/js/scripts.js', array('jquery'),'1.1', true); wp_enqueue_script('my_scripts'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); ## UPDATE If you want to use jQuery in your scripts, you should do it in one of these ways: 1. Use `jQuery` instead of `$` to avoid conflict 2. Create a self invoking function and pass `$` to it. Take a look at this example: (function($){ $(document).ready(function(){ alert("test"); }) })(jQuery);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "child theme, wp enqueue script, wp register script" }
Find out if post was just updated on post edit screen Is it possible to add an admin_notice to the _post.php_ edit screen in the admin– only if the post was just updated. function my_admin_notice(){ global $pagenow; if ( $pagenow == 'post.php' ) { // Check if the post was just updated... echo '<div class="notice notice-warning is-dismissible"> <p>This is my custom post-was-just-updated admin notice.</p> </div>'; } } add_action('admin_notices', 'my_admin_notice');
I figured it out by looking in WP Core. When you update a post it actually takes you back to the edit posts screen ( _post.php_ ) with a GET parameter of `message=1`. And then it erases that parameter from the url with javascript quickly. So you can find out if posts were uploaded in a plugin by checking: if ($_GET['message'] == 1) { // do something because the post was just updated }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, actions, notices" }
How can ι create my own (custom) WordPress table/list? I don't know exactly how is the correct name, but i want to create my own table like the default wordpress table : ![enter image description here]( I wanted to ask, does the WordPress provide some API to create it?
I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: < Basically, you'll want to create a class that extends `WP_List_Table`: class My_List_Table extends WP_List_Table { // what your table is all about } $myListTable = new My__List_Table(); It is an involved process, but that tutorial seems pretty good. Good luck!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, forms, api, list, table" }
'Customize' button in admin bar for CSS On the WordPress.org site I'm an admin for, we have a `Customize` button in the Admin bar (see very left): ![enter image description here]( This allows us to easily edit CSS on the front end without editing any of our files. I specifically remember reading that this feature allows us to write CSS that won't be overwritten by a theme update. Now the time to update has come, and I'd like to absolutely confirm this. But I can't find any references to this button online. What's this feature called? Is it on everyone's WordPress.org site, or is this some special feature of our theme or perhaps a plugin?
The WP Toolbar's _Customize_ button will launch the Theme Customizer. This is standard on all WordPress sites, but it could be disabled via themes or plugins. WordPress version 4.7 added the _Custom CSS_ feature which will allow you to add your own styles to the activated theme. These styles will not be overridden when updating the theme. > ...custom CSS safely stays available through updating and switching themes, starting fresh for each new theme. Technically, it would be possible for a theme to stomp on any options or theme mods with an update, so you should always make a backup of your database and files before updating.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, customization, themes, css, updates" }