INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Sidebar on the wrong side of the page I'm building a website on WordPress through a child theme based on Dazzling. The website is < The problem I'm having is that the sidebar of my website is being shown on the right side, even though on the theme's configuration on WordPress dashboard it is set to be on the left. The problem seemed to arise when I uploaded the header.php file (I'm not sure if it was when I created header.php or when I created style.css). When I inspect the page, the tag that contains the sidebar (widget area) is div#secondary.widget-area.col-sm-12.col-md-4 . However, I can't find this tag neither on the header.php nor the style.css. Does anyone know how to fix the problem?
I just checked your site, if you want to move the sidebar to the left, add this to your CSS. @media (min-width:992px) { .col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9 { float:right; } } ![enter image description here]( In case you don't know how to add CSS, check this out.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "sidebar" }
.html form added to a page I have an external html form that I would like to add to my wordpress developed site. The form links to other areas in the business like the cashiers, so when customers fill the form out, the content is added to their system. I have seen different ways such as adding raw html and adding as media however these do not allow me to edit the form as the visual composer stops working after I paste in the html code. What other options do I have if any.
I figured out that you can not directly have a html form display correctly on a page. To work around this, I added the html document to the media and then linked directly to this using the generated hyperlink.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms, html" }
Query Concatenation I can't figure out how to properly concatenate my PHP variables in my MySQL query. **$convert_class_id** and **$convert_char_id** are holding numerical values. When I try to activate my plugin I get an error: > Parse error: syntax error, unexpected '=', expecting ',' or ')' $skill_select = $wpdb->get_results( $wpdb->prepare(" SELECT skill_name, char_id, um_id, c.class_id FROM `wp_ml_skill_class` sc JOIN `wp_ml_skill` s ON (s.skill_id = sc.skill_id) JOIN `wp_ml_character` c WHERE c.class_id = " . $convert_class_id . " " AND c.char_id = " " . $convert_char_id . " ")); Thanks in advance.
In SQL statement use placeholders instead of variable: `%s` (string) or `%d` (number). The second argument of `prepare()` is array of variables to substitute into the placeholders. $skill_select = $wpdb->get_results( $wpdb->prepare(" SELECT skill_name, char_id, um_id, c.class_id FROM `wp_ml_skill_class` sc JOIN `wp_ml_skill` s ON (s.skill_id = sc.skill_id) JOIN `wp_ml_character` c WHERE c.class_id = %d AND c.char_id = %d", [$convert_class_id, $convert_char_id]));
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, query, mysql, errors" }
get_posts - get all posts by array of author I have a case like below. ![enter image description here]( Confused how to use the wpQuery to achieve this This is for a single user. Not sure how can i pass the array. global $current_user; get_currentuserinfo(); $args = array( 'author' => $current_user->ID, 'orderby' => 'random', 'post_per_page' => '1', 'order' => 'ASC' ); $current_user_posts = get_posts( $args );
Use `author__in` not `author` as a query parameter. $authors = [ 1, 2, 3, ]; $current_user_posts = get_posts( [ 'author__in' => $authors, 'orderby' => 'random', 'post_per_page' => '1', 'order' => 'ASC' ] );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, get posts" }
Unable to add template to page set as Posts page in WP V 4.6.1 ![enter image description here]( trying to set a template to our blog page which is set as Posts page in WP Admin. The theme is **Twenty Fifteen**. The issue is that the option **Template selector** which appears for all other pages under **Page attribute** menu doesn't appear only on pages set as **Posts page**. Is this an error tied to this version or theme? There are multiple templates used in this website, but none seems to appear for this page.
You cannot set a custom template for the latest posts page. This setting is ignored for it. The template that is used for this page is determined by the Template Hierarchy. ![WordPress template hierarchy]( So if you start at the left for _Blog Posts Index Page_ you'll see that it uses `home.php` for its template, if it exists, otherwise it uses `index.php`. But if your homepage is set to show the latest posts then `front-page.php` will be used if that exists. PS: You're running a 2 year old version of WordPress, and should update as soon as possible.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates, blog" }
update woocommere total value on checkout based on selected payment method i have 2 payment methods .. in one of them i add extra fees How to trigger WooCommerce Ajax which updates shipping calculation on change payment method ?
solved using jQuery jQuery( document ).ready(function() { jQuery(document).on('change','#payment',function(){ jQuery( 'body' ).trigger( 'update_checkout' ); }); });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, woocommerce offtopic" }
How to install Woocommerce without plugin? I followed this guide < Then I installed a Woocommerce folder inside of my theme folder and added some lines in functions.php function mytheme_add_woocommerce_support() { add_theme_support( 'woocommerce', array( 'thumbnail_image_width' => 150, 'single_image_width' => 300, 'product_grid' => array( 'default_rows' => 3, 'min_rows' => 2, 'max_rows' => 8, 'default_columns' => 4, 'min_columns' => 2, 'max_columns' => 5, ), ) ); } add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' ); And I moved files from template folder to parent folder... I went to admin panel and nothing happens...
You cannot do that. From the question's title, it kind of seems you think WooCommece is not a plugin, and you install it using a plugin, but the thing is that WooCommerce is a plugin. You are following a guide called **Template structure & Overriding templates via a theme**, doing that you are only doing so, not installing WooCommerce without a plugin. (sounds funny when you actually say that) There shouldn't be an issue if you simply install it and use it like the rest of the word.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "theme development, woocommerce offtopic" }
How to capture customer's credit card details via PayPal on my checkout page? On my ecommerce website, I don't want customers to leave my website and be directed to PayPal when paying via credit card. Is there a good plugin that shows a PayPal credit card form on my checkout page? Thanks!
You can use WooCommerce PayPal Pro Payment Gateway, it basically does what you are looking for. > Will it offer on-site checkout so my customers don't have to leave the site? **Yes**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic, paypal" }
Advanced Custom Fields - Get value in other plugin file I'm using the ACF plugin and i have a dropdown added to users who have a specific role. The dropdown contains the values Yes and No. That value i need to get in an other plugin, but i couldn't get it to work... This is what is have: $woonfield = get_field_object('wooncheck'); $woonvalue = get_field('wooncheck'); $woonlabel = $woonfield['choices'][ $woonvalue ]; <?php echo $woonvalue ?> Do I need to put the current user ID somewhere or something else? I really have no idea anymore. Thanks!
Per ACF documentation, if you're not getting values from posts, you need to prepend the ID. For users that needs to be `user_` $id = ...; get_field('wooncheck', 'user_' . $id);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, advanced custom fields" }
Simulate Update User button click I have a site running Paid Membership Pro and I'm adding a user membership level via a Webhook from Chargify. I use a function in the Stranger Studios Multiple Memberships Per User plugin < to add the membership level. These users already have an account and role assigned to them, they are just having another membership level assigned. The weird thing is it adds the level however, the end user doesn't have access to the content until I manually edit the user profile and click Update User button. No changes are needed in their profile just to open their user account and click the button. I've tried running the Wordpress wp_update_user() function after adding the membership level and running cURL post to /wp-admin/user-edit.php but still I need to manually save the user profile before they gain access to content. Any help would be extremely appreciated.
Thanks must go to WebElaine as her comment lead me on the right path to solving this. The issue was when the pmprommpu_addMembershipLevel() adds the membership level it sets the endate to 0000-00-00 00:00:00 running a $wpdb->update to set this to NULL fixed the problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, users" }
Display "add to cart" button on every listing in product category page? I need to place **Add to cart** button at every product on the page of certain category as shown below ![page's screenshot]( How can I achive this? Link to subject page oma-fintess.com.ua
<a href="<?php the_permalink(); ?>" class="more">More info</a><?php if($available){?><a href="<?php $add_to_cart = do_shortcode('[add_to_cart_url id="'.$post->ID.'"]'); echo $add_to_cart; ?>" class="more">Buy now</a> <?php } This code solve my problem as expected. WooCommerce documentation reference
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, woocommerce offtopic, archives, buttons" }
Get post content with all filters applied, knowing post id I've just started working with Wordpress and I need to get the content of a post with all filters applied (eg. the html content of the post as appears on the page after all the available filters have been applied). I am using this: $post = get_post($postid, OBJECT, 'display'); echo $post->post_content; I am getting content like this, including some tags added in by the visual composer plugin: ...[vc_row][vc_column][vc_column_text]Lorem ipsum[/vc_column_text][/vc_column][/vc_row]... Looks like this is the database value of that field and no filters are being applied. Could anyone help me get the post_content (with all filters applied) of a post knowing the post id?
You need to pass that through the `the_content` filter like so: `echo apply_filters( 'the_content', $post->post_content );`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, filters" }
Add border/background color/color text of embedded pop-up I have been trying in vain to give color to my subscription pop-up. I believe it must be something quite easy and straight-forward but, since I do not understand a thing about html, I really need your help. Below follows the code. PS: I would like to have a strong border line in red, all the pop-up itself in black and the text in white. #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; } ## Text title Text 1. Text 2. **Name** **Email Address *** **** (function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[1]='FNAME';ftypes[1]='text';fnames[0]='EMAIL';ftypes[0]='email';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='ADDRESS';ftypes[3]='address';fnames[4]='PHONE';ftypes[4]='phone';fnames[5]='BIRTHDAY';ftypes[5]='birthday';fnames[6]='MMERGE6';ftypes[6]='imageurl';}(jQuery));var $mcj = jQuery.noConflict(true);
## Simple CSS Styling Add this to your CSS #mc_embed_signup { background:#000; color:fff; border:1px solid red; padding:20px; } ## Adjust to Your Preferences You can adjust the border width by giving it a larger than 1px value, such as this: `border:8px solid red;` These are the colour values used. They are called Hexadecimals (Hex): > `#fff` = White > > `#000` = Black
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom background" }
Install wordpress in backend with Existing html website alive I have created a HTML website and want to shift to wordpress. I have another theme so I will be copying my content to that theme. But I want to keep my HTML website alive till I am done with the shifting to wordpress. Is there any way I can install the wordpress database and install my theme and start my word in backend whereas the HTML still stays alive. I am a beginner in this so please spare me for any errors. Thank you.
## WordPress in Sub Directory Just install your WordPress site next to your HTML site in a subdirectory such as /mysite. While you are working on the WordPress site, it would be found in < Then once you are ready to switch to the WordPress site, you can just change the site url to < in the WordPress settings. This will then run your WordPress site via that same URL :) ![enter image description here]( ![enter image description here]( ## Safty Check 1. If you've not used local URL's in your custom links, you will have to update these manually when you change the WordPress Site URL. 2. After you have changed your URL to the root URL, it is best to scan the site and database to make sure no old URL were left unchanged. There are many good plugins and scripts that can do that. Velvet Blues Update URLs is one I use when transferring sites to new domains or changing from HTTPS.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "installation" }
Showing a different logo for a custom post type We are looking for a way to show a different logo for a custom post type than to the rest of our site? The custom post type is created with Custom Post Type UI… with ACF and Divi as theme. We have tried the following: if ( is_singular('customer') ) { ?> <img src="<?php bloginfo('template_directory'); ?>/dist/images/logo-customer.png" alt="Logo Customer"> <?php } else { ?> <img src="<?php bloginfo('template_directory'); ?>/dist/images/logo.png" alt="Logo"> } When adding this to functions.php we get an error “syntax error, unexpected end of file” Not sure what we are doing wrong here but we can't seem to get this code to work
You're missing the `<?php` tag before the closing bracket, so it's not being processed. Your code updated below: <?php if ( is_singular('customer') ) { ?> <img src="<?php bloginfo('template_directory'); ?>/dist/images/logo-customer.png" alt="Logo Customer"> <?php } else { ?> <img src="<?php bloginfo('template_directory'); ?>/dist/images/logo.png" alt="Logo"> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
site identity will not update my host is bluehost. i use wordpress to work on site currently. i am using trends theme. my site is www.sylverwolfenterprise.com i spelled a word wrong and forgot to upload an image for my site identity. When I tried to correct it, it does not take. I have tried turning off server side cache. I have cleared cookies and cache on my side, I have run ccleaner, I have deleted everything, saved draft, then publish to no avail. what am i missing?
Try loading the page with a query_string on the end, to make sure you're not still getting a page cached somewhere. like <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin" }
How can I store user preferences in WordPress and retreive them later? I have a WordPress website where I want to give users some options to sepcify how they want to see the site. For example, they can choose from a given set of fonts, menu color etc. I am assuming this will mean that I have to create a webpages where logged in users can check different boxes to set their preferences. Is there a way to do that using something that takes advantage of the WordPress ecosystem instead of coding everything from scratch? Basically, I want a dedicated webpage which logged in users can visit to set their preferences. :) How can I do that in a way that allows me to take advantage of WordPress without coding everything myself? To be clear, I have no problem in writing the code. What I meant to ask was if there are any WordPress functions or plugins that I can rely on to make it easier. :)
You can have two different approaches, Both require some coding. 1. **Using a Plugin** In your case, there are a lot of good plugins out there but If I'd like to give a name, you'll have to check `Profile Extra Fields by BestWebSoft` (I think it doesn't require a lot of coding) and `Advanced Custom Fields` (It requires some coding but it worth, you can take a look at this article to read more about how to add user fields in ACF) 2. **Coding from scratch using WordPress's built-in user functionalities** There are very good built-in functions like `get_user_meta`, `add_user_meta`, etc. They're very easy to use and they're very well integrated inside the WordPress platform. You can learn more about these functions and some more by looking into the `users.php` file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, database, users, cookies" }
Is there any action filter/hook for validating a custom field before publishing the post? I have a custom filed called `xxxx_url`. `xxxx_url` should be unique. So, before publishing the post, I want to make sure that `xxxx_url` is unique or not? If it isn't unique, publishing the post should be reject. I tried `publish_post`. But that isn't the correct one, since it triggers when we publish the post. I want to run my code just before the publish.
At the beginning of `wp_insert_post`, the function that saves/updates a post, there is a filter called `wp_insert_post_empty_content`. By default this filter checks whether the title, editor, and excerpt fields are all empty, in which case the save process will be halted. However, since all the fields to be saved are passed to this filter, you can expand this filter to include any other test to determine whether the post should be considered empty. It would be something like this: add_filter ('wp_insert_post_empty_content','wpse312975_check_unique_url',10,2); function wpse312975_check_unique_url ($maybe_empty, $postarr) { // extract custom field from $postarr, check uniqueness if ($unique) return false else return true; } Note: the function must return 'true' to halt the saving process. If the custom field is not unique you may also want to echo a warning.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 11, "tags": "custom field, filters, hooks, actions" }
Edit copyright in Hesita Child Theme I am currently using a Hesita Child Theme. I want to edit the copyright text in the footer. I have found the text I need to edit in 'hestia/inc/views/main/class-hestia-footer.php' I think know what code to edit, however, I do not know how to make that change in the child theme. I have changed it before, but it has been reverted back to the original after a parent update. Can anyone help? Cheers
## You Could Also Try This Cheeky Little Trick :) If you just want a quick and easy, no fuss change, you can do this to the Hestia theme copyright area. Just add the following code to your child theme CSS or to the WordPress Customise > CSS area. .copyright a { display: none; } .copyright:before { content: "My site"; } .copyright:after { content: " Craig"; } Alternatively, you could just hide it all. .copyright { display: none; } ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "child theme, copyright" }
Restrict a search to a custom post type I have a search form in the home page and search form in the sidebar. Is it possible to make the search form in the home page show results as per a specific template and make the sidebar search form show a different template? i want to make the homepage search box to show results in different way. Its a custom post. so if user uses that form it should only have data from that custom post. But the default wordpress search box in the sidebar should get the results from entire website. eg. listing search page results with map Thanks
You can restrict a search to a custom post type by modifying a basic WP search form like this: <form id="cptsearch" action="<?php echo home_url(); ?>" method="get"> <input type="text" name="s" /> <input type="hidden" name="post_type" value="POSTTYPENAME" /> <input id="searchsubmit" type="submit" alt="Search" value="Search" /> </form> To select a specialized template for the custom post type search, add this filter in your functions file: function template_chooser($template) { global $wp_query; $post_type = get_query_var('post_type'); if( $wp_query->is_search && $post_type == 'POSTTYPENAME' ) { return locate_template('page_POSTTYPENAME.php'); } return $template; } add_filter('template_include', 'template_chooser'); And of course, you must create the specialized search results template: page_POSTTYPENAME.php
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "templates, search" }
how to get category`s slug in WP_Query loop? i use below code : //custom post = project //taxonomy = project-category $args = array( 'post_type' => 'project', ); $query = new WP_Query( $args ); // The Loop if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); ?> <div class="element-item col-lg-4 project hover-trigger landscape transition motal" data-category="transition"></div> <?php } wp_reset_postdata(); } how to get category`s slug of each post in loop? Thanks
`get_the_category()` retrieves `WP_Term` objects for all the categories assigned to the post. You can combine that with `wp_list_pluck()` to just get the slugs: $categories = get_the_terms( null, 'project-category' ); $category_slugs = wp_list_pluck( $categories, 'slug' ); `$category_slugs` will now be an array of slugs for the categories of the post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, loop, slug" }
Get youtube link title in post title If my post title is ` I want it to be converted to original video title which is "Ras Cricket - Fyah" Is there a way without API stuff cause it seems hard.
Use the following code into your `functions.php` file. function change_title_yt( $post_id ) { $current_title = $_POST['post_title']; $doc = new DOMDocument(); $doc->preserveWhiteSpace = FALSE; $doc->loadHTMLFile($current_title); $title_div = $doc->getElementById('eow-title'); $title = $title_div->nodeValue; $my_args = array( 'ID' => $post_id, 'post_title' => $title ); if ( ! wp_is_post_revision( $post_id ) ){ // unhook this function so it doesn't loop infinitely remove_action('save_post', 'change_title_yt'); // update the post, which calls save_post again wp_update_post( $my_args ); // re-hook this function add_action('save_post', 'change_title_yt'); } } add_action('save_post', 'change_title_yt');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links, title, youtube" }
Enable Wordpress Debug only for Admin Is it possible to enable debug alert just for admin user? there is a way by adding a secret query in URL. But I do not want to use it. is there anyway just display debugs, for admin?
Do this: if(!function_exists('display_php_error_for_admin')) { function display_php_error_for_admin() { $user_id = get_current_user_id(); $user_meta = get_userdata($user_id); $roles = $user_meta->roles; if(is_array($roles)){ if (in_array("administrator", $roles)) { error_reporting(0); @ini_set('display_errors', 0); } }elseif ($roles == "administrator"){ error_reporting(0); @ini_set('display_errors', 0); } } } add_action('init','display_php_error_for_admin');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "debug" }
Plain permalinks not working! For my wordpress website plain permalinks are not working. The post url is changing but when we click on the post its not redirecting to the post page. It will be in the home page itself. For example: If I change the permalinks to other custom formats, it works correctly and showing the posts page. For example: I tried creating a new `.htaccess` file after changing the permalinks to plain. Still not working.
Plain permalinks of the form `/?p=14523` (or `/index.php?p=14523`) don't necessarily need any `.htaccess` file since they don't require mod_rewrite to rewrite the URL (unlike the the _custom permalinks_ you mention). However, for a URL of the form `/?p=14523` (as opposed to `/index.php?p=14523`), where you don't explicitly state the index document (ie. `index.php`) in the URL then the `DirectoryIndex` must be correctly set on your server. This can be achieved in `.htaccess` using the following directive: DirectoryIndex index.php Normally, this is set by default on most servers, but sometimes it is not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, permalinks, redirect, htaccess" }
How to echo a dynamic url I need to insert following dynamic URL: echo $myfy->get_retrieve_cart_url( $post->ID, $landing_page ) into: echo "<a href='"LINK"'> . get_title() . </a>"; Basically, I need to replace the "LINK" with above URL, I have tried all combinations that I've thought about and I'm getting a string error, Can anybody give me a helpline?
There are two workarounds: **If the first line you're mentioning is inside a void function:** You have to create a wrapper function and use `ob_` functions to get the real link: <?php function echo_link($post, $landing_page) { global $myfy; echo $myfy->get_retrieve_cart_url( $post->ID, $landing_page ); } function get_link($post, $landing_page){ ob_start(); echo_link($post, $landing_page); return ob_get_clean(); } // And finally in your result: echo "a href='" . get_link($post, $landing_page) . "'>.get_title()"; **If the first line you're mentioning is not inside a void function or you can simply duplicate it without concerning about the future changes:** <?php $link = $myfy->get_retrieve_cart_url( $post->ID, $landing_page ); echo "a href='" . $link . "'>.get_title()"; By the way, You might forget about those dots (`.`) while trying to concatenate your strings.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "urls" }
Inject class in body when particular page template is used <body <?php body_class(); ?> > In header.php I have written the above code. But I want when this page template is in use: page-customer.php then body_customer class should go above. Is this possible through some hook?
there is a filter for that and it's called... `body_class` ;) This should work for your case: function add_my_custom_body_class( $classes ) { if ( is_page_template( 'page-customer.php' ) ) { $classes[] = 'body_customer'; } return $classes; } add_filter( 'body_class', 'add_my_custom_body_class', 10, 1 ); if you wanna add class based on page ID (as you've mentioned in comments), you can change the logic inside the function and add class only when particular page is queried, let's say your page ID is 3: if ( 3 === get_the_ID() ){ $classes[] = 'your_additional_class'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, pages, page template" }
How to transfer categories (default) to custom taxonomy? I wanted to move all my posts from the default post type into the new custom post type i've made. I was able to do it using this code: UPDATE wp_posts SET post_type = 'movies' WHERE post_type = 'post' However, i wasn't able to transfer the categories i have on default category. Is it possible to transfer all the posts including the category into custom post type & custom taxonomoy/category?
wp links the posts and the terms in table wp_term_relationships so one doesn't really have to worry about the custom taxonomy. You basically want to change the term ids from that of the default to the term_id of the new term in your custom taxonomy for your select set of posts. Lookup the term_ids and then do UPDATE wp_term_relationships SET term_taxonomy_id = 'newterm_id' WHERE term_taxonomy_id = 'oldterm_id' AND object_id IN (SELECT ID FROM wp_posts WHERE post_type='movies')
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, taxonomy, sql" }
Blog post Links leading to home page I have a Wordpress site with a paid theme but I seem to have a problem with the blog posts. When I create a blogpost, the blog post title and read more links appears in the blog menu item I have. But when the link is clicked, the website goes to home page instead of the blog post. What could be the issue? Any idea where to start trouble shooting?
1. Delete you .htaccess file in root 2. Reset your permalink structure 3. If have access to the theme file make sure your blog title link refers to the_permalink() as destination. 4. you might have open anchor tag from the logo which developer forgot to close.See page source or inspect it. 5. Share the code in your loop.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, homepage, blog, blog page" }
Does WordPress remove draft status automatically? Last week our marketing team placed around 35 posts inside of draft due to some legal issues in our market. This week the same marketing team has reported that WordPress has somehow Published these posts automatically and taken them outside of draft status? Could some code, module, cron or something do this?
Just by itself WordPress will not change the post status. However, if you have a plugin like Draft Scheduler installed, drafts will be published automatically, possibly with some interval. So, you should check your plugins on this type of activity. Another possibility would be that a backup of the database has been installed after a crash, but you would probably have noticed that.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, publish, draft" }
get_terms() order by term_meta I'm doing a `get_terms()` query that I'm trying to order by a custom term meta. The custom term meta key is `'order'` which as a numeric value (between 1 and 10). I have tried the following, but the order doesn't seem to follow the meta value - any pointers is appreciated. $type_terms = get_terms( 'type', array( 'hide_empty' => false, array( 'key' => 'order', ), 'orderby' => 'meta_value_num', 'order' => 'ASC', ) );
> the order doesn't seem to follow the meta value Yes, and it's because you set the meta key like this: (which doesn't actually set the meta key) array( 'key' => 'order', ), The proper way is by using the `meta_key` parameter: 'meta_key' => 'order' So the full code would be: $type_terms = get_terms( 'type', array( 'hide_empty' => false, 'meta_key' => 'order', 'orderby' => 'meta_value_num', 'order' => 'ASC', ) ); For more information, please refer to `WP_Term_Query::__construct()`, which is used by the `get_terms()` function.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "terms, term meta" }
WP_Query how to add a thumbnail to the first post from the last 5 posts? I've a query like this: <ul> <?php $the_query = new WP_Query( array( 'cat' => '1', 'posts_per_page' => 5 ) ); ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <li> <?php if ( has_post_thumbnail()) : ?> <?php the_post_thumbnail(array(230,163)); ?> <?php endif; ?> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li> <?php endwhile; wp_reset_postdata(); ?> </ul> ![Example: How can I show thumbnail the last added post?
Because you're not specifying `order` and `orderby` parameters within your `WP_Query` query, the latest added post will be shown in the first place. Having that in mind, you can do the following: <ul> <?php $the_query = new WP_Query( array( 'cat' => '1', 'posts_per_page' => 5 ) ); ?> <?php $iterator = 0; ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <li> <?php if ( has_post_thumbnail() && $iterator == 0 ) : ?> <?php the_post_thumbnail(array(230,163)); ?> <?php $done_last_post_thumbnail = true; ?> <?php endif; ?> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> <?php $iterator++; ?> </li> <?php endwhile; wp_reset_postdata(); ?> </ul> Of course, this will work only if the latest post has thumbnail.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, post thumbnails" }
Add Post Status to Body Class I have added a custom post status of rejected, working just fine. I want to add the post status to the body of the post when it is being previewed. In order to style a front end information box seen by the admin.
You'll have to use the `body_class` hook in the `functions.php` file of your theme in combination with `get_post_status()` function. Like the following: add_filter( 'body_class', 'custom_class' ); function custom_class( $classes ) { if ( get_post_status() == 'rejected' ) { $classes[] = 'rejected'; } return $classes; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, post status" }
Display custom post types with custom date field value (before today) & order by custom date field I'm trying to display custom post types with custom date field value being before today. It works OK for showing posts before today, but the order is only based on post date. I want to have the result ordered by `meta_key`. I tried the following code and I don't understand why it doesn't work: query_posts( array( 'post_type' => 'soiree', 'orderby' => 'meta_value', 'meta_key' => 'date_de_concert', 'meta_query' => array( array( 'key' => 'date_de_concert', 'posts_per_page' => '-1', 'value' => date( 'Y-m-d' ), 'compare' => '<', 'type' => 'DATE', 'orderby' => 'value', 'order' => 'DESC', ) ) ) );
I prefer to use WP_Query (for more info read "When should you use WP_Query vs query_posts() vs get_posts()?"), try this way: $args = array( 'post_type' => 'soiree', 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'date_de_concert', // you don't need 'meta_key' => 'date_de_concert' when using meta_query //'meta_key' => 'date_de_concert', 'order' => 'DESC', 'meta_query' => array( array( 'key' => 'date_de_concert', 'value' => strtotime( 'today' ), 'compare' => '<' ) ) ); $concert_query = new WP_Query( $args ); if ( $concert_query->have_posts() ) : while ( $concert_query->have_posts() ) : $concert_query->the_post();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, custom field, query posts, meta query, order" }
SVN precommit and nullable return types When committing my plugin to the repo, I'm getting an error that looks like this: > Commit blocked by pre-commit hook (exit code 1) with output: > > > *********************************** > PHP error in: path/to/file.php: > > > Parse error: syntax error, unexpected '?' in path/to/file.php on line 36 > Errors parsing path/to/filephp Examining the line in question, I see that the `?` is part of one of PHP 7.1's nullable return types: > `static function foo($bar=null): ?string { ... }` Note that my readme.txt file correctly notes the minimum PHP version, if that makes any difference to the parser. If not, do I need to remove all my nullable return types for now?
Linting only supports 7.0 and down. Nullable Types are available in PHP 7.1, so 7.1 code will fail. You will have to change it. Good Luck!
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "php, svn" }
Multi-site: Change the URL of main site to HTTPS I've setup the multisite on a fresh installation of WordPress. Then I created some other websites, so, in the end, I have something like this * < * < * < * < I have then installed an SSL digital certificate, so I changed the URLs of the websites to match the HTTPS scheme: * < * * * To change the scheme I gone to `Sites > All Sites`, then clicked on each site and in tab "Information" (the first one) I simply changed the scheme and saved. This worked. **The only site left without the`https` is < for this, in fact, I have cannot change the URL.** If I go to `Sites > All Sites` and click on it, in fact, in the first tab "Information" the URL is not editable and is in the form < without the https scheme. How can I change it? I'd like to change it now, before I start to install plugins and write articles. Any suggestions?
I would suggest editing the `wp-config.php` file, and adding: define('WP_HOME',' define('WP_SITEURL',' **However for multisite** here it says you should edit `DOMAIN_CURRENT_SITE` and `PATH_CURRENT_SITE`, if there is such thing defined in a multisite wp-config. First suggestion is based on this article.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "multisite" }
Not Able to Insert Taxonomy Term Using wp_insert_post() I have a Custom Post Type called `eyeglasses` and Custom Taxonomy called `models`. I also created two terms for taxonomy called `M156` and `M120`. Now I am trying to upload two post for test through `wp_insert_post`. This is adding the `$title` to the `post_title` of `eyeglasses` but not adding or updating the term of the post. function we_load_posts($title, $term) { wp_insert_post(array( "post_type" => "eyeglasses", "post_title" => $title, "tax_input" => array( "models" => array($term) ), "post_status" => "publish" )); } we_load_posts("Montana", "M156"); we_load_posts("Havana", "M120"); can you please let me know what I am missing or doing wrong here?
Few points come to mind: 1. There is a typo in `"post_type" => "'eyeglasses"` (extra single quote). It should be: `"post_type" => "eyeglasses"`. 2. Try putting the `$term` instead of `array( $term )`: "tax_input" => array( "models" => $term ) 3. Also, is it `models` or `model`? e.g. "tax_input" => array( "model" => $term ) 4. `tax_input` requires `assign_terms` capability. So if the user you are running this CODE with, doesn't have that capability, it'll not work. In that case, the right way is: $post_id = wp_insert_post(array( "post_type" => "eyeglasses", "post_title" => $title, "post_status" => "publish" )); wp_set_object_terms( $post_id, $term, 'model' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "custom post types, custom taxonomy, wp insert post, terms" }
Custom page for WooCommerce's /product-category/ I am building a website from scratch on WordPress using WooCommerce. I'll be having products from numerous brands and to have an easier time organizing them, I've made each brand a category. Currently, when I go to mywebsite.com/product-category/brand_name it's using my page.php template. I would like it to use a different one, but I'm not sure what file I need to add. I tried page-product-category.php, page-product.php, page-category.php and nothing seems to work. I understand that "woocommerce/content-product.php" is what I need to edit in order t ochange what the woocommerce output looks like, but I also need to edit everything else, header, navigation, footer and so on. I tried a few more different pages too, such as "woocommerce/woocomerce.php", "category.php", but still no luck, it still uses my page.php template. Thank you in advance!
`product-category` URL uses `taxonomy-product-cat.php` which calls `archive-product.php` you will need to override it by creating the same file with the same name in `themefolder/woocommerce/archive-product.php` You can open any file in templates folder in the WooCommerce plugin and you will find a line in the very top comment describes how to override the file. Don't forget to add `add_theme_support( 'woocommerce' );` in the theme `functions.php` If It's not there.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "categories, woocommerce offtopic, templates, page template" }
why my post not redirecting to custom created single-show.php file? i am registered custom post type name is 'show' in **function.php** ,and also i created **single-show.php** file where i want my custom post to be show when i follow the permalink of post ,this only to for 'show' custom post type but it's post not redirecting to single-show.php..please can any one guide me how to do it.. i am showing simple code of **single-show.php** <?php if($post_type == 'Show') { // Start the Loop. while ( have_posts() ) : the_post(); echo '<h1>'.get_the_title().'</h1>'; endwhile; } ?> please tell me what i am doing wrong..?
Simply use default WordPress loop for single pages of post types... <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); echo '<h1>'.get_the_title().'</h1>'; // Post Content here } // end while } else{ esc_html_e( 'Sorry, no posts found.' ); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
Where to find HTML to post Adsense Code I am a **beginner** WP user and having an issue of where to find HTML area to post AdSense code. I know that AdSense directs it to be posted between & tags, but I am not even sure where this is located. I am using a plugin, AdInserter, but not sure if that is the location to add AdSense code either. Probably an elementary question, but like mentioned I am a beginner! Thanks for the help!
Ads are most commonly displayed in the sidebar. You can add Google Adsense in your sidebar by using WordPress widgets. Simply go to Appearance » Widgets page in your WordPress admin area. Next, drag & drop the 'Custom HTML' widget to the appropriate widget area and paste your Google AdSense code in there.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html, adsense" }
How to remove city field from order in dashboard? i need to remove city field and one of payment method anyone know how ? ![order details woocommerce](
put that code in function.php or in plugin file . add_action( 'woocommerce_admin_billing_fields', 'unset_order_city_field' ); function unset_order_city_field( $billing_fields ){ unset($billing_fields['city']); return $billing_fields; }
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
How to get current page title inside a page's template I am trying to get the page title to show up inside various h1, h2 and p tags that i have part of the page template - so that when the template is applied to a page it will make the current page's page title appear wherever I add a shortcode or whatever is needed to pull the page title. When I add the following i am getting a blank... Here's what I mean: I want "Find the best " to basically pull the page title so that if the title is video games it will display as "Find the best video games" <h1 class="btx-heading-text btx-secondary-font btx-s-text-color btx-s- text-border" style="padding-right:25%; padding-bottom:5%; letter- spacing:-2px;"><span style="color: rgb(0, 0, 0);">Find the best&nbsp; </span><span style="color: rgb(126, 131, 142);"><?php get_the_title() ? ></span></h1> Currently, I only get the following "Find the best"
`get_the_title()` does not output anything - it's meant for being saved to a variable. Use just `the_title();` in its place - that way it will be output. :)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "title" }
How to change the deafult template in Wordpress plugin I have this plugin: Simple Job Board When I view a job offer I see the default view from my theme. But in page attribute I have a lot templates. but if I change, nothing happens. It is possible to change it by using functions.php ? Kind regards \--edit Or how to change the default template off all page in wordpress ?
For your plugin question, you need to contact the plugin's support guys. Plugin questions are not within scope here. For information about templates, start here to gain knowledge on how they work: < Templates are part of the theme, so to change the template, you have to change the template used by the theme. But you don't want to change theme templates, you want to create a Child Theme that uses your current theme. Put your modified templates in the Child Theme, so any theme updates don't bork your custom templated. Learn about Child Themes here: < .
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, templates" }
Creating a function within functions.php to change the date I'm using the PODS WordPress Framework which is amazing. I created a template with one of the fields publishing the date of an event which is done through a simple 'magic tag' like this {@date_of_event} This publishes the date in this format: **September, 15th 2018** What I need to do is change the format of the date being published into a numeric version which I can do by passing the value into _my own function._ That would be done like this: {@start_date,MY_FUNCTION} So, to do this I need to create a function in my functions.php file like this: function MY_FUNCTION ($input) { return "New Input" . $input; } Now, the php time date format that I need is like this: Y/m/d So - **my question** \- how do I insert this into the function above? Thanks for all help and direction on this!
You can use the PHP's `strtotime()` and WordPress's `date_i18n()` functions: function MY_FUNCTION( $input ) { // Removes commas so that we'll get the proper timestamp. Otherwise, the // strtotime() function would return FALSE. $input = str_replace( ',', '', $input ); // Retrieve the UNIX timestamp of the date. $timestamp = @strtotime( $input ); // Returns the date in *localized* format. return date_i18n( 'Y/m/d', $timestamp ); } `MY_FUNCTION( 'September, 15th 2018' )`, for example, would give you `2018/09/15`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "date time, pods framework" }
What is the first file wordpress looks at in a theme? I've inherited a theme and am trying to get my head around a plugin failure. There is an index.php file in the root of the theme, is that the first file wordpress will look at when it attempts to resolve the homepage or maybe it is something else? All files in the the root are as follows: 404.php archive-jetpack-testimonial.php archive.php assets comments.php footer.php front-page.php functions.php header-front.php header.php inc index.php page.php rtl.css screenshot.png search.php secure.php sidebar.php single.php style.css style.css.map template--standard.php With which file does wordpress begin?
If it's the home page, WordPress will look for the following files in this order and use the first one it finds: 1. front-page.php 2. home.php 3. index.php WordPress template hierarchy is described in detail here: < > This article explains how WordPress determines which template file(s) to use on individual pages. If you want to customize an existing WordPress theme it will help you decide which template file needs to be edited.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "themes" }
Gutenberg RichText I'm using the RichText API for a custom block: <RichText tagName="a" className="button" placeholder={ __( 'Button text...' ) } value={ buttonText } onChange={ ( value ) => setAttributes( { buttonText: value } ) } /> I am using `a` as the tag name because I want the element to be a link but I'm not sure how to add a URL. Is it possible to add a `href` attribute? Adding `href="some URL"` to RichText does not work. I looked through the documentation and Googled it but couln't find any guidance.
Please paste the full code, According to official Gutenberg button block. You need to have additional block attributes to use for button link,text - < <RichText.Content tagName="a" className={ linkClass } href={ url } title={ title } style={ buttonStyle } value={ text } /> As you can see, there's a **URL, Title & Text** attributes. url: { type: 'string', source: 'attribute', selector: 'a', attribute: 'href', }, title: { type: 'string', source: 'attribute', selector: 'a', attribute: 'title', }, text: { type: 'array', source: 'children', selector: 'a', },
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "javascript, block editor" }
Full list of registered scripts or styles, but from an admin options page I'm developing a plugin that will allow some CSS optimization. But first of all, i need to get the list of all stylesheets (later i'll do something for scripts too). Doing this: function debug_print_styles () { global $wp_styles; ?> <h2>Debug print styles</h2> <?php foreach ($wp_styles->queue as $handle) { echo $handle."<br />"; } ?> <?php } clearly works as intended if used on a post/page template. But if i want that list on an admin settings page, this won't fit, as it prints only the styles for the admin page. I looked at many forums, including this one, but found the same thing i already did. So, is there a way to achieve this? Thank you.
> So, is there a way to achieve this? Indeed, there is - I'm doing it in my own optimization plugin - but it's going to involve more work than you might first suspect. 1. Use `add_action()` to register a hook that triggers on the front-end to output a JSON-encoded array of registered styles 2. Use the HTTP API (or an AJAX call) to make a request against the front-end to trigger that hook 3. Read the results of your HTTP API call from your `/wp-admin/` script There are a number of additional considerations if you want to cover all your bases here, but that should be everything you need to get started.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, wp admin, css" }
Site Hacked - Wordpress Divi Site - Cannot find where to fix the issue? I need help trying to find out where to look to find out how to get rid of an issue on a wordpress site I manage. If you go to < you will see if you scroll down to the bottom of the website right over the footer and under the map there is Red text links on two lines. It shows on all pages. When I use Google Inspector editor it shows there are like 20+ html files created from those links, one of which is here: < \- yet I cannot even find where those html files are located to delete? Any help would be great! I disabled all plugins and it still shows, I already changed the wp-admin password. Have no idea how this happen or how to get things back to normal? Any help much appreciated! ![enter image description here](
Disabling plugins won't help if WordPress core has been compromised (and reinstalling WordPress won't do much good if your hosting account has been compromised). I would recommend nuking and paving your installation with help from your hosting provider (and getting a professional to audit any necessary themes and plugins you plan to use after this is completed to ensure this doesn't happen again).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hacked" }
Periodically Query an external API on wordpress site I am creating a wordpress site that will periodically retrieve data from an API and use that data to update info in the `wp_users` table. I don't really know how to go about this. I'll start with 2 questions: 1. The API can return batch data. If I make a batch call, is there a way to update all the users at once?** 2. Say I want to make the API call once an hour when the site is live. How do I set that up? I tried to search but I don't even know if I am googling the right words.** Thank you!
1. You can use wp->query calls to loop through the users table and update each row in a loop. 2. Probably would need to use cron jobs for this, this is different for every host but you basically would tell it to run your php script at intervals.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "api, rest api, performance, wp user query" }
ACF Load Field Groups Programmatically I would like to load ACF fields for custom post types based on a set of conditions and **NOT** use Custom Location Rules. A brief use case / rationale: * If `CPT A` exists AND `Theme Option Y` is 1, then show `Field Group 1` on `CPT A` in wp-admin * I want to set rules programmatically because I don't want users to be able to override/mess up location rules via the field group options. I've been poking around and according to some threads, it seems like hooking into `acf/get_field_group` is going to be the way to go, however it isn't documented. Is there any way I can do a filter hook to override a field group's location rules based on programmatic conditions?
In case anyone needs it, this is working for my needs: add_filter('acf/get_field_group', 'my_change_field_group'); function my_change_field_group($group) { $get_current_screen = get_current_screen(); $get_current_post_type = $get_current_screen->post_type; $my_option = get_field('my-option','option'); if ( $get_current_post_type == 'my-cpt' && $my_option == 'stuff' && $group['key'] == 'group_123456789' ) { $group['location'] = array( array( array( 'param' => 'post_type', 'operator' => '==', 'value' => 'my-cpt', ), ), ); } return $group; };
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "filters, advanced custom fields" }
Why is die() used at the end of function that handles an Ajax request? What could go wrong if I am not using `die();` after the function that handles an Ajax request? I have noticed that almost all the WordPress Ajax-based code is using it.
If you do not `die`, execution will continue and might generate extra output which might break whatever information you are trying to send from the server to the browser. Strictly speaking, you might not need to `die`, but there is very little point in taking the risk. In more general terms, WordPress Ajax shows its age and the lack of experience working with Ajax when it was designed. You should use the WordPress JSON routes instead, as they can have a better URL structure, and the programming structure is more logical and modular.
stackexchange-wordpress
{ "answer_score": 17, "question_score": 9, "tags": "ajax" }
WP All Import / Update stock quantity from multiple XML files Hi there as the title says, I am trying to import stock quantity from multiple xml files, I am trying to save stock in custom filed and then add code to sum this new filed and existing new and then update new stock value, but it doesnt seem to be working, any advice?
I managed to get it working, here is answer: \- when importing update new stock to custom field: _custom_stock_placeholder \- update only this field: _custom_stock_placeholder \- add this code to functions.php add_action('pmxi_saved_post', 'post_saved', 10, 1); function post_saved($id) { $original_stock = get_post_meta($id, '_stock', true); $new_stock = get_post_meta($id, '_custom_stock_placeholder', true); $combined_stock= $original_stock + $new_stock; update_post_meta($id, '_stock', $combined_stock); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, custom field, woocommerce offtopic" }
Slow Query On Search Please I have a very slow query on my wordpress search, checking the processes it takes upto 40sec to execute using `SHOW FULL PROCESSLIST;` below is a sample of query SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '%Industreet%') OR (wp_posts.post_excerpt LIKE '%Industreet%') OR (wp_posts.post_content LIKE '%Industreet%'))) AND (wp_posts.post_password = '') AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish') ORDER BY wp_posts.post_title LIKE '%Industreet%' DESC, wp_posts.post_date DESC LIMIT 0, 25 I have tried my best to fix this, but nothing is working out. though I have a total post of 120k on my site. I really need help. Thanks in advance
This is the query generated by the internal search function on Wordpress. It is criticised for being inefficient, and there are a few drop-in replacements available as plugins. You may be able to find something that helps you by doing more research around these. For example: < < I don't have a specific recommendation to offer as I'm just digging into this myself, hence having to link elsewhere.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, database, search, sql" }
Get all the URLs of the pages that uses a specific shortcode For example my _example.com/sample-page/_ is using `[my_shortcode param="1"]`. How can I get all the URLs of the pages that uses `[my_shortcode]`? Is there an approach to achieve that?
Solution that I've found: $pages = get_pages(); $pattern = get_shortcode_regex(); foreach($pages as $page) { if ( preg_match_all( '/'. $pattern .'/s', $page->post_content, $matches ) && array_key_exists( 2, $matches ) && in_array( 'my_shortcode', $matches[2] ) ) { echo $page->post_title . <br />; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, shortcode" }
Wordpress select field - show current value? Function is generating select field, what can I do to set 'selected' currently saved value ... if possible? For example, previously I selected 36 and saved **"update_option('_nos',$myvalue)"** function woo_add_spin() { woocommerce_wp_select( array( 'id' => '_select_nf', 'label' => __( 'Select #spins: ', 'woocommerce' ), 'selected' => true, 'options' => array( '24' => __( '24', 'woocommerce' ), '36' => __( '36', 'woocommerce' ), '48' => __( '48', 'woocommerce' ) ) ) ); } so every time function is executed i would like to check current value and set "selected" to the option with the same value or using jQuery check currently set value and just add 'selected' accordingly ?
By referencing to the source code, this function supports an argument called `value` which you can pass one of the keys inside the `options` array like this: function woo_add_spin() { woocommerce_wp_select([ 'id' => '_select_nf', 'label' => __( 'Select #spins: ', 'woocommerce' ), 'selected' => true, 'value' => '24', 'options' => [ '24' => __( '24', 'woocommerce' ), '36' => __( '36', 'woocommerce' ), '48' => __( '48', 'woocommerce' ) ] ]); } By looking inside the source code, WooCommerce also tries to fetch the value of the select field using the `id` field and the post meta but, you can't take advantage of this built-in feature because you're saving the settings inside the `wp_options` table.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic, select" }
Redirecting "wrong" but working links to their canonical URL in order to prevent search engine penalties (e.g. /123/ at the end of URLs) The WordPress permalink system is really nice as it even detects minor problems with URLs and is loading the correct page. For example we have a page with an URL like this: > < If we type > < or > < into the Browser console we are also redirected to the correct page. Nice! However if we type > < With a random number at the end we are not redirected (though the correct page or post is displayed). The marketing guys of our company told me that this _might be bad for SEO duplicate content issues_? Why are those links not redirected and can/should I prevent this?
Ensure that you provide a canonical url - this should ensure that search engines don't see the url variants as duplicate content. Additionally, appending a number on the url, will make Wordpress try to access that page. Using a debug plugin, such as Debug Bar, is quite useful for diagnosing this kind of behaviour as it will show the query performed on each page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, url rewriting, redirect, seo" }
How do i create navigation links like this in wordpress? ![enter image description here]( ![enter image description here]( Currently, I am using an Avada Theme and I would like this navigation to be in the shop and product pages.
You need to setup bread crumbs for the site. this is a link from the avada documentation that tells exactly how to do it. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, navigation" }
Why wordpress cannot write to directory and how to fix it? I got message To perform the requested action, WordPress needs to access your web server. Please enter your FTP credentials to proceed. The solution is here < However, I don't quite understand about ownership. Who owns the file? ![enter image description here]( The owners of the file is 1001? Who the hell is 1001?
**To fix this issue:** Set WordPress directory and file permissions to allow your webserver's user account execute+read+write access. (Typically this means setting permissions 0775 for directories and 0664 for files.) > However, I don't quite understand about ownership. I'd recommend a review of Understanding Linux File Permissions at Linux.com - it never hurts to know what's going on at the system level. > The owners of the file is 1001? > > Who the hell is 1001? 1001 is the first "userland" user created on the system (system-level users typically have ID's in the 0-1000 range). In this case, the user entry may be missing from `/etc/passwd` or Filezilla doesn't have read access to `/etc/passwd` to display the username associated with UID 1001. Ensure that `/etc/passwd` has 0644 permissions (owner read+write, group and global read) and an entry for 1001 exists _or_ contact your hosting provider for assistance.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "ftp" }
Relative links in Gutenberg I'm developing a site on my local machine and am now adding the content that I want to go live with. But I noticed that when I add a link in the new Gutenberg editor, the link is absolute, e.g. it's something like ` which seems bizarre. I also have ACF installed and the page links I define with that are perfect. I changed the permalink for one page, and all the places I had it in ACF updated automatically, but I had to manually change the links in content pages. And when I go live, I'm going to have to change them all again. That seems incredibly weird to me. To the point that I think I'm missing something simple. So am I?
It doesn't have anything to do with Gutenberg. It's just the way WordPress stores links in the main content. Anytime you add a link in the WP editor, it automatically puts in the absolute path. ACF and other forms of custom postmeta instead store the post ID, so whenever its slug/permalink changes they are automatically updated. When you push content from your local site, just use a database migration plugin, which will handle all the URL changes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, block editor" }
Ajax stops working when logged in? I have implemented ajax in the website add_action('wp_ajax_wppl_function', 'wppl_function '); add_action('wp_ajax_nopriv_wppl_function', 'wppl_function'); But this works without any issue if i log out. This is the error that i am getting the console component : "Core" file : "wp-includes/class-wp-hook.php" line : 286 message : "call_user_func_array() expects parameter 1 to be a valid callback, function 'wp_ajax_wppl_function' not found or invalid function name" stack : ["do_action('wp_ajax_wppl_function')"] type : "warning" Not sure what's happening.
A few things that I see: 1. There's a space in your first add_action declaration. Should be `add_action('wp_ajax_wppl_function', 'wppl_function');` 2. Have you declared wppl_function to run it? 3. Have you localized your scripts when logged in? Please review the codex entry on wp_ajax_nopriv (action))
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "ajax, warnings" }
How to get post ID in a Page? I'm trying to list all of my posts in a page(with post's content). Everything is showing correctly but the audio player which uses post id to get the URL of an attachment in the post is not showing. I'm using the following code to get the post ID:- global $wp_query; $postID = $wp_query->$post->ID; $file_id = get_post_meta( $post->ID, sound_s, true ); $fileUrl = wp_get_attachment_url($file_id); $attr = array( 'src' => $fileUrl, 'loop' => '', 'autoplay' => '', 'preload' => 'none' ); echo wp_audio_shortcode( $attr ); It works in the post itself but when I try to list it in the page the post ID shows page Id instead. Please help me with this.
You should not use globals directly. There are some nice wrapper functions in the WordPress API. If you want to retrieve the ID of the current post or page just use **get_the_ID()**. Without any test ... you could write the functionality in this way: $file_id = get_post_meta( get_the_ID(), 'sound_s', true ); $file_url = wp_get_attachment_url( $file_id ); echo wp_audio_shortcode( [ 'src' => $file_url ] ); I don't know much about the plugin that you use but why don't you loop just over the list of posts: $posts = get_posts(); foreach ( $posts as $item ) { $file_id = get_post_meta( $item->ID, 'sound_s', true ); $file_url = wp_get_attachment_url( $file_id ); echo wp_audio_shortcode( [ 'src' => $file_url ] ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, wp query, loop, query posts" }
Page Templates not using functions.php I am having an issue with page templates in Wordpress. I have created some for my website but they are not using the wp_enqueue_style in my functions.php. anybody know why this is? mainly my stylesheet is in functions.php so i want it to use the same one
Your enqueued css should work for all page template if there is no condition applied. could you please share it how you enqueued? Another thing you can check. In header.php, can you please check that wp_head(); function has been called properly in the page template's head tag. if not exists in the header.php between the head tag then add this function. Thanks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, wp enqueue style" }
If I use a static page-slug.php for a page, is the database still queried? I wonder how to display a static page in order to increase the page load a little bit: The first option is to put the content in the database (via the Admin GUI), the second option is to create a `page-slug.php` without calling the loop within `page-slug.php`. The latter option would be useless if the database is still queried, which leads to my questions * Is it better in terms of page load to use `page-slug.php` for static pages instead of putting the content into the database? * Will wordpress query the database if I use `page-slug.php` (with the loop) in order to check if there's any content for this page?
Yes. It will. WordPress will query the database for that page regardless of whether or not you use the loop. If you're only talking about adding a chunk of content into the editor, then you're way overestimating the impact of querying the database for a single page. There are plenty of plugins available that will render your pages to static files that won't query the database (or run PHP at all), if that's the direction you want to go in. WP Super Cache and WP Rocket are two that come to mind.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, content" }
I've removed my /author/ slug but it clashes with new and existing pages. Any fixes? I've successfully removed my author slug using this tutorial: < so it's like website.com/author/cixxy to website.com/cixxy My question is, if I have an existing page like website.com/readme , and a new user registers as readme nickname, then his author page will just redirect to the readme page. Or if they registered already, then I won't be able to use that nickname for a page anymore, right? So if they registered as "Contact" username, I won't be able to have a /contact slug. How can I prevent this? I see behance.net, facebook etc using both pages as the root and also users, so I'm guessing there has to be a way.
There is no way around uniqueness being necessary, with the effects you described. Personally I wouldn't remove the part that makes ensuring uniqueness of the slug much easier, like the author part, in my mind it is just a sign of a well structured site. Anyhow, there is `validate_username()` function with the `validate_username` hook. You can use it to disallow certain usernames, so e.g. a custom list of stopwords you want to enforce. And you can use it to prevent the registration of usernames, who would be conflicting with other already registered slugs, content.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, users, redirect, author, slug" }
How Create Different Layouts For Single Wordpress Theme? How can I create different layouts and style (Home with Sidebar, Home without Sidebar, Home Grid, ...) for a single Wordpress theme by choice of user in an Admin panel? Should I have different css and home pages? What I mean is like this.
There are many ways to do this, but one way would be to use Page Templates. You can then select the template in the editor for each page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "homepage" }
Best way to start becoming a wordpress developer It's my mission this year to become a wordpress developer. I've been using wordpress for years as a frontside user but I now want to be able to develop wordpress sites from themes to functionality and cms. I already have a great understanding of CSS & HTML and some PHP(It's been a while), is there a great course anyone can recommend? Or where should I start? What languages does one need to be strong in? HTMl, CSS, JAVASCRIPT & PHP? Thanks in advance.
I would recommend setting up a local install of WordPress. From there you can play around with different themes and plugins. I would take a look at the code behind the default themes to see how they are built. The best way to learn is by doing, so I would think of a site you can make and build it from scratch. Maybe a portfolio site for you or whatever. I don't think you really need to go through courses, just google what you need to know, there are plenty of free resources out there! Between this site and google it is pretty rare I don't find an answer immediately. Here are a few resources to help. * WordPress Codex * Wordpress Forums * About Themes * Creating a Theme * WP Beginner * List of Resources
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, customization" }
Convert Wordpress shortcodes into plain html I am building a static landing page on WordPress root folder, and I need to import some shortcodes from an existing page located in `wp-content` directory. What I do is import with `$post = get_post($post_id)` the post containing my shortcode, then I extract it -> > $output = apply_filters( 'the_content', $post->post_content ); Finally I do -> > echo do_shortcode($output); The issue here is that on the page I got displayed only the raw format of the shortcode, like `[shortcode]`; There is a way to convert shortcodes into plain html so my page can display it correctly or I am missing some `require/include` somewhere? I already added `define( 'WP_USE_THEMES', false ); require "wp-load.php";`
For other who wonders about it: I resolved adding `WPBMap::addAllMappedShortcodes()`; to my function, which renders all shortcodes! > > define( 'WP_USE_THEMES', false ); > require_once "wp-load.php"; > require_once "wp-content/themes/salient/functions.php"; > /* Function that gets an object containing post data and returns in output the post_content value. Return string. */ function get_post_content(){ //renderize shortcode WPBMap::addAllMappedShortcodes(); $post = get_post(INSERT_POST_NUMBER); $output = apply_filters( 'the_content', $post->post_content ); $value = do_shortcode($output); return $value; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
show loop id post , only first id can read I have a script , show post by id , and id post from array here my code : if ( have_posts() ) : while ( have_posts() ) : the_post(); $f = cherry_get_option('blog-featured-post',false); foreach ($f as $fs ) { $q = new WP_Query( array( 'post__in' => array($fs), 'orderby' => 'date', 'order' => 'asc' ) );} if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post(); //show post the_title(); endwhile; endif; endwhile; else: echo "no post found"; endif; wp_reset_query(); nah from that code `$fs`will output id post what will display , i am try to `vardump($fs)` it work fine (the output is `string(4) "1254" string(4) "1310"`) but in `post_in` just first id can read (`string(4) "1254"`) I dont know what happen with my code , if anyone can help , i will happy
You are getting the option "blog-featured-post", which apparently returns two posts. Then, for each of these posts, you are making a query. Only the second one is actually used, since your `if ( $q->have_posts() )` is outside of the loop. This query only has one post, since you use the post ID with the `post__in` option. So this is expected behavior.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, wp query, loop" }
Add suffix to price html does not work I am trying to add a suffix through a filter hook to a product price in Wooommerce, but for some strange reason the `woocommerce_get_price_html` filter hook (like explained here) does not change anything to the price. What can be the obstacle for not adding the suffix? Or do I need to use another hook? **My filter hook:** function pr_price_suffix( $price, $product ) { return $price . ' test'; } add_filter( 'woocommerce_get_price_html', 'pr_price_suffix' ); **The code that prints the price in single-product.php:** <?php echo wc_price( wc_get_price_including_tax( $product ) ); ?>
I don't think the filter will work in your template, since you're using `wc_price( wc_get_price_including_tax( $product ) )` .. a possible workaround: function pr_price_suffix( $price, $product ) { return wc_price( wc_get_price_including_tax( $product ) ). ' test'; } add_filter( 'woocommerce_get_price_html', 'pr_price_suffix', 10, 2 ); and in your single-product.php template: <?php echo $product->get_price_html(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, filters, hooks" }
Exclude product attributes from taxonomy terms loop As the title suggests, i want to exclude product attributes from the taxonomy terms loop, but each attribute is a unique taxonomy, so i don't know exactly how to exclude all of them programmatically. I'll be grateful if someone knows how to do it. $taxonomies = get_object_taxonomies( 'product', 'objects' ); $exclude = array( 'product_type', 'product_visibility', 'product_cat', 'product_tag', 'product_shipping_class' ); foreach ( $taxonomies as $taxonomy ) { if ( in_array( $taxonomy->name, $exclude ) ) { continue; } $terms = get_terms( array( 'taxonomy' => $taxonomy->name, ) ); foreach ($terms as $term) { echo $term->name; } }
Product attribute taxonomies are prefixed with `pa_`, so you can check the taxonomy name for that prefix and skip it if it exists: if ( substr( $taxonomy->name, 0, 3 ) === 'pa_' ) { continue; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, custom taxonomy, woocommerce offtopic, taxonomy, terms" }
How to print array of specific item I have get the following array from my database using mysql query in PHP. What is way to print the specific item (e.g: `staff_name` and `coupon`)? {"items":[{"ca_id":1,"appointment_date":"2018-07-02 08:00:00","service_name":"Eye check-up","service_price":50,"service_tax":0,"wait_listed":false,"deposit_format":null,"number_of_persons":"1","units":"1","duration":"3600","staff_name":"Mc Miltony","extras":[]}],"coupon":null,"subtotal":{"price":50,"deposit":0},"customer":"Mr Jhon","tax_in_price":"excluded","tax_paid":"5.00"}
Not really a WordPress question, but I'll bite. That data is JSON. To manipulate it with PHP you need to decode it with `json_decode()`. Then you can treat it as a PHP object. So to access the values you'd mention, and assuming the JSON is in a variable named `$json`: $object = json_decode( $json ); $staff_name = $object->items[0]->staff_name; $coupon = $object->coupon;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, database, array" }
Page content not visible in backend I was asked to take a look at a WordPress website. The front page had a lot of content on it, that I wanted to edit, but when I opened up the page editor, there was nothing at all in the content field. I created an exact copy of the page, and that showed completely blank except for the header and footer (which was at the top of the page). I suspected the content came from the WPBakery Page Builder plugin which was installed, but deactivating it made no difference. I also tried deactivating all other plugins one by one, but it made no difference. Where is this content coming from?
The content is most likely coming from a template file. Look inside your theme folder for files such as `front-page.php`, `page-home.php`, `content-home.php`, etc...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "content" }
Change max number of products on shop pages I'm using a child theme to the default WooCommerce Storefront theme. I would like to change the maximum number of products shown on the shop pages, to be unlimited (no pagination). How would you go about this?
You can add this code to your `functions.php`: /** * Change number of products that are displayed per page (shop page) */ add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 ); function new_loop_shop_per_page( $products ) { // Return the number of products you wanna show per page. $products = 100; return $products; } Change the **100** for more if you need it, since you don't want pagination simply put a high number and you won't have pagination. Change the number of products displayed per page
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic" }
WooCommerce apply shipping rates based on price How do I apply shipping rates based on the cart total? For example: * If cart total is $0.0 to $9.99 - shipping rate is $5.75 * If cart total is $14.99 to $35.00 - shipping rate is $8.25 * If cart total is $35.01 to $75.00 - shipping rate is $15.50 * If cart total is $75.01 and over - shipping rate is $25.00
Try this plugin Advanced Flat Rate Shipping Method WooCommerce. Hope this helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Rest Api How to get results of child categories with one api call Example: If I have a parent category 1 with child categories 2,3,4 etc instead of a call like this: /wp/v2/posts?categories=1,2,3,4 i want a call like this (imaging code) /wp/v2/posts?categories=1&includeallchilds=true that will include all articles from the child and sub-child of 1. how is this possible? I don't want my application make 2 api calls to find all childs of the categories of 1.. this query can done what i need, but i cant include this on rest api call, $args = array( 'post_type' => 'post', 'order' => 'DESC', 'posts_per_page' => 100, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => '1', ), ), );
WP can already do this out of the box thanks to the `include_children` parameter of `tax_query` which is true by default. While it is false by default for REST API parameters, it can be turned back on using a tax query, so you do not need to tell it the sub-terms. Here's an example taken from the official Make WP blog, just do something like this: const query = { categories: { terms: [ 3, 5, 7 ], include_children: true, }, }; wp.apiFetch( { path: wp.url.addQueryArgs( '/wp/v2/posts', query ) } ); Which generates a URL that looks like this: /wp-json/wp/v2/posts?categories[terms][0]=3&categories[terms][1]=5&categories[terms][2]=7&categories[include_children]=true&_locale=user Notice
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin development, query posts, rest api" }
Is XAMPP faster than running LAMP in WSL on Windows 10? I've been using Local by Flywheel for my local dev environment but recently it started acting weird so I decided, that since I'd finally learned a decent amount of CLI, maybe I should try just using WP-CLI and LAMP installed on WSL for Windows 10. Well [[I've run into a bunch of issues]]( and I'm almost ready to throw in the towel. So I was thinking about using Xampp instead. Is Xampp a virtual machine? Running LAMP in WSL isn't a virtual machine right? I know Local by Flywheel is a virtual machine which is part of why it's a bit slow sometimes.
XAMPP is not a virtual machine, it's a local server, and is excellent for local WP development, however attempting to use WP-CLI takes some more steps, detailed here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, mysql, apache, xampp, windows" }
Disallow author with robots.txt I would like to **disallow the authors** (of posts for example) in the file robots.txt. In fact, I noticed that for some of my sites, Google indexed the authors of articles, which I don't want to. Someone thinks is it possible ? (I tried something like Disallow: **/author/** but I'm not sure it works...) Thank you in advance, ArbreMojo.
If you use Yoast SEO, you can go to Users > All Users, and in the Yoast SEO settings, check _Do not allow search engines to show this author's archives in search results_. See this link. OR With robots.txt, you can add: User-agent: * Disallow: /author/* OR You can also add the robots meta-tag to the appropriate pages: function custom_function_filter_wp_robots( $robots ) { if(is_author()) { $robots['noindex'] = true; } return $robots; } add_filter( 'wp_robots', 'custom_function_filter_wp_robots' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "seo, google, robots.txt" }
Disallow /cgi-bin or not? Because of the fact that the rules of **Google** concerning the SEO recently changed, I would like to know if it still advised to disallow `/cgi-bin` or not ? Thank you in advance, ArbreMojo.
It can't hurt (except your robots.txt is publicly accessible, anyone can see your directory), but bots who honor the robots.txt file, will skip that directory anyway. If you don't use any CGI scripts, I would simply block it in `.htaccess`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "seo" }
Add custom body tag if product is out of stock I have searched endlessly for this but I am yet to find a solution. I have found ways to add custom classes through functions but can't seem to achieve through woocommerce where a custom class is added on the single product page when a product is out of stock. Any pointers would be much appreciated.
add_filter('body_class', 'SE_314220_custom_outofstock_class'); function SE_314220_custom_outofstock_class ($classes) { global $post; if($post->post_type !="product") return $classes; $product = wc_get_product( $post->ID ); if($product->get_stock_quantity() ==0) $classes[] = 'OUT-OF-STOCK'; return $classes; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to handle expired assets/content when user has direct URL An E-Commerce site has PDF coupons that expire after a certain date. What is the best way to handle them? I've heard allowing 404's aren't great for SEO and 301 redirects can clog up the .htaccess. There is already a landing page generated through internal links if a coupon is expired, so ideally I would like a way to capture requests to expired assets and redirect to that page. I'm curious, what ways are there to handle this?
Are these pdfs all in a sub-directory somewhere? You could add an .htaccess file to your sub-directory root then put this as the top line. ErrorDocument 404 /path/to/your404page This would make it easier to manage and keep it separate from your main htaccess file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "redirect, urls, seo" }
Check if comment author has url I wanted to add target=_blank to comment author link and also wanted to add redirection link to url. So here is what I did: <a href="site.com/go?url=<?php echo get_comment_author_url(); ?>" target="_blank"><?php echo get_comment_author(); ?></a> It works, but if comment author has no website I want to echo this: <span><?php echo get_comment_author(); ?></span> So, how to check if comment author entered url field? Tried this but did not work: <?php if ( ! empty( $fields['url'] ) ) { ?> **Solution** Thanks to shanebp answer here <?php if( get_comment_author() == get_comment_author_link() ) comment_author_link(); else echo '<a href="site.com/go?url='. get_comment_author_url() .'" target="_blank">'. get_comment_author() .'</a>' ?>
**Solution** Thanks to shanebp answer here <?php if( get_comment_author() == get_comment_author_link() ) comment_author_link(); else echo '<a href="site.com/go?url='. get_comment_author_url() .'" target="_blank">'. get_comment_author() .'</a>' ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, comment form" }
When variable value have space between word, doesnt show any result WP_Query I now create a widget, that return the post has same tag enter in inputbox I use WP_Query, but i have a problem. when i enter word with space in inputbox dont return any result, but when enter word dont have space its work correctly This is my inputbox <input type="text" class="widefat" id="<?php echo esc_attr($this->get_field_id('tagCategory')) ?>" name="<?php echo esc_attr($this->get_field_name('tagCategory')) ?>" value="<?php if (isset($tagCategory)) echo esc_attr($tagCategory); ?>"/></p> This is my Query $wpbp = new WP_Query(array( 'post_type' => 'post', 'tag' => $tagCategory, 'posts_per_page' => $numberOfPosts, 'orderby' => 'id', 'order' => 'ASC' ) );
It is correct behavior. And the reason for this problem is pretty simple... When you use `tag` param in `WP_Query`, then it searches for tags with given slug (string used in URLs) - so there should be no spaces. There are 7 parameters for slug searching in WP_Query: * tag (string) - use tag slug. * tag_id (int) - use tag id. * tag__and (array) - use tag ids. * tag__in (array) - use tag ids. * tag__not_in (array) - use tag ids. * tag_slug__and (array) - use tag slugs. * tag_slug__in (array) - use tag slugs. As you can see none of above takes name as value. If you want to search for tag name, then you should use `tax_query`: ... 'tax_query' => array( array( 'taxonomy' => 'post_tag', 'field' => 'name', 'terms' => $value ) )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query" }
Undefined index: action with code-snippets to change register page I see this error **Notice: Undefined index: action in /home/olexywro/public_html/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 6** in my login page with this code snippets: // Redirect Registration Page function my_registration_page_redirect() { global $pagenow; if ( ( strtolower($pagenow) == 'wp-login.php') && ( strtolower( $_GET['action']) == 'register' ) ) { wp_redirect( home_url('/zarejestruj-sie/')); } } add_filter( 'init', 'my_registration_page_redirect' ); Somone could me tell me why? 6th line of this code: if ( ( strtolower($pagenow) == 'wp-login.php') && ( strtolower( $_GET['action']) == 'register' ) ) {
You're doing this: strtolower( $_GET['action']) But you're not checking if `$_GET['action']` exists first. You can't count on it being set, because when you visit wp-login.php, it doesn't have `?action=` in the URL, but this hook still fires. So you need to add `isset( $_GET['action'] )` to your conditions: if ( strtolower($pagenow) == 'wp-login.php' && isset( $_GET['action'] ) && strtolower( $_GET['action'] ) == 'register' ) { }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions" }
Read array in php? I'm trying to add some custom user meta on the registeration. For example, I have field to set a fruit : function some_fruits($fruit= false) { $fruits= array(); $fruits['1'] = 'Apple'; $fruits['2'] = 'Banana'; $fruits['3'] = 'Apricot'; if ($fruit) { return $fruits[$fruit]; } else { return $fruits; } } But when I call this field with $display_fruit = get_user_meta($user_id, 'fruit', true); it displays **1** instead of **Apple**. How can I solve this ?
Fastest way would be something like this: $fruit_id = get_user_meta($user_id, 'fruit', true); //returns 1 $display_fruit = some_fruits($fruit_id); //will return 'Apple'
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, user meta" }
Read file contents the WP way I'm developing a sidebar widget. I need to read a `txt` file in a particular directory of the website. I can do it with `file_get_contents` or `readfile` PHP functions, but what's the best way to safely do it in Wordpress? (I don't know if the information is useful, but once red the content, I simply need to `echo` it) Any help is appreciated
Have you had a look at the Filesystem API?. The method of your choice would probably be `get_contents()` or `get_contents_array()`
stackexchange-wordpress
{ "answer_score": -1, "question_score": 2, "tags": "widgets" }
Can I use wp-cli to create posts with a custom post types? I regularly need to create a batch of posts of a custom post type, with names and meta values that follow a regular pattern. This seems like a perfect canditate for using wp-cli, but so far it hasn't worked. Using wp-cli, if I enter: wp post create --post_title='test' --post_status='draft' post_type='class_notes' I get an error: > Unable to read content from 'post_type=class_notes'. However wp-cli is definitely able to connect to this post type, as the following returns a proper list of labels and capabilities: wp post-type get 'class_notes' Is it the case that I simply cannot create a post with a custom post type using wp-cli?
It should probably be `wp post create --post_title='test' --post_status='draft' --post_type='class_notes'` (note the two `--` that mark it as a command option)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp cli" }
How to display taxonomy order child, parent I have taxonomy="local", Term: ABC (parent) \- HCM \- Q1 \- Q2 \- Q3 I used code in single_post_type: `<?php echo get_the_term_list(get_the_ID(), 'local', '', ', ', ''); ?>` but it display by letter (ABC,HCM,Q1,Q2,Q3). I want display child first->parent: Q1,Q2,Q3,HCM,ABC Please help me !!! thanks ![Pic](
@Aparna_29 , post Test Bình Dương ABC ( parent ) Thuận An HCM ( child 1 ) An Phú ( child 2 ) ![Get tax](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "terms" }
How do I detect which page I'm on within a paginated post? I'm using `wp_link_pages()` to paginate a post. I want to show something below the post content only on the first page of the post. Naturally I thought I'd use `get_query_var('paged')` to get the page number, but it returns 1 regardless of which page I'm on. I know I could parse out the URL manually to see which page I'm on, but there has to be a built in WordPress function for this.
The pagination query var on singular posts is `page`, not `paged`. echo get_query_var( 'page' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, pagination, wp link pages" }
Blog Page doesn't show summary but full content I am new to Wordpress and I have encountered a troubling issue. I have 6 posts already present on my posts section and I want them as summary to the blog page. I did make the changes in the Reading settings for the same by selecting **For each article in a feed, show** as **summary** . But I still get a full content on my blog page. Thanks in advance.
Try `the_excerpt()` function instead of `the_content()` Hope this will help
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, blog" }
How to Make Wordpress Default gallery responsive on mobile? I have read about the subject in many blogs and forums but I have not achieved anything. What I would like to do on my page is the following: decalaveras.com On this page, when accessed from mobile, it automatically goes from 3 columns to 1 column in the image gallery. Does anyone help me get this? I use the same theme, twenty sixteen.
They achieve this by using CSS Media Queries . Here are the specific ones controlling the gallery width. @media(max-width: 720px){ .gallery-item{ max-width: 50%; } } @media(max-width: 480px){ .gallery-item{ max-width: 100%; } } Add those into your style.css and see if they work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, css, gallery, responsive" }
Override load-styles.php with admin screen css I am trying to modify css. ![enter image description here]( I tried to modify the css with below code but does seems to work. if i try to change the color it works. #poststuff #post-body.columns-2 { margin-right: 300px; display:flex important; flex-direction:column !important; } It seems to work in if i modify directly form the chrome developer. function wpdocs_selectively_enqueue_admin_script( $hook ) { if ( 'toplevel_page_kita-general-settings' != $hook ) { return; } // wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'myscript.js', array(), '1.0' ); wp_enqueue_style( 'kita_options_page', get_template_directory_uri() . '/css/kita-admin.css' ); } add_action( 'admin_enqueue_scripts', 'wpdocs_selectively_enqueue_admin_script' );
If its just that one style you want to edit, you could try... add_action('admin_head', 'admin_styles'); function admin_styles() { echo '<style> #poststuff #post-body.columns-2 { margin-right: 300px; dispay:flex important; flex-direction:column !important; } </style>'; } Or add a separate stylesheet with something like this... add_action('admin_head', 'admin_styles'); function admin_styles() { echo '<link rel="stylesheet" href="style.css" type="text/css" media="all" />'; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "css, wp enqueue style" }
How to make a redirect link in wordpress? How to make a redirect link in wordpress. My site has two domain. I just wanted to set 1 link only and the redirect link is from domain A to domain B. I want to make a redirect link from ![enter image description here](
Check out 301 redirect plugin **< OR Add redirect rule in to .htaccess file RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ [L,R=301,NC] RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ [R=301,L]
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
WordPress Issue : The uploaded file could not be moved to wp-content/uploads/ I have created a local WordPress 4.9.8 setup with PHP 7 inside a Fedora running machine. When I try to upload media into the WordPress admin, it keeps saying that > The uploaded file could not be moved to wp-content/uploads/ I have given full(777) file permission for content/uploads directory but still, I get the same error. Finally, I tried to create the directory structure manually and place the media file by myself as follows > /var/www/html/test-jp/wp-content/uploads/2018/09/1024-xxxxx-logo.png What may be the reason?
This may due to the SELinux feature of the Fedora OS. You can temporarily disable the SELinux in Fedora as follows and test. Check SELinux status as `sestatus` If the SELinux is active, the result for the above command will be included. > Current mode: enforcing Execute command `sudo setenforce 0` to temporarily disable SELinux Then if you check `sestatus` > Current mode: permissive To re-enable SELinux execute command `sudo setenforce 1`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "uploads, media, media library" }
Use WP user status (logged_in) to manage access to independent application I have WP installed in the root of my website. In the same directory there’s a completely _independent_ application. What I want to do is the following: when the user accesses the page containing the application: 1. if he is in NOT logged into WP, the application must redirect him to the traditional wp-login page; 2. if he IS logged into WP, he can use the application; Is there any way to get/read WP user data from an independent PHP page? If not, can you suggest different solutions to avoid users having to authenticate multiple times on the same website (once for the CMS, once for the application)? Any help is appreciated.
You can access to any WordPress functions if you first include the `wp-load.php` to your custom PHP page. <?php require_once('path/to/wp-load.php'); if( ! is_user_logged_in() ) { auth_redirect(); } // Your application starts from here... ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, users, cookies, session" }
How to use a custom body_class as a condition? I am using a plugin that works great apart from the fact the breadcrumb is messed up. I would like to either try to ovveride the breadcrumb or remove it completely if I don't succeed. I am using that plugin with a custom category-slug.php file but "because of the plugin" I cannot target that page anymore using is_category because a kind of new page is generated. I have added a custom body_class to that new page in order to be able to style it with css. I was wondering if it was possible to use the custom body_class to target that page in functions, hooks or filters : Something like if ( body_class = 'my-class') { } Thanks in advance
You can try this, $body_css_classes = get_body_class(); if ( in_array( 'my-class', $body_css_classes ) ) { /* DO THIS */ } else { /* DO THAT */ } For more details please check this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "body class" }
CPT Post Title Permalink: Replace "@" (or all special characters) with dash "-" instead of just removing I have Custom Post Type "Email", where the Post Title is always going to be an email address, ie: **[email protected]** The problem I am having is the "@" is being removed in the permalink: **../exampledomain-com** I would like it to save as: **../example-domain-com** Replacing the "@" with a "-" I tried the following from here, but as someone more knowledgeable will quickly see, it doesn't apply to the permalink: function at_to_dash($title) { return str_replace('@', '-', $title); } add_filter('sanitize_title', 'at_to_dash');
Just make sure your filter runs _before_ the one that Wordpress itself applies - add a priority of 9: add_filter( 'sanitize_title', function( $title ) { if ( FALSE !== strpos( $title, '@' ) ) { $title = str_replace( '@', '-', $title ); } return $title; }, 9 ); Usage: echo sanitize_title( '[email protected]' ); Output: mytitle-example-org
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "permalinks, title, characters" }
Trying to remove plural 's' from search Query but it's just removing every letter of the end - what am I doing wrong? Thanks Trying to remove plural 's' from Woocommerce search Query but it's just removing every letter of the end - what am I doing wrong? Thanks function mySearchFilterFunction($query) { if ( !is_admin() && $query->is_main_query() && $query->is_search) { $search_term = $query->get('s'); $query->set('s', substr($search_term, 0, -1)); } } add_action( 'pre_get_posts', 'mySearchFilterFunction');
Try this: function mySearchFilterFunction($query) { if ( !is_admin() && $query->is_main_query() && $query->is_search) { $search_term = $query->get('s'); if (substr($search_term, -1) == 's'){ $search_term = substr($search_term, 0, -1); } $query->set('s', $search_term); } } add_action( 'pre_get_posts', 'mySearchFilterFunction');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "search" }
Increment user meta data by 1 each time a page is visited Can't for the life of me figure out why this isn't working, I've tried like below with $val, I've tried sticking the get_user_meta into the meta_value, I've tried just adding +1 in the meta_value but no matter what it always sets the value of the meta data to the number I'm trying to increment by so if its +1 it'll be set to 1 and +4 to 4. if(!get_user_meta(bp_displayed_user_id(), 'page_visits', true) >= 0){ update_user_meta(bp_displayed_user_id(), 'page_visits', 0); } $val = get_user_meta(bp_displayed_user_id(), 'page_visits', true) + 1; update_user_meta(bp_displayed_user_id(), 'page_visits', $val);
This line is wrong. `if(!get_user_meta(bp_displayed_user_id(), 'page_visits', true) >= 0){` That is "not value greater than or equal to zero". The NOT operator has precedence over the greater than comparison. So, assuming the value is a number, then NOT a number evaluates to false. Then you are comparing false to greater than or equal to zero. False == zero, so this evaluates to true, which means that in your next line, you set it explicitly to zero. So, the operator precedence is likely screwing you up. Try adding parentheses around your comparison before negating it. `if ( !( get_user_meta( bp_displayed_user_id(), 'page_visits', true ) >= 0 ) ) {` Also, counting page visits in user meta like this is fairly horrible for performance. Best to use some other real analytics solution.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, user meta" }
WPDB Update using Conditional Arrays **Issue:** I need to use the update function as per exact same format as below, the issue is with the conditional statement for `id` i.e. [ _WHERE (id = 1 OR id = 2) AND status = true_ ] $wpdb->update( $tbl_request_log, array( 'status' => false, ), array( 'id' => array($req1_id, $req2_id), 'status' => true, ) );
This is not posible with `$wpdb->update()`. If you check the source code, you will see these lines (lines 2150 - 2161), there is no way getting an `OR` in there: foreach ( $where as $field => $value ) { if ( is_null( $value['value'] ) ) { $conditions[] = "`$field` IS NULL"; continue; } $conditions[] = "`$field` = " . $value['format']; $values[] = $value['value']; } $fields = implode( ', ', $fields ); $conditions = implode( ' AND ', $conditions ); * * * **However** , you can write your own query using `prepare()` $wpdb->query($wpdb->prepare( "UPDATE `$tbl_request_log` SET `status` = false WHERE (`id` = %d OR `id` = %d) AND `status` = true", $req1_id, $req2_id ));
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wpdb" }
Get post ID of either existing post or new post If i'm using the following: post_exists( $class_post_title ) or wp_insert_post( $class_post ); How can I get the ID of either the post that exists, or the post that has been created?
From the documentation for `post_exists()`: > **Return** > _(int)_ Post ID if post exists, 0 otherwise. So you can get the ID just by assigning the result of `post_exists()` to a variable: $post_id = post_exists( $class_post_title ); The same thing works for `wp_insert_post()`: > **Return** > _(int|WP_Error)_ The post ID on success. The value 0 or WP_Error on failure. So you can do this: $post_id = post_exists( $class_post_title ); if ( ! $post_id ) { $post_id = wp_insert_post( $class_post ); } // $post_id is now the ID of whichever post exists or was created.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Image Upload Custom Form Field for Category and Custom Taxonomy I am currently customizing a Wordpress Theme, and I want to add a new form field on Category for uploading an image. The image should be retrieved from the Media Library. I found out that there are ways to do this, but I am not sure which one is the best practice or the recommended approach. Thank you in advance for your help.
There are several tasks you need to perform when you choose to do with custom code. And I personally think they're complicated tasks. Here is the list of what I can imagine. 1. Hook to the category edit page to add a new form for upload image. This can be done with the hook `{$taxonomy}_add_form_fields`. 2. Handle the image upload. Depend on what you want the upload field to be, it can be a HTML `file` input or a button to open the Media Library popup. 3. If it's just a `file` input, then you have to work with pure PHP to handle upload via `$_FILES`. 4. If it uses Media Library, then you need to work with JS to trigger the popup. As you're developing a theme, it can take a lot of time working on that. Besides, it belongs to plugin territory. So, I'd suggest using a plugin for that. Meta Box framework with MB Term Meta extension works great in this case. Disclaimer: I'm the author of Meta Box.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, images, taxonomy, media library" }