INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How do I create a secondary version of the_content I am trying to create a secondary/alternate version of the_content with some changes. This is the code I found to start with:- function new_content($content) { $content = str_replace('<img','<img class="newImgclass"', $content); $content = str_replace('<p>','<p class="newPclass">', $content); return $content; } add_filter('the_content','new_content'); I want a version of `new_content` that doesn't affect the original `the_content` that is when I echo new_content only, all the `p` have a `class="newPclass"`. Right now, the changes are being applied to the_content.
You're overcomplicating things. If you want `the_content()` to behave as it usually does, then don't change it via filter or similar. Just create your new custom function, eg like so (could be placed in your functions.php or if you're in a plugin somewhere there) function replaced_content() { $content = get_the_content(); // $content = str_replace ... print $content; } Then you can use it just like any other function <div class="main-content"><?php the_content(); ?></div> <div class="another-content"><?php replaced_content(); ?></div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, filters" }
Can I link to content dynamically from a page to a new page? I am new to Wordpress dev, and I have a page that loops through some custom fields(repeater) of people. I'd like each subfield link to go to another page that has more info from that person on the previous page(same field group data). Is there a dynamic way to do this or do I need to create a new page for each person to show more details on link click?
I solved this by using this as my link, then doing a check on name to show the correct data in the new template: <a class="btn" href="<?php echo esc_url( add_query_arg( 'n', $name, site_url( '/person-info/' ) ) )?>">Read more</a> And updating functions.php: function add_custom_query_var( $vars ){ $vars[] = "n"; return $vars; } add_filter( 'query_vars', 'add_custom_query_var' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, pages, advanced custom fields, links" }
How to set a user meta key value based on another user meta key value Each of the 7,000+ users on my site has around 25 keys in the usermeta table. I won't list them all, but two of the keys are "access_code" and "association". There are several dozen unique access codes for my site and each user is assigned only one access code. Here's what I'm trying to do: I want to find all the users with the access_code key with value "abc" and for each of those users where that value is true, their association key would change to "XYZ Corporation". Any thoughts?
You would need to use a meta query for this. $meta_query_args = array( array( 'key' => 'access_code', 'value' => 'abc', 'compare' => '=' ) ); $args = array( 'meta_query' => $meta_query_args ); $users = get_users( $args ); // User Loop foreach ( $users as $user ) { update_user_meta( $user->ID, 'association', 'XYZ Corporation'); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user meta" }
Do I need to use wp_reset_postdata for my function? I am using this function which seems to work fine, however I was wondering if I must use `wp_reset_postdata` after `endwhile`? function evecal_task_function() { $args=array( 'posts_per_page' => -1, 'post_type' => 'events' ); $now = time(); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); $fxdate = strtotime(get_field('fl_date',false,false));$datediff = $now - $fxdate; if ( $datediff > 1) {update_field('fl_expire', '1', get_the_ID());} endwhile; endif; }
Yes you should, otherwise you could interfere with another query happening on the same page. Using `$the_query->the_post();` interferes with the global `$post` variable, and `wp_reset_postdata()` serves that exact purpose, to reset the global `$post` variable to the original (global) query. _Read more_
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions" }
Prevent WordPress plugin from connecting to its server I have a WordPress plugin which keeps sending and retrieving data to its server. Is it possible to block url of plugin such as api.plugindata.com.
If you have access to your `/etc/hosts` file you can add > api.plugindata.com 127.0.0.1 or > api.plugindata.com localhost to route all traffic going to `api.plugindata.com` to your own machine. * * * If you don't have access to the file you can also search in the plugin source code where this domain occurs and either comment the code or maybe use a hook (if available) to prevent communicating.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins" }
Change Search display for Custom Post Type I want the search to not search for custom post type "mitgliederbereich" when on other pages, and when you are on the "mitgliederbereich" page, that only "mitgliederbereich" posts should appear in search. How can I achieve this? Here is my functions.php code for the function. function mitgliederbereich_filter_search($query) { global $post; if ($post->post_type == "mitgliederbereich") { if (!$query->is_admin && $query->is_search) { $query->set('post_type', array('post')); } return $query; } else { if (!$query->is_admin && $query->is_search) { $query->set('post_type', array('mitgliederbereich')); } return $query; } } add_filter('pre_get_posts', 'mitgliederbereich_filter_search');
Try below code function mitgliederbereich_filter_search($query) { global $post; global $wp_post_types; if ($post->post_type == "mitgliederbereich") { $wp_post_types['mitgliederbereich']->exclude_from_search = false; } else { $wp_post_types['mitgliederbereich']->exclude_from_search = true; } } add_filter('pre_get_posts', 'mitgliederbereich_filter_search'); Hope this helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, php, functions, custom taxonomy" }
How can I resolve the php notice "Constant EMPTY_TRASH_DAYS already defined" With `define('WP_DEBUG', true);` in wp-config.php, I get the following notice: > Constant EMPTY_TRASH_DAYS already defined in /wp-config.php on line 83 I have checked this file, and this constant is defined just once. I've also searched through all of the php files on the server and don't see that it's defined anywhere else. I've run a thorough search. The only other place it's defined is in `default-constants.php`: > if ( !defined( 'EMPTY_TRASH_DAYS' ) ) > define( 'EMPTY_TRASH_DAYS', 30 ); By commenting out the second line, the notice disappears. But it doesn't make sense to have to edit `default-constants.php` in order to define the constant in the proper place, which is `wp-config.php`. How should I define this constant properly, without editing `default-constants.php`, which risks being overwritten during an upgrade?
When defining any WordPress constants in wp-config.php you need to do it before this line: require_once( ABSPATH . 'wp-settings.php' ); That line loads many of WordPress’s default constants, and if you haven’t already defined them yourself then they’ll be defined in that line, meaning that any of them that you try to define after this line will have already been defined.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, wp config" }
UnInstallation of a Plugin from a developers perspective - The correct and clean method I think a good developer should provide the uninstallation in the safest and cleanest possible way. I downloaded various plugins today to understand the process, but everything was very confusing. I found that many plugins are using both uninstall.php files and `register_uninstall_hook(__FILE__, 'pluginprefix_function_to_run');` Is it correct? because the link that I have provided above says that these two are two different methods. so what is correct using either registration hook or uninstall.php or both?
They’re just two different ways of doing the same thing. It’s up to you which one to use, or whether to use both. Neither is ‘correct’. Use whichever makes more sense to you with the structure of your plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, uninstallation" }
Add attribute only to first image of every post via functions.php I would like to use a simple function in order to add a specific attribute (lets call it “example”) to the first image of every blog post, so that I don't have to do it manually in thousands of posts. Unfortunately I'm not very good with preg_replace so any help will be appreciated.
add_filter( 'the_content', 'wpse317670_add_img_attribute' ); function wpse317670_add_img_attribute( $content ) { $from = '/'.preg_quote('<img', '/').'/'; $to = '<img example="example"'; return preg_replace($from, $to, $content, 1); } This will add the `example="example"` to the first image found in every post content. There is another option, without using regular expression (possibly much faster and will use less memory): add_filter( 'the_content', 'wpse317670_add_img_attribute' ); function wpse317670_add_img_attribute( $content ) { $from = '<img'; $to = '<img example="example"'; $pos = strpos( $content, $from ); if ( $pos !== false ) { return substr_replace( $content, $to, $pos, strlen( $from ) ); } return $content; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, images, customization" }
Including a Customized Initialize File with a wordpress header We began this project without using wordpress, and have a significant amount of code related to user and access control that we would like included on CERTAIN pages in the site (namely the shop). We are using woocommerce as our cart, and we need to have the ability to connect our existing database of users to the site so that non employees can still use the front end while the shop that we want to create using woocommerce will only be accessible to people who have an account on the employee portal. The Directory for all the non-wordpress is in a folder below wordpress, or in other words, wordpress is at the root, and our project is in a directory below the root.
It's not clear where you need to add this additional code. But I would assume that it is in 'include'-type files that you need to run in the portion of the generated page. So, to do that, use the `add_action('wp_head','your-function-name')` to load your external function file: add_action('wp_head','include_my_include'); function include_my_include() { include get_template_directory() . 'your-function-file.php'; return; } See here: < . This code would be in your theme's (Child Theme, hopefully) function.php file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, woocommerce offtopic" }
How do I rewrite a single category link to point to a custom page? I have categories Cats, Dogs and Rabbits. I would like to change the link used for "dogs" when listing category on the front end to a custom page instead of the category archive.
Your goal seems to be to change the link which is output when listing the categories rather than making the existing link point to a different page as my last answer assumed. So I am going to try a different answer with a different solution. Using the filter `term_link` in the function `get_term_link()` you can change the link which is generated for a specific category. function wpse_317747_filter_term_link( $termlink, $term, $taxonomy ) { if ( "category" !== $taxonomy || "dogs" !== $term->slug ) { return $termlink; } return get_permalink( $target_page_id ); } add_filter( "term_link", "wpse_317747_filter_term_link", 10, 3 ); This changes the generated link if working on `category` taxonomy and the current term slug is `dogs`. Just set `$target_page_id` to correspond to the page you want the link to point to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, url rewriting" }
Multisite on single wordpress I've got single site on instance of wordpress. Now I want to add second blog so second site (separate domain) under the same hosting so the same wordpress instance. Is it possible to achieve it having sweparate not related domains? I'm new in wordpress area and most of tutorials I saw are about multidomain with having subdomain or subdirectories so not my case.
You absolutely can have a single WordPress Multisite installation serve up more than one domain. 1. Set up Multisite. For this site, it won't matter if you use subdirectory or subdomain. (If you plan to add other sites to this Multisite network, choose the option you'd prefer to use for those other sites.) 2. Create your new site. 3. Go to the new site's Dashboard, and mouse over its name in the admin bar at the top of the page. Select **Edit Site** from the dropdown menu. 4. Change the **Site Address (URL)** to what you want it to be, and save the changes. **Note:** You'll need to make sure that your new domain name is registered, and that its DNS entry points to the appropriate IP address. You'll also need to make sure that your WordPress server's configuration is set to accept requests for the new domain name. This is something you'll either need to handle yourself, or take up with your hosting provider.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, subdomains, domain, domain mapping, configuration" }
How to get current post user id I have some posts, each post have different authors(users). I save each author image avatar in **user_meta** table. Now i want show each author avatar in self posts. i get **user_id** with **wp_get_current_user()** function. but it work when user is logged in, i want when user not logged in get user id and show user avatar Here my code first way show user post avatar to all post not work $current_user = $post->post_author; <?php if (!empty(get_user_meta($current_user, 'user_avatar', true))): ?> <img src="<?php echo get_user_meta($current_user, 'user_avatar', true); ?>" alt="some text"> Second way work, but whene user is logged in $current_user = wp_get_currebt_user(); <?php if (!empty(get_user_meta($current_user->ID, 'user_avatar', true))): ?> <img src="<?php echo get_user_meta($current_user->ID, 'user_avatar', true); ?>" alt="some text">
To show author avatar per post inside loop you need to modify a little: $current_post_author_id = get_the_author_meta( 'ID' ); <?php if (!empty(get_user_meta($current_post_author_id, 'user_avatar', true))): ?> <img src="<?php echo get_user_meta($current_post_author_id, 'user_avatar', true); ?>" alt="some text"> Try, if it works for you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, theme development, themes, users" }
In modifying a file in a subfolder in a child theme, do I need all the files in that sub folder in my child? I am working with a Child theme and I needed to change a page in a subfolder in the theme. I uploaded the entire folder with all the enclosed files and modified the one file which worked. My question is... do I need all the files in the subfolder or just the one I modified?
No, you _should_ only need the files that you are going to modify. Technically you can move all the files from the parent-theme into the child-them. When you move only the files which need changing into the child-theme then it's a little simpler to keep track of the changes. Also good to know when working with child-themes: `get_template_directory_uri()` will always grab the path to the parent theme. & `get_stylesheet_directory_uri()` will always point to the path of the active theme (whether it's parent or child)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme" }
I changed the URL I changed URL to whatismyipadress.com's result instead of localhost, and i can't access it anymore where's that edited to change it back? I am using WAMP, if that helps. It doesn't meet the quality standards.
< helped. The answer must be at least 30 characters long.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls" }
Wordpress 4.9.8 doesn't save if content has style=" Wordpress 4.9.8 when I save a draft/publish return me an error: Gone The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource. I found that the problem is because my text has " style="bla bla bla" ". If I remove style= it works. I tried disabling all plugins, change to default theme, create a new installation, change PHP version from 5.6 to 7, 7.1, 7.2 : doesn't change. Any ideas?
I've had the same issue recently. Inline styles, as well as `<img>` tags, would cause the `410 Gone` status and error message (`The requested resource /wp-admin/post.php is no longer available on this server and there is no forwarding address. Please remove all references to this resource.` upon previewing or publishing the post. The problem was due to the hosting provider doing some maintenance on `mod_security` in cPanel. I found out when I asked them for the Apache logs so that I could look into it more. Contact your hosting provider to get this fixed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "save post, 500 internal error, draft, customization" }
How to display only the first two elements from ten same elements For example, in my theme, I have the following elements, <ul> <li> apple </li> <li> orange </li> <li> banana </li> <li> pear </li> <li> peach </li> ... </ul> I just want to display the first two _li_ elements, how to hide the other ones form the third element? The given condition to my issue is that, I cannot add any attribute like _id_ or _class_ to _li_ elements.
You can css ul li:nth-child(n+3) { display: none; } It'll not show 3rd and up.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, css" }
How to test another theme in a live WordPress website instead of live preview? I want to implement a new theme called Hepta on my current website, but when I test it using the live preview, it shows me limited content and features as it imports most of the contents from the active theme. Hence, I added few core plugins for that theme and also added theme import plugin. But, my concern is that if I activate the theme import plugin, the theme which is currently live(the older theme) might be affected, which will end up affecting the live website. So, I want to test the new theme and make it my primary theme once it is ready. How should I do this?
To try new theme over live wordpress site you need to duplicate the site in staging. There are many ways to do that: * Manually: create a sub-domain (ex: staging.domain.com) copy files and DB there and do your changes there after tested well migrate them to live. * Using plugin: A plugin named WP-Staging may help you the manual process. * You can use wp-engine service, which help you manage staging things. Hope one of the above way be helpful for you. A help link to check.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, child theme" }
Adding price to woocommerce cart item with get_price gets multiplied with 3? Similar question: WooCommerce Dynamic Cart Pricing function odb_add_length_price( $cart_object ) { if( !(is_admin() && !defined('DOING_AJAX'))) { foreach ( $cart_object->get_cart() as $cart_item ) { $price = $cart_item['data']->get_price(); $price = 1 + $price; $cart_item['data']->set_price( $price ); } } } add_action( 'woocommerce_before_calculate_totals', 'odb_add_length_price', 10, 1); If the product price is set to 100, then the total should be 101. The price returned is set to 103, for some reason it gets multiplied by 3. If i remove the $price and set a static value to 100, the returned price is 101. If i only return the price, the prices returns as 100. So each time i combine or calculate get_price plus x, it multiplies by 3.
The solution was to add `remove_action( 'woocommerce_before_calculate_totals', 'odb_add_length_price', 10, 1);` on the first line in the function. This removes the function each time it run and works like expected.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
current menu item hover not working? I am trying to change the text color of my current menu item as on hover its green but the background is green so I want the color to be white on hover but it does not seem to want to work, to view hover over the selected page on 'our products' website link li.current-menu-item a:hover{ color:white !important; }
I just checked your website and found some helpful CSS for your site. Find this line of CSS and change your color code, it will surely work. **For menu hover and focus ('Use this CSS in bedcentregrimsby.css')** .navbar-default .navbar-nav > li > a:focus, .navbar-default .navbar-nav > li > a:hover { color: #a4cb9a; } Please feel free to quote. Thanks, Cheers..!!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, html" }
Accessing parameters when adding filter I am trying to change the out put of **wc_get_rating_html** using this filter apply_filters( 'woocommerce_product_get_rating_html', $html, $rating, $count); So far this function works and of course doesn't make any changes. add_filter('woocommerce_product_get_rating_html', 'change_rating_output'); function change_rating_output($html){ return $html; } My question is that how I can access those **$rating** and **$count** parameters inside the function **change_rating_output** so that I can change the $html as I need.
When you call `add_filter()`, set the _fourth_ parameter to `3` (which is the number of parameters accepted by the callback function which in your case is `change_rating_output()`), and then change your `change_rating_output()` function so that it accepts the `$rating` and `$count` parameters: add_filter('woocommerce_product_get_rating_html', 'change_rating_output', 10, 3); function change_rating_output($html, $rating, $count){ // Now do what you want with $rating and $count return $html; } See < for further details.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic, filters" }
How to avoid duplicate users when I am using get_users? I using get_users to get users from my database. I am using this code: $args = array ( 'role' => 'Colaborador', 'role__not_in' =>[ 'subscriber', 'Administrator'], 'orderby' => 'rand' ); $users = get_users($args ); But in the output when use the foreach to print the data I need I found that are some user that are duplicate, appearing twice in the array. How can i fix this?
I think it's arguments issue. I recommend not to use `role` & `role__not_in` together rather either use only `role` OR use `role__in` & `role__not_in` combination. Also check your `role` param spelling. (see more on role) 2ndly `orderby` param `rand` is not valid according to codex (see here) so use proper param.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "array, users" }
Transform .wp-video to the native video player of the browser Is there a way to display a video using only the default video player of the browser, without the `mejs` / `wp-video` interface? The additional markup gives me a lot of trouble. I just want to use the `<video>` element, and handle my custom needs with CSS/JS. I won't say I'm an expert. I have considerable amount of experience with custom templates and hooks, but I can't figure this one out.
I've found the right way digging through the WP documentation: < This code seems to do the trick: function buildVideoPlayer($output, $attr) { // $output contains the default HTML string, created by the WP core // $attr is an associative array, which contains the parameters // (src, poster, preload, etc.) specified in the shortcode // The following piece of HTML string will replace the default WP video player return "<video src='".$attr["mp4"]."'></video>"; } add_filter("wp_video_shortcode", "buildVideoPlayer", 10, 2); Make sure to pass how many parameters do you want to catch in `add_filter()`. The default value is 1, but `wp_video_shortcode` has 4, and in this code, I needed the 2nd one.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, videos" }
I need to edit a widget, with no dashboard access What the title says. There's a widget on a website that I need to edit, but I only have ftp access. I've tried everything to try and locate where the template is for the specific widget I'm trying to edit (yes I tried Ctrl+Shift+F in sublime). This is the widget that needs to be edited: <div id="custom_html-5" class="widget_text et_pb_widget widget_custom_html"> <h4 class="widgettitle">The Inside Edge Service</h4> <div class="textwidget custom-html-widget"> <div class="testimonial-descript"> <p>I know Mike is a very solid investor and respect his opinions very much. So if he says pay attention to this or that - I will.</p> </div> </div> </div> The theme being used is Divi. The widget is located inside Divi's sidebar module. I am very desperate, any help is appreciated
It's a text widget, I think. If you need to modify title/content text then you need to modify in database (as you've no dashboard access*) If you need to change div structure for that widget, then you code in child theme. [*Note: if you got Database access then you can manage dashboard access too.]
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, widgets" }
In a continuous integration environment how do you implement the database entries for plugins and themes I'm setting up a wordpress continuous integration environment - git->composer->bitbucket-AWS codepipeline, etc. I have yet to figure out how I automate, for the development team, the setup of the WordPress meta data stored in the database. Theme customization, plugin setup/configuration, how to handle licensed plugins such as Offload Media Pro - where I can't share a license key with the development teams (some are contracted) but they need the plugin working to test. Does anyone have a good resource on how to solve these issues?
1. A lot of people use **WP CLI** to script the setup using Bash scripting. Here are some articles that discuss this. 2. Another approach is to **hardcode PHP scripts with embedded SQL** to do the setup. 3. A third approach is something I have been working on recently; **a set of PHP objects** to make setup and configuration easier for automated testing. The objects do not have nearly the breadth of functionality that WP CLI has, but if you prefer scripting in PHP over scripting in BASH you can always send pull requests for things you need to add. Hope this helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "wp cli, git, customization, composer" }
Why do I need to use The Loop on pages (inside page.php etc)? This question is addition to the following question. The answers to the linked question say that you have to write THE LOOP inside each php template file, but what is still open is WHY? why is it necessary to write is as part of page.php if this page is not supposed to display any post at all? another question why when I perform have_posts() inside page.php the return value is 'true'? shouldn't it contain no posts at all in this page?
The wording is (for historical reasons) a bit confusing. Actually Post can mean two things in WordPress: 1. The literal Post as in Blog-Post 2. A general term encompassing other default Post Types (like e.g. Pages) or Custom Post Types. So there is the Post Type "post" just like there is the Post Type "page". Here is a link to the Codex which elaborates on that a bit more: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "posts, loop, pages" }
Display Custom Post Type in divs I'm sorry if this is a already asked Question but i'm trying to get my custom post types displayed in grid like this: <div class="row> <div class="col-md-4> /* Start the Loop */ while (have_posts()) : the_post(); get_template_part('template-parts/post/content', get_post_format()); endwhile; // End of the loop. </div> </div that mean i would like to Display every post in a div with the class col-md-4
You'll want to move the row/columns inside the loop to do this. Perhaps even inside the template part. Seeing as I don't know what's in there, I'd suggest this: (notice I corrected your missing " at the end of div classes and added php start/stop) <div class="row"> <?php /* Start the Loop */ while (have_posts()) : the_post(); echo '<div class="col-md-4">'; get_template_part('template-parts/post/content', get_post_format()); echo '</div>'; endwhile; // End of the loop. ?> </div> this is fine if there are only 4 items in your row. or your system handles row calculations for you. If it doesn't you'll need to move the row call into the loop as well and add item count and then if statements for the 1st and every 4th item after that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Custom post type with slug for plural (archive) and for single I've been searching a way to have kind of "two" slugs for a custom post, let me give an example: www.mywebsite.com/articles/ or www.mywebsite.com/articles/page/2/ for the archive www.mywebsite.com/article/%post-name%/ for the single custom post
Both of these are controlled by the arguments passed to `register_post_type`, specifically, the `rewrite` and `has_archive` arguments: $args = [ 'rewrite' => ['slug' => 'article'], 'has_archive' => 'articles', // the rest of your arguments... ]
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "custom post types, slug, rewrite rules" }
How to get the count How to get the count of the `WP_User_Query` result while I use $query = new WP_User_Query( $args ); echo count($query); It returns 1 when there is no user. But I need 0 in that case. How can I get the count of users?
You should use a `total_users` property: $query = new WP_User_Query( $args ); $query->total_users; or `get_total` method: $query = new WP_User_Query( $args ); $query-> get_total(); Docs are your friend: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, wp user query" }
Link works although page was moved to another location I am a new to WordPress. Please help me with the following issue. I created page A and set Parent to X, hence its permalink was displayed as "< In page B, I reference to page A by the attaching the link "< there I then changed Parent of page A from X to Y. The permalink of A thus was updated as: "< I visit page B again and click on link "< it still works and brings me to link "< I wonder how it could happen? I was expecting to see Page Not Found or something like that as link "< is no longer available. There probably is something I don't know about how the link in WordPress works. Can somebody please help explain this to me? Thanks!
## That is called _canonical redirect_. And it's done through `redirect_canonical()` which basically > Redirects incoming links to the _proper URL_ based on the site url. and > Will also _attempt to find the correct link_ when a user enters a URL that does not exist based on _exact_ WordPress query. (Those excerpts were both taken from the function's reference.) So in your case, although the post parent of `A` has changed from `X` to `Y`, the post `A` (or a post with that slug) still exists, and therefore, when you visit the old URL: (old URL - post parent is X) with canonical redirect, you'd be redirected to the correct URL: (new URL - post parent is Y) and not being presented with a `404` (page not found) error page. Try visiting ` and you'd see the canonical redirect being applied. And if you visit ` assuming there are no post with `A123z` as the slug, then you'd see the 404 error page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks" }
Simply deleting XMLRPC file I have never used XMLRPC for any activity for my WordPress sites and also not going to do so. There are many articles on disabling XMLRPC on your site for additional security. In the use case scenario that I discussed when if that service is not required, why to disbale it or make it more secure ? I just wish to simply delete the xmlrpc.php. Will it cause any errors if I delete it ?
You shouldn't delete that file - it will be restored after update - so deleting it makes no sense (and it shouldn't be treated as security fix). You can disable XMLRPC using filter: add_filter('xmlrpc_enabled', '__return_false'); And even block access to that file. Below code for Apache (sandrodz showed code for nginx): <Files xmlrpc.php> Order deny,allow Deny from all </Files>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "xml rpc" }
How to disable a jQuery plugin on WordPress plugin page I have created a WordPress search plugin for a customer. It worked at my site, but when I installed it in my customer's website it broke, because there is a `jquery.formstyller` plugin installed there, which apparently styled the dropdown I used in the plugin with it's own divs and styles. Is there a way I can turn off that plugin when the user lands on the plugin page for searching?
Sure there is. < /** * Dequeue the jQuery UI script. * * Hooked to the wp_print_scripts action, with a late priority (100), * so that it is after the script was enqueued. */ function wpdocs_dequeue_script() { wp_dequeue_script( 'jquery-ui-core' ); } add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 ); Obviously replace `jquery-ui-core` with the handler of the script you want to remove. And don't do this globaly, only for your plugin page, where conflict happens.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, jquery" }
How to disallow a certain custom gutenberg block outside of an InnerBlocks block? I did add a custom block as an `InnerBlocks` block, called `slider`. Then i got another custom block `slider-item`. I think you get the idea. The slider block just allows `slider-item` as it's child blocks. Like so: <InnerBlocks allowedBlocks={ [ 'ajk/slider-item' ] } template={[ [ 'ajk/slider-item' ], [ 'ajk/slider-item' ], ]} /> Now I want to achieve that an **editor isn't able** to use the `slider-item` outside of my `slider` container block. Or is there some kind of **repeater block** possibility i do miss?! * * * WP `4.9.8` Gutenberg `4.2.0`
In the `slider-item` you can specify **parent** must be `slider`. That way, the `slider-item` cannot be used outside of your `slider` container block. Something like: registerBlockType('ajk/slider-item', ... parent: ['ajk/slider'], <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "block editor" }
Font Awesome icons disappearing My Font Awesome icon is not showing up in my menu. I reference it <i class="fa fa-pencil fa-fw"></i> and call the referring Stylesheet with <link rel='stylesheet' id='taptap-fontawesome-css' href=' type='text/css' media='all' /> in the header. It seems like the CSS gets applied correctly (width, et cetera) but the Icon itself is missing. I don't know what else to try so if anyone of you has an idea it is highly appreciated. Cheers Michael
It seems like that your pencil icon is being overwritten by your theme, see: < ![enter image description here]( Therefore, use the following code below to restore it: .fa-pencil:before { content: "\f040"; } Edit: Font Awesome 4.7.0 is highly outdated, as of this post, the latest stable version is Font Awesome 5.5.0 The following code will add Font Awesome 5 to you wp website and this will be placed in the footer. I recommend you doing this with the **Code Snippets plugin** or putting this in your child theme's **functions.php** function add_footer_styles_font_awesome() { wp_enqueue_style('fontawesome5', ' array(), null ); }; add_action( 'get_footer', 'add_footer_styles_font_awesome' ); See documentation: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css" }
Difference between these two nginx try_files statements for WordPress? What is the difference between these two try_files statements and which do you use and why? I've seen both used in tutorials online but cannot find an explanation of the differences or benefits of one over the other. location / { #try_files $uri $uri/ /index.php$is_args$args; #try_files $uri $uri/ /index.php?q=$uri&$args; }
As far as I know, WordPress does not require a `q=` parameter set to the original request (the _pretty permalink_ ). So in the second option, the `q=` parameter will be silently ignored. According to the Nginx wiki page for WordPress, the query parameters (`?$args` or `$is_args$args`) are included: > ... so non-default permalinks doesn't break when using query string I do not know what "non-default permalinks" are, but I just use the following, which works fine with _pretty permalinks_ : try_files $uri $uri/ /index.php;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "nginx, virtual hosts" }
Undefined index when saved to options $options = get_option('analytics'); if ( ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) { $options['analytics_startdate'] = '2018-12-01'; } Why this is throwing an error : > Undefined index: analytics_startdate , though i am specifying it.
> though i am specifying it. You're not actually specifying it. You're trying to use it in your regex and THEN you specified it. You can't use it in your "if" criteria when if it doesn't exist. You need to check to see if it exists first. The following would set your value if it is not set OR if it IS set and doesn't match your regex: $options = get_option( 'analytics' ); if ( ! isset( $options['analytics_startdate'] ) || ! preg_match( '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $options['analytics_startdate'] ) ) { $options['analytics_startdate'] = '2018-12-01'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "errors, offsets" }
How to check if you are on widget.php page? I am trying to write a widget and I need to add the color picker to my widget form. I want to add the script only on widget.php page and not on all the admin pages. Is there a way that I can detect the page inside the construct function of my widget? If not how I can include the script only when I'm on widget.php page?
You may use the global variable `$pagenow` to figure out if you are on a particular **admin page** , in your case this would be checking if you are on the `widgets.php` admin page: <?php global $pagenow; if( $pagenow === 'widgets.php' ) { ?> <script> // JavaScript goes here </script> <?php }   Furthermore, it will be helpful for you to use the plugin Query Monitor so that you may easily find out what conditionals may be used on a particular instance.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, widgets" }
Images do not show in the website, but they appear on new tab I am new to wordpress. I updated my wordpress website to the current version since I did not take care of it since 2013. However, after I updated it, my images do not appear on my website anymore. The pages only shows white blank space where the images should be. I can open the images on new tabs without any problem. I suspect that the problem lays on the theme setting, because when I changed to the other theme, it worked. I want to keep my current theme for my website. Where can I check the code to get the images?
You will need to learn about the Template Hierarchy, which is the process that is used to select the code that 'builds' the page. Within the template is the code that will display images, content, etc. You will also want to learn about "Child Themes", which is a way of customizing a theme without affecting the theme code. You don't want to modify the theme's code because any changes you make will be overwritten by a theme update. You might also consider contacting the theme's support forum to ask questions there about your theme. You have already determined the theme is at fault, so the theme's support is the place to ask questions about theme problems. So, the template is what needs to be changed. And to do this properly, create a Child Theme and copy your theme's template in there, and modify that code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Select2 in WordPress I have seen some best practices in WordPress about enqueueing scripts in WordPress. The scripts that are already in WordPress core should not be added again, but call that from WordPress core. I want to know whether `select2` is in WordPress core. I have found only one article saying so here
It's not. They may have been planning it for 4.1 or 4.2, as suggested in your link, but for whatever reason it never happened. You can see a list of core-registered scripts that you include here. Another thing to keep in mind is that many (arguably _too_ many) plugins enqueue their own version of the script, so be aware of potential conflicts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp enqueue script, scripts" }
can't get the product id in single woocommerce page In the single woocommerce page where I have actions like `woocommerce_before_single_product_summary` to show the products, I can't access the product id. I tried the following codes and it didn't work : $post->ID get_the_ID() $product->id $product->get_id()
If you're using `$product` and `$post`, then you need to use `global $product;` and `global $post` to get access to them. Did you do that? global $product; $product_id = $product->get_id();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Add custom post type archives to search results? How do I get WP search results to include custom post type (CPT) archives? For example, if I have CPT `'career'` whose title (in the template php) is 'Careers', how do I get search results to include the CPT archive URL (www.my-domain.com/careers) for "careers", "career", "jobs". I suppose the question might be, can one insert their own results into search, and how? I am/can optionally use the Relevanssi search plugin as well. I installed that to try and solve this problem, but it seems that alone is not enough. Thank you for your attention.
WordPress will not return a post type archive page in search results. Relevanssi might work, but a slightly easier route is to create a custom page template that lists the `career` items. Name the page "Careers" and it will show up in search results. Another advantage to this approach is that the page's text content can be displayed above the listing of `career` items, meaning you can manage that in WordPress rather than hard-coding that text in the template. There are disadvantages as well - paginating the `career` items is significantly more complex, so you may be tempted to disable pagination entirely and display them all on a single page. If you have dozens or hundreds of items, that is not a good idea.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "custom post types, search, custom post type archives" }
Undo WooCommerce CSV import I've done a CSV import through the WooCommerce import function. Unfortunately, there's something what went wrong. By now, almost all products don't show any data as it has somehow been overwritten. I'm running a webshop so this is kind of a huge problem. I've been searching for a solution everywhere but can't find the which makes me get back my original data from before. Unfortunately I haven't made a back-up before doing the CSV import. I'm praying for an answer.
If you don't have backup and you need to restore or undo your changes then there is only one way. You have to contact your hosting provider, ask them if they have old database backup. Generally they keep backups. If they will have then request them to restore. Hope this helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, database, import, csv" }
Custom menu items in admin I would like to add my own custom menu items to **Appearance > Menus**. How can this be done? The best way to describe what I want to do: ![enter image description here](
Use the `add_meta_box()` function (working example), and use `nav-menus` for the post-type. John Morris also wrote about this in 2013: How to Add a Fully Functional Custom Meta Box to WordPress Navigation Menus.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
code to add an extra selection to the menu editor I've given up looking for a plugin to achieve what I want (either they don't exist or I'm not using the correct search term) either way this leaves me with two options. Pay someone to make the changes to WP or do it myself. I'd prefer to do it myself but I admit that I'm a little nervous as I don't have much experience in .php coding although I am okay with html and css. What I'm trying to achieve is a menu created from the data contained in a custom field of my product posts. Like this... ![proposed_WP_menu_mod]( What is the simplest way to achieve this? If there's a way that doesn't involve editing the WP GUI that just automatically adds the values from the custom field to a menu, then I'd be happy with that too. Thanks for your help.
The WooCommerce Brands plugin has this feature. < ![enter image description here]( It sounds like you would need to move your brands out of the custom field and into this plugin, so the effort will depend on how many product brands you have and whether you're willing to start over with this plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Change permalink structure with post id I have a blog news from 1 year with around 1500 articles indexed on Google with this permalink structure (I know it is bad...): /%category%/%postname% (without slash!) Now I would like to change permalink structure without loosing SEO to: /%post_id%_%postname%/ (or maybe is better this one -> /%postname%/%post_id%/) I wrote this rule for the .htaccess but I am not sure it work well: RewriteRule ^/([^/]+)/([^/]+)$ ^/(\d+)_([^/]+)/$ [R=301,L] Thanks for your help!
postID/postname should work faster. Had a similar dilema and it turned out WordPress did all the 301 redirects automatically: Changing pemalink structure to /%post_id%/%postname%/ Didn't measure any rating or traffic drop. However, in the first week, page load time did increase because of most visits being redirected. After that, all fine. Make sure to change all the internal links, so they point to the new address, otherwise, users clicking on them will be redirected. Not very bad, but not perfect either.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, redirect" }
How to get data from WordPress site sql file I have an SQL file of my WordPress site but I lost my project files. So if I import the sql into my DB then can I run the sql with new database file? Or is there any other way to back the previous data?
The problem is that your images reside in **/wp-content/uploads/** and without this folder, everything will be restored except images and some files you have previously uploaded to the **Media Library**. The plugin(s) and the theme you used could be installed (uploaded and activated) again. To backup a WordPress websites you only need to backup the following: * **/wp-content/plugins/** \- to backup the plugin(s) you use * **/wp-content/themes/** \- you only need to backup your active theme, the theme you're using * **/wp-content/uploads/** \- Mostly for your images and other things you have uploaded to the Media Library * And of course your **database** Without these folders, you get all your post and pages back, but since you have no files and/or folders of your website, you will have no images, no plugins and you will have to install your plugin(s) and theme again or use another one.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "mysql" }
Restrict access to admin but allow admin_post hook I'm using this hook to allow only admin roles access dashboard add_action( 'admin_init', function() { if ( defined('DOING_AJAX') && DOING_AJAX ) { return; } if ( !current_user_can('manage_options') ) { wp_redirect( home_url('/meu-perfil') ); exit(); } }); Now I need to run a function when a form is submitted on front end, like so: function editUser() { error_log('message'); } add_action( 'admin_post_nopriv_add_foobar', 'editUser' ); add_action( 'admin_post_add_foobar', 'editUser' ); But the first hook is blocking the second one.
All you need to do is to modify your method of restricting users. add_action( 'admin_init', function() { if ( (defined('DOING_AJAX') && DOING_AJAX) || ( strpos($_SERVER['SCRIPT_NAME'], 'admin-post.php') ) ) { return; } if ( !current_user_can('manage_options') ) { wp_redirect( home_url('/meu-perfil') ); exit(); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "wp admin, hooks, actions" }
Send email to author of the post when the custom post status changes to published I have this answer in reference : < It sends to all users. I want to notify the author of the post only when author's custom post type gets published. Please help thanks
This should work -- make sure to change `my_custom_type` to the correct CPT slug: add_action( 'transition_post_status', 'notify_author_on_publish', 10, 3 ); function notify_author_on_publish( $new_status, $old_status, $post ) { if ( 'publish' !== $new_status || $new_status === $old_status || 'my_custom_type' !== get_post_type( $post ) ) { return; } // Get the post author data. if ( ! $user = get_userdata( $post->post_author ) ) { return; } // Compose the email message. $body = sprintf( 'Hey %s, your awesome post has been published! See <%s>', esc_html( $user->display_name ), get_permalink( $post ) ); // Now send to the post author. wp_mail( $user->user_email, 'Your post published!', $body ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, email" }
How to add / embed an author into REST data from a custom post type? We have a couple of post types which don't directly support authors. Instead, we have custom interfaces for choosing the author. We end up with an author ID, though, so I'd like to inject that author ID into the REST data for that custom post type. I've tried this: add_filter( 'rest_post_dispatch', function( $results ) { $result->add_link( 'author', rest_url( '/wp/v2/users/42' ), array( 'embeddable' => true ) ); return $results; }); … but that returns the link on the entire response (e.g. a set of 10 custom posts) -- what I want to be able to do is, for each post, add a link with that post's own user ID. Is this possible? I can't find documentation anywhere -- the best I found was this old page on Linking.
I found out how to grab each result and add a link. For the `ananda_video_audio` post type: add_filter( 'rest_prepare_ananda_video_audio', function( $results ) { // These two lines are unique to our code of course $video = new Ananda_Video_Audio( $results->data['id'] ); $authors = $video->get_author_IDs(); foreach( $authors as $author_id ) { $results->add_link( 'author', rest_url( '/wp/v2/users/' . $author_id ), array( 'embeddable' => true ) ); } return $results; }); Because embeddable is set to true, the author data all gets added to _embedded as well, in the response. Works great. Links I found helpful, in case you're doing something similar: * Adding links * List of REST filters in WordPress
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rest api" }
Template Loop - add switch case php My plugin template is currently as follows: if ( $query->have_posts() ) { ?> <ul id="list-con"> <?php while ($query->have_posts()) { $query->the_post(); ?> <li> <a id="floimg" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php if ( has_post_thumbnail() ) {the_post_thumbnail("mini-me");} ?><span class="flotnm"><?php the_field('fl_name'); ?></span></a> </li> <?php } ?> </ul> I need to incorporate a switch statement inside the loop but I can't figure out the php syntax. <?php $curtype = get_post_type( $post->ID ); switch($curtype){ case "firstcase": return <li> code as defined above break; case "secondcase": return some other <li> code as defined above break; } ?>
if ( $query->have_posts() ) : ?> <ul id="list-con"> <?php while ($query->have_posts()) : $query->the_post(); ?> <?php switch ( get_post_type( $post->ID ) ) { case "firstcase": ?> <li>code as defined above</li> <?php break; case "secondcase": ?> <li>another code as defined above</li> <?php break; } ?> <?php endwhile; ?> </ul> <?php endif;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, templates, switch" }
Writing a plugin which needs to upload files I am quite new to Wordpress development, and am writing a plugin which needs to have an option of uploading a spreadsheet, which the plugin will then work with and process data as appropriate. This is for front end users, not in the admin area. What is the best practice? Should I code an upload myself, or integrate another plugin, which my plugin calls and is dependent on? If the latter, any suggestions of a plugin???? Thank you
I think this could be part of the solution you're looking for: < How familiar are you with web-forms in php & file-uploads in general? Here's a prebuilt plugin solution for frontend uploads: < & here's a tutorial which looks to be along the lines of what you're describing: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development" }
List of pages of a specific user How to get list of pages of a specific user? And show them in a WordPress page. Say i have `page1` , `page2` , `page3` , `page4` created by `User1` . How to list them in a page like this: 1. page1 created: 1/1/2018 - 11:12 AM 2. page2 created: 2/1/2018 - 10:00 PM 3. page3 created: 3/1/2018 - 09:11 AM 4. page4 created: 4/1/2018 - 12:12 PM
I have found how to do it. Here is the code: $author_query = array('posts_per_page' => '-1','author' => 1,'post_type' => 'PAGE'); $author_posts = new WP_Query($author_query); while($author_posts->have_posts()) : $author_posts->the_post(); ?> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> <br /> <?php endwhile; more information: see here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages" }
add_rewrite_rule ignoring other params than the "p" param A specific post on my website has a shortcode that uses a parameter called "query" to produce its content. So, this is an example of a working URL: "my-post" is the permalink of the post and the page is using the "query" param correctly. However, we need to change this URL to a friendly one like < and then I was trying to use the `add_rewrite_rule` like this: function custom_add_rewrite_rules() { add_rewrite_rule( '^something-here/([\d]+)$', 'index.php?p=10219&query=$matches[1]', 'top' ); } add_action('init', 'custom_add_rewrite_rules'); When I try to access the friendly URL, I'm redirected to < successfully, but the **query** param is null (`$_GET["query"] = null`). I also tried making use of `add_rewrite_tag` to register "query", but with no success. If anyone has some light to shed it'd be more than appreciated.
It sounds like the plugin expects there to be a get param. Your rewrite-rule is removing the get-param before it can be used by the plugin. If the plugin hasn't been updated for a long time (it's abandonware) then you can go through the plugin and replace the get-param with the portion of the url which would have been the get-param. Just make sure to prevent the plugin from updating after you've made your edits. If you add the following function custom_add_rewrite_rules() { add_rewrite_tag('%query%','([^&]+)'); add_rewrite_rule( '^something-here/([\d]+)$', 'index.php?p=10219&query=$matches[1]', 'top' ); } add_action('init', 'custom_add_rewrite_rules'); & then replace `$_GET['query']` &/or `$_REQUEST['query]` with `get_query_var( 'query' )` in the plugin you've described, that should be enough to do the trick. Stephen Harris sums it up nicely in the answer here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "url rewriting, rewrite rules" }
How to display latest posts with authors image how can U get latest posts from a specific category and post them with the picture of the author. All authors are signed as an author on WordPress and they all have profile picture. Actually it will stand for columns side like this ![enter image description here]( the system must get latest 1 first then the second and third goes like this...
You could try something like this: <?php $args = array( 'category' => 12, 'post_type' => 'post' ); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <h4><?php the_author();?></h4> <?php the_excerpt(); echo get_avatar(get_the_author_meta()); endforeach; ?> In the example the category id is set to 12 - just replace it with the id of the category you want to use. More info: How to loop through posts: < How to get the author name: < How to get the author image: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, author" }
Sending POST Request from server I have to make a Post request to below and get the response . How can I do this in WordPress. I have [CLIENT_ID] and [CLIENT_SECRET] - i can just change it. [REFRESH_TOKEN] is `$_GET('code');` POST grant_type=refresh_token& refresh_token=[REFRESH_TOKEN]& client_id=[CLIENT_ID]& client_secret=[CLIENT_SECRET] Please help thanks
'wp_remote_post' is the function you're searching for. $response = wp_remote_post( $url, array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => array( 'param1' => 'value1' ), 'cookies' => array() ) ); if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); echo "Something went wrong: $error_message"; } else { echo 'Response:<pre>'; print_r( $response ); echo '</pre>'; }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "api, json" }
What is the wordpress page title php code? I have a header file in WordPress theme which always shows site title after the creation of a new page because of code `<?php echo esc_html( get_bloginfo( 'name' ) ); ?>` but I want it to replace with current page title instate of site name so, what would be PHP code for that?
Try below code. global $post; echo esc_html( get_the_title($post->ID) );
stackexchange-wordpress
{ "answer_score": -2, "question_score": 0, "tags": "title" }
How to start a new post with custom Taxonomies already set? Is there a way to start a post and have some default terms already added to the taxonomies?
You can use the `transition_post_status` action for that. New posts transition from `new` to `auto-draft`, so we check for that condition to only add terms on that initial auto-save. function wpd_add_post_terms( $new_status, $old_status, $post ) { if( 'new' == $old_status && 'auto-draft' == $new_status ){ wp_set_post_terms( $post->ID, array( 42, 23 ), 'category' ); } } add_action( 'transition_post_status', 'wpd_add_post_terms', 10, 3 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, custom taxonomy, customization" }
Get Term ID by Description I need to return the taxonomy term ID based on the terms description. Is this possible? I know the description along with the term ID is held within the `wp_term_taxonomy` table. However I was wondering whether I could retrieve it through a function rather than having to use wpdb.
I'm not aware of ready-made functions that support this, but you can easily construct a `WP_Term_Query` to do this. The following code is untested but should work: $args = [ 'description__like' => 'the description you\'re searching for', 'taxonomy' => 'category',//or other taxonomy 'fields' => 'ids', 'hide_empty' => false, ]; $term_query = new WP_Term_Query($args); foreach ($term_query->terms as $term) { // ID is in $term->term_id }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "taxonomy, description" }
How to Completely Remove Archive Title a.k.a the_archive_title? I want to remove it COMPLETELY. Not only the label "Archive: " but EVERYTHING. It should not appear. I've been looking for the solution for hours to no avail. Please help. Thank you!
Basically I'm adding this code in my theme's / child theme's function.php add_filter('get_the_archive_title', 'my_get_the_archive_title' ); function my_get_the_archive_title( $title ) { return ''; }; And voilà it's gone, completely, forever!! Just the way I want it!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, archive template" }
Set category page title in custom theme I'm new in wordpress. I am using one custom theme and install in wordpress. I want to change category page title and remove "Category:" prefix from title. How can I manage it from admin ? I don't know wordpress programming. So, I need to setup using admin panel. Please guide me. Thanks !! Page URL : < ![enter image description here](
In your `functions.php` of your theme file add the following code, taken from Remove "Category:", "Tag:", "Author:" from the_archive_title. add_filter( 'get_the_archive_title', function ($title) { if ( is_category() ) { //being a category your new title should go here $title = single_cat_title( '', false ); } elseif ( is_tag() ) { $title = single_tag_title( '', false ); } elseif ( is_author() ) { $title = '<span class="vcard">' . get_the_author() . '</span>' ; } return $title; }); Of course you need to read about how the `functions.php` works. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, title" }
How disable canonical redirect wp-signup I use wordpress 4.9.8. I want to close user access to site.com/wp-signup.php I added code in .htaccess <Files wp-signup.php> Order Allow,Deny Deny from all </Files> When I go to site.com/wp-signup.php, I get error 403.It's good for me. But if I follow the link /wp-signup and /wp-signup.ph and /wp-signup.p etc I get the following error: ![enter image description here]( This error is formed from a file - wp-includes/functions.php line 2722. How to display 403 error with any link /wp-signup ? Thanks for help!
The `<Files>` directive is used to target specific files on the filesystem, not URLs. To change this to target any _URL_ that starts `/wp-signup` then use mod_rewrite instead. For example: RewriteRule ^wp-signup - [F] This must go at the top of your `.htaccess` file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "htaccess" }
Adding number to date not working I am adding number stored in custom user meta data to current date. Here is my code $addeddays = get_user_meta($this->order->user_id, 'xxx', true); $timeBase = date('j.n.Y'); echo date('j.n.Y', strtotime($timeBase, "+ $addeddays days")); But output is 1.1.1970 What is wrong in code or how to do it with other method? I read question about this but in answers was also my method so I do not know why it is not working.
your code is not working, because you use `strtotime` incorrectly... It should be used like this: int strtotime ( string $time [, int $now ] ) But you pass formatted dated as first param, and another string as second one. So how should it look like? Like so: $addeddays = intval( get_user_meta($this->order->user_id, 'xxx', true) ); $timeBase = date('Y-m-d'); echo date('j.n.Y', strtotime( "+ {$addeddays} days", strtotime( $timeBase ) )); Or a simpler version (since `$timeBase is today: $addeddays = intval( get_user_meta($this->order->user_id, 'xxx', true) ); echo date( 'j.n.Y', strtotime( "+ {$addeddays} days" ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, custom field, user meta, date" }
how can i fix my display post in my index.php hello i try to display my post into a div grid of 3 columns with the code <div class="Jobs"> <?php if(have_posts()) { while (have_posts()) { echo'<div class="info_Job">'; echo '<h2>',the_title(),'</h2>'; echo the_post_thumbnail(),'</div>'; the_post(); } } ?> </div> but instead to correctly display the 3 differents post y 2 of the same post and another like below![enter image description here]( how can i correct this please
you're using commas as concatenators you're echoing `the_title()` and `the_post_thumbnail()` (use get if you're echoing) your `the_post()` was at the bottom <div class="Jobs"> <?php if(have_posts()) { while (have_posts()) { the_post(); echo'<div class="info_Job">'; echo '<h2>'.get_the_title().'</h2>'; echo get_the_post_thumbnail().'</div>'; } } ?> </div> If you don't want to use get but directly output do this instead: <div class="Jobs"> <?php if(have_posts()) { while (have_posts()) { the_post();?> <div class="info_Job"> <h2><?php the_title();?></h2> <?php the_post_thumbnail();?> </div> <?php } } ?> </div>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, css" }
custom post type to post association in wordpress I have created a custom post type called groups which is now available in the dashboard of the admin console on WordPress. I now want to be able to add multiple groups to posts. Similar to how one can add tags to posts. I would really appreciate some solutions to how I can go about doing so. thank you in advance.
Here is a plugin which does exactly what I asked for and it is very simple to use. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts" }
WooCommerce Storefront site-header padding Can someone please point me what folder/file location of where this precise bit of padding-top definition comes from other than **style.css**? I can't seem to find any sass/scss files in any of the storefront folders. padding-top property value appears to be calculated value IMO. @media (min-width:768px){ .site-header{ padding-top:2.617924em;
.site-header for storefront is in minified styles.css ![styles.css](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, css" }
URL rewrite problem in WordPress plugin I am having some trouble getting rewrite rules to work as I want in my a WordPress plugin. I added a rewrite rule: add_rewrite_rule('some_url','some_redirected_url', 'top'); The rule is written to .htaccess and the rule works as expected; when inspecting the $_SERVER variable I get the following: > $_SERVER['REDIRECT_URL']='some_redirected_url' > > $_SERVER['REQUEST_URI']='some_url' However, WordPress is parsing $_SERVER['REQUEST_URI'] for request arguments so the redirected request is not parsed. In other words, if I go to < the request is not working, even if the redirect works. If I go directly to < everything works correctly. How can I make WordPress parse the redirected URL?
If you want a rewrite rule that loads a post type archive from a different URL, the simplest way is via an internal rewrite, which doesn't get inserted into .htaccess. Internal rewrites map URLs to query arguments, and must result in a successful main query: add_rewrite_rule( 'some_url/?$', 'index.php?post_type=yourcpt', 'top' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, rewrite rules" }
Roles see different top menu (nav menu) I'm new to WordPress but has some knowledge in HTML, CSS and and a little of PHP. I'm trying to make a new menu in "top menu" that will be hidden to users that are not admin, but will appear to admin when signed in. Is there a plugin or such or do I need to hard code it? Advice(s) would definitely help me! Thanks!
**Please use this plugin for Roles see different top menu (nav menu) :** <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, user roles, admin menu" }
Display Category description I want display category description only the first page: I use in my category.php: <?php if(category_description()) :?> <section class="cat-desc"> <?php echo category_description(); ?> </section> <?php endif; ?> I try this: <? if (is_category()) { $page = (get_query_var('paged')) ? get_query_var('paged') : 1; if ($page == 1) { echo category_description(); //you don't need to include the category id on the actual category page - wordpress figures it out. } } ?> <? if (is_tag()) { $page2 = (get_query_var('paged')) ? get_query_var('paged') : 1; if ($page2 == 1) { echo tag_description(); //you don't need to include the category id on the actual category page - wordpress figures it out. } } ?> With the Category description is all ok but the tag description is missing. Thanks.
After adding descriptions to your tags, modify your WordPress theme to display the description at the top of each archive page. Open the "Appearance" section of your WordPress website's main menu and select "Editor." Click the "tag.php" link under "Tag Template" on the right side of the page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Which cache is kicking I have been struggling with a site that I inherited from another developer. My main problem is that, changes I make in the css file of the template don't get picked up right away, indicating that some kind of caching is kicking in. What I checked is. 1. The .htaccess file for any caching directive. 2. Any caching WordPress plugins that might be activated. 3. Any caching functionality implemented by the hoster. 4. Cloudflare or any other CDN. 5. [EDIT] I have tried different browsers and computers so the caching is server side. As you can imagine none of the above is enabled and yet my changes to the css take some hours to be seen. I am not a WordPress expert in any way, so I am asking the community of what other caching mechanism I might missing here. Thanks
You could change the file version each time the file gets updated. To do this, go to your `functions.php` file and find where the style-sheet is being enqueued (or registered) - it will look something like: wp_enqueue_style( 'theme-style', get_template_directory_uri() . '/style.css' ); and change it to: wp_enqueue_style( 'theme-style', get_template_directory_uri() . '/style.css', array(), filemtime( get_template_directory_uri() . '/style.css' ) ); This will change the file version each time you save it, forcing the new version to get loaded. As you very correctly pointed out, the styles have to be properly added in `functions.php`, not hard-coded in `header.php` or elsewhere.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, themes" }
get_option() does unserialize and don't remove \ When i `update_option()` with special caracter, for exemple **BARCA D'AREGOS** the serialize option puts save like that BARCA D\'AREGOS on database. If i do `get_option()` the display value is **BARCA D\'AREGOS**. `stripslashes()` don't work. Anyone have solution?
The get_option function is necessary for you using maybe_unserialize. update_option() function maybe_serialize passed. // store data time use maybe_unserialize. $data = maybe_serialize( $data ); // get/display time user maybe_unserialize $data = maybe_unserialize( $data ); Please check it with above example code
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, options" }
Wordpress PHP command and ELSE IF problem I am trying to show different messages based on user's custom field data. 'Site-access' meta field can be 0 or 1 and I was able to retrieve it for logged in user using the_field('site-access', wp_get_current_user()); Now I have to apply a comparison statement to this command based on retrieved data. Unfortunately it doesn't work within ELSE IF tags and I can't assign it to variable. $access = the_field('site-access', wp_get_current_user()); if($access == "1"){ echo 'welcome'; } else { echo 'access denied'; } **Working code** $access = get_field('site-access', 'user_' . get_current_user_id()); $int = (int)$access; echo $int; if ($int == "1") { echo "it's 1"; } else { echo "it's not 1"; }
It could work like this; but you need to use `get_field()` instead of `the_field()`, since the latter displays the field instead of returning a value. See < for more information.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How to Globally Use wp_localize_script() Ajax URL I have added this to my `functions.php` and need to use `ajaxURL` in all of enqueued scripts in the template (instead of enqueuing only one script here add_action( 'wp_enqueue_scripts', 'ajaxify_enqueue_scripts' ); function ajaxify_enqueue_scripts() { wp_localize_script( 'ajaxify', 'ajaxURL', array('ajax_url' => get_template_directory_uri() . '/app/login.php' )); } add_action( 'wp_ajax_nopriv_set_ajaxify', 'set_ajaxify' ); add_action( 'wp_ajax_set_ajaxify', 'set_ajaxify' ); but when I try to call an ajax method I am getting this error Uncaught ReferenceError: ajaxURL is not defined Is there any way to add the `ajaxURL` to all scripts?
You can conditionally echo the code on only few templates or specific pages. Here is an example: add_action ( 'wp_head', 'my_js_variables' ); function my_js_variables(){ // for specific page templates $current_template = get_page_template(); // return if there is no page template, or if the page template is other than template-x1.php or template-x2.php if( !isset($current_template) || ( $current_template != 'template-x1.php' && $current_template != 'template-x2.php' ) ){ return; } ?> <script type="text/javascript"> var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>; var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>; var myarray = <?php echo json_encode( array( 'foo' => 'bar', 'available' => TRUE, 'ship' => array( 1, 2, 3, ), ) ); ?> </script> <?php }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, ajax, wp localize script" }
Woocommerce Category Sort Dropdown In Woocommerce Category page default sort dropdown has like below options. ![enter image description here]( My question is what/how products sort by Popularity ? **Not a code** What is the **measurement** ? like if sort Price: Low to High,then we know those product sort Low price to High then How about **Popularity** ?
'Sort By Popularity' filter sort products based on total sales of product
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, woocommerce offtopic, sort, dropdown" }
WooCommerce - Conditionally enable shipping for virtual products I am currently enabling shipping for virtual product in WooCommerce by inserting the following in my functions file add_filter( 'woocommerce_cart_needs_shipping_address', '__return_true', 50 ); Is there a way to modify this so I can exclude a product? I have one specific virtual product that does not need a shipping address.
You can try following code: add_filter('woocommerce_cart_needs_shipping_address','fun_return_shipping_param'); function fun_return_shipping_param($needs_shipping_address) { $items = WC()->cart->get_cart(); $product_ids = array(); foreach($items as $item => $values) { $product_ids[] = $values['data']->get_id(); //You can get product id of product added in cart } if(in_array($your_product_id, $product_ids)) // check whether your product is in cart $needs_shipping_address = true; return $needs_shipping_address; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic" }
Where i should not use if (!defined('ABSPATH')) { exit; }? I think this best way to prevent direct access.. <?php if (!defined('ABSPATH')) { exit; }?> i have used this on all my php files..can it create problems? any files on WordPress theme i should not use it?
The point of that code is to prevent any PHP inside the file from being executed if the file is accessed directly outside a WordPress context. `ABSPATH` is defined by WordPress, so if it's missing when the file is accessed you can tell that it's not running in a WordPress context. So the only place you wouldn't use it is in any file that you did need to access directly. There probably shouldn't be any such files in a WordPress theme or plugin. The most common example might be a file for handling AJAX requests, but in WordPress you should be using admin-ajax.php or the REST API for that sort of thing.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "theme development, security" }
Not all my scripts are enqueueing From both scripts, only 'custom.js' is loaded, not common.js this is in my functions.php file: <?php function custom_scripts () { if (!is_admin()) { wp_deregister_script('jquery'); wp_enqueue_script('common', get_bloginfo('template_directory') . '/js/common.js', array(), '1.0', true ); wp_enqueue_script('custom', get_bloginfo('template_directory') . '/js/custom.js', array(), '1.0.1', true ); wp_enqueue_script('common'); wp_enqueue_script('custom'); } } add_action("wp_enqueue_scripts", "custom_scripts"); ?> any idea whyy?
Please try to change handler `common` name.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp enqueue script" }
how to bulk add one line in the first paragraph of all posts I want to add a sentence at the beginning of all posts of content directly into the post_content WordPress database. How do I? Either through the `function.php` or the MySQL command.
I'd go for solution posted by @butlerblog - it's a lot easier to manage and change in the future and it's better WP practice. But... If you're asking... Here are the ways you can do this: ## 1\. WP way: function prepend_content_to_posts() { $to_prepend = 'This will be prepended'; $posts = get_posts( array( 'posts_per_page' => -1 ) ); foreach ( $posts as $post ) { wp_update_post( array( 'ID' => $post->ID, 'post_content' => $to_prepend . $post->post_content ) ); } } Then you'll have to call that function. Be careful not to call it twice - it will add your content twice in such case. ## 2\. MySQL way: UPDATE wp_posts SET post_content = CONCAT('<YOUR STRING TO PREPEND>', post_content) WHERE post_type = 'post' AND post_status = 'publish' Be careful to change table prefix according to your config.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, bulk" }
Does anyone recognize shortcode ig_special_heading? Does anyone recognize the shortcode [ig_special_heading] and can tell me what plugin or theme it comes from?
I think the plugin you are looking for is < Apparently it has shortcodes that start with ig_ and provides them for things like... * Accordion * Buttons * Badges * Notice box * Columns * Clearfix * Divider * Google maps * Tabs * Toggle
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "shortcode" }
Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in ....functions.php on line 73 When I tried to edit my menu, it appeared > HTTP ERROR 500 Then I set `define('WP_DEBUG', true);` in _wp-config.php_ Once I try to save the menu, the following error appears: > Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in /www/web/keenker/public_html/wp-content/themes/keenker/functions.php on line 73 The tricky thing is, my line 73 in _functions.php_ is > return trim($title); And throughout the _functions.php_ file, I don't even have `REQUEST_URI` parameters. Appreciate for any help.
*Without quotes PHP interprets the `REQUEST_URI` as a constant** but corrects your typo error if there is no such constant and interprets it as string. When `error_reporting` includes `E_NOTICE`, you would probably get an error such as: > Notice: Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in _< file path>_ on line _< line number>_ But if there is a constant with this name, PHP will use the constant’s value instead. (See also Array do's and don'ts) **So always use quotes when you mean a string.** Otherwise it can have unwanted side effects. And for the difference of single and double quoted strings, see the [PHP manual about strings](<
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "functions, menus, errors, 500 internal error" }
WooCommerce Template overriding not working with woocommerce.php I am creating a custom theme with my own HTML. I am trying to override woocommerce template. I have created a template named with `woocommerce.php` but it still shows template with default structure. I checked the system status and it says that `Your theme has a woocommerce.php file, you will not be able to override the woocommerce/archive-product.php custom template since woocommerce.php has priority over archive-product.php. This is intended to prevent display issues.` But when I load the `shop page` it opens up with default structure. Some screenshots 1. Folder Structure 2. WooCommerece system status 3. woocommerece.php
I fix that by disabling Woocommerce template debug mode in config.php. define( 'WC_TEMPLATE_DEBUG_MODE', false ); You can check if the template debug mode is set via: WP Dashboard -> WooCommerce -> System Status -> Tools
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "woocommerce offtopic, template hierarchy" }
Can't access wp-admin Internal Server Error 500 I suddenly can't access `company.co.za/wp-admin`, as it redirects to with error 500 What should I do to resolve this? I know I can try disabling all plugins, but how do I do that without loggin into wp dashboard? Is there some other step I should take? Thank you
There are so many for internal server error. The main reasons for internal server errors are. 1. Corrupt .htaccess file 2. PHP Memory limit 3. Corrupted plugin 4. Incompatible PHP version 5. Corrupted core files In oder to fix this issue, you need to investigate in step by step order. To solve this issue first of all you need to enable Debug mode and check the issue. after that try with restoring .htacess file, enabling default theme, disabling plugins etc. if you still facing 500 internal server issue, check the tutorial on wpera --> <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp admin, redirect, 500 internal error" }
Found a translation function that is missing a text-domain. Function _n I am getting this error? > Found a translation function that is missing a text-domain. Function _n can this be fixed? how can the translation be done in this case? if( count($value) < $field['min'] ) { $valid = _n( '%s requires at least %s selection', '%s requires at least %s selections', $field['min'], 'acf' ); $valid = sprintf( $valid, $field['label'], $field['min'] ); } UPDATE The error is gone when `$field['min']` was assigned to a variable. I am i doing it correct?
Your error (actually a warning) seems to come from the Theme Check plugin. There's nothing wrong with the code you're showing above. `'acf'` is your text domain. and the _n function takes four arguments as you've given it. It strikes me that the Theme Check plugin is not very good at static analysis of function calls. I actually get a different warning with your code (possibly a later version) It seems it can't cope with array expressions like `$field['min']`. But of course WordPress/PHP will execute this just fine. As you discovered yourself, assigning a variable gets rid of the warning. So doing something like the following is absolutely fine and seems to satisfy Theme Check's code scanner. $n = $field['min']; $valid = _n( '....', '....', $n, 'acf' ); $valid = sprintf( $valid, $field['label'], $n );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "translation" }
Cannot modify header information - headers already sent during plugin activation I am getting this error > PHP Warning: Cannot modify header information - headers already sent by (output started at /home/zk2ba8xn663w/public_html/wp-includes/formatting.php:5100) in /home/zk2ba8xn663w/public_html/wp-includes/pluggable.php on line 1219 The error message only shows up if i am activating from TGM plugin actiavtion page, ... if i first install through tgm and then go to actual plugin activation page redirect works with out any problem. this is the redirect i am using function activation_redirect( $plugin ) { if( $plugin == plugin_basename( FILE ) ) { exit( wp_redirect( admin_url( 'admin.php?page=general-settings' ) ) ); } } add_action( 'activated_plugin', 'activation_redirect' );
Since the standard redirection works, I figured the conflict must be with TGM plugin activation already hooking to `activated_plugin` and producing output and thus preventing the redirect... Therefore the solution was to ensure that the plugin activation function hook was added to an earlier priority than the (silent) default of 10 most probably used by TGM: add_action( 'activated_plugin', 'activation_redirect', 9 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, errors, headers, activation" }
Query posts by custom fields (object post) As described in ACF documentation, here is the way to find all posts where a custom field called ‘color’ has a value of ‘red’. $posts = get_posts(array( 'numberposts' => -1, 'post_type' => 'post', 'meta_key' => 'color', 'meta_value' => 'red' )); But in my case, I need to find all posts where the ID of an object post custom field has a certain ID. How should I proceed to handle **meta_value** as an object, and targeting its ID key?
If you use Post Object field type, then it is stored as ID in custom field. So this should do the trick: $posts = get_posts(array( 'numberposts' => -1, 'post_type' => 'post', 'meta_key' => '<FIELD_NAME>', 'meta_value' => <POST_ID> )); PS. You should use 'posts_per_page' instead of 'numberposts' (which is deprecated).
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, posts, custom field" }
How to update the children of a post? i found nothing about it in the WP reference and Google, so i ask you: I want to update a post by a form - and with it its children. $post = array( 'ID' => $mainid, 'post_status' => 'wartend' ); $lead = wp_update_post($post); $children = get_children( $mainid ); foreach ($children as $child){ wp_update_post( array( 'ID' => $child, 'post_status' => 'wartend', 'post_parent' => $mainid ) ); } The post is getting updated, but not the children.
`get_children` returns an array of post objects by default: < So you would have to use `'ID' => $child->ID`, in this case... also my want to wrap the foreach with `if (count($children) > 0) {}` to prevent possible errors where there are no children. ie: $children = get_children( $mainid ); if (count($children) > 0) { foreach ($children as $child){ wp_update_post( array( 'ID' => $child->ID, 'post_status' => 'wartend', 'post_parent' => $mainid ) ); } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "front end, wp update post, posting" }
How can I change preview URL? How can I change the preview URL in Wordpress? When creating a post in Wordpress, there is a `Preview` button which takes you to the draft view. Because I have a custom integration of Wordpress and don't use a theme, I would like to change the URL of the preview link. Is this possible? How? Regarding the custom implementation, Wordpress posts are integrated in another framework. I do this by setting `WP_USE_THEMES` to `false`, loading `wp-config.php` and directly accessing the posts using `WP_Query()`. This means I am bypassing any Wordpress theme that is set.
You can do something like this, add to functions.php add_filter( 'preview_post_link', 'the_preview_fix' ); function the_preview_fix() { $slug = basename(get_permalink()); return " } More info HERE and HERE.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "wp config, previews" }
Wordpress drop domain alias my client try to change domain without me and now, when you try to go into < it will change into this site < I can not change it in wordpress admin. So can somebody tell me how to change it in files? I can connect into server by FTP.
If you are **NOT** using **WordPress MultiSite** add the following in wp-config.php. define( 'WP_HOME', ' ); define( 'WP_SITEURL', ' ); If you **ARE** using **WordPress MultiSite** you will need to access the database directly and edit the wp_options table and change "siteurl" & "home" to the correct url. Here is more info on changing the site URL
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, url rewriting, urls" }
ACF for audio url in wordpress audio shortcode This **WordPress shortcode** plays an audio file for you and works great: [audio src=" In a specific post or page ,I want to give it the **url** of song using **Advanced Custom filed (ACF)** plugin: [audio src="[acf field="sound_file_1"]"] but It does not work and tries to open _[acf feild"..._ as the song url. ( **Note** that I have defined the url field using acf and tested it alone without audio shortcode and it works)
I havent tested yet but I think can work, what I would do is create a function to create a new shortcode from those to doing this. function new_shortcode() { $urlmusic = get_field('sound_file_1'); echo do_shortcode("[audio src='$urlmusic']"); } add_shortcode( 'audioACF', 'new_shortcode' ); Use [audioACF]
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, advanced custom fields, audio" }
Redirect loop with similar URLs I want to redirect a page that ends in mysite.com/fall to mysite.com/fall-2019 I've renamed the original page permalink of mysite.com/fall to mysite.com/fall-old and to a 301 in the .htaccess that reads... RedirectMatch 301 /fall It redirects to the link by then the page says there is a redirection loop. I assume because that redirect is reading the /fall part from the new URL still. How can I make the redirect exclusive to that page?
`RedirectMatch` is very helpful if you want to redirect according to regular expression or similar. This is not needed here, and could be the very reason of your problem. Try the following instead Redirect 301 /fall /fall-2019
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect" }
tribe_get_start_time displays the current date and time on other post types than tribe_events i am displaying posts selected by an ACF relationship (with object format) on a page, including custom posts like tribe_events. I want to display the date and time on the tribe_events posts, but not on the other posts. I am using this code below. It displays correctly the start date and time of the tribe_events, but it also displays the current date and time on the other posts. What can i don to have the date and time only on the tribe_events posts ? Thanks ;-) <?php global $post; $posts = get_field( 'relationship' ); if( $posts ): foreach( $posts as $p ): setup_postdata( $p ); // Display the date of the event $p_event = tribe_get_start_time ( $p->ID, 'j F à H \h i' ); if ( $p_event ) { echo $p_event; } else ''; endforeach; endif; ?>
There are various ways to solve this. First coming to mind are checking via `is_singular()` or `get_post_type()`. Using the latter you could write foreach( $posts as $p ): setup_postdata( $p ); $post_type = get_post_type($p); if ($post_type === Tribe__Events__Main::POSTTYPE) { //or: if ($post_type === 'tribe_events') { // Display the date of the event $p_event = tribe_get_start_time ( $p->ID, 'j F à H \h i' ); if ( $p_event ) { echo $p_event; } else ''; } endforeach;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, date time, the events calendar" }
Assignments must be the first block of code on a line Validation Error on Travis Travis is giving me ~ **Assignments must be the first block of code on a line** for this specific line of code: $validate_string = $pf_param_string = substr( $pf_param_string, 0, - 1 ); It seems fine to me or am I doing the assignments wrong?
You're not supposed to assign multiple variables on a single line. Do them separately: $pf_param_string = substr( $pf_param_string, 0, - 1 ); $validate_string = $pf_param_string; Or, if you don't need both variables, just skip one of them: $validate_string = substr( $pf_param_string, 0, - 1 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, validation, coding standards" }
Images showing up in Post Editor, but not in Published Post I am trying to add three images by just inserting them into the post here: < Although I can see the images perfectly in my Media Library as well as in the post editor itself, somehow they don't show inside the actual post (only their captions). I have never encountered this issue before, would someone please be so kind to assist me?
The image is there. If you view the source you can see it. If you inspect the image in your browser you can see its hidden with CSS and set to display:none; This is the style your theme is applying. .single .entry-content img { display: none; } You will need to override that style with your own. .single .entry-content img { display: block; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, images, themes" }
Cant display an image via PHP in wordpress I have a strange problem, when I try to enter the source of an image tag using PHP it shows me the following error in the inspector <img src=(unknown) alt=""> this code fragment gives me the correct url, checked by seeing the CPanel and pasting and copying the address,but when I try to enter it via php the image is not shown $image = wp_get_attachment_image_src( $post_thumbnail_id); //echo($image[0]); ?> <img src="<?php $image[0]; ?>" alt=""> The next thing I did was an echo of image[0] and it gave me the url of the image, I copied it and pasted it in the tag and that's when it showed me the image <img src="mysite.com/wp-content/uploads/2018/11/957a...150x150.jpg" alt=""> I saw the page in Incognito Window and I did not show the image either. Any clues?
I think that you need echo the image, try this: <php $image = wp_get_attachment_image_src( $post_thumbnail_id ); //echo( $image[0] ); ?> <img src="<?php echo $image[0]; ?>" alt="">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, shortcode" }
WooCommerce add_to_cart I'm creating a WooCommerce product programmatically (Create product via CRUD) and wants to add it to its cart. Code I'm using is marked as legacy (WC_Cart) $cart = new WC_Cart(); $cart->add_to_cart($product_id); **The question:** Is there a newer way to add product(s) to the cart?
> **The question:** Is there a newer way to add product(s) to the cart? Well, `WC_Cart::add_to_cart()` is still the way to do it. Except (on the front-end), there's no need to reinstantiate the cart class: $cart = new WC_Cart(); because the main WooCommerce class already instantiates `WC_Cart`, and you can easily access the class instance like so: $cart = wc()->cart; //$cart = WC()->cart; // same as above, but wc() (i.e. lowercase) is actually preferred :) where `wc()` is a wrapper function that returns the main instance of the main WooCommerce class. And to add a product into the cart, you can use either of these options: // Option #1 wc()->cart->add_to_cart( $product_id ); // Option #2: Here we assign wc()->cart to a variable. $cart = wc()->cart; $cart->add_to_cart( $product_id ); Hope that helps! :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Override WooCommerce files from plugin I want to display my custom template for Single Product i.e. `single-product.php` For WordPress native templates, we can use `add_filter( 'single_template', 'custom_single_tmpl' );` and a callback function looks like this: public function custom_single_tmpl( $tempalte ) { return PLUG_DIR_PATH . '/templates/custom-single.php'; } Is there any way to **override** WooCommerce template files like that? **Edit:** I want to override Header and Footer as well, not only a single product content (same way as WordPress above `add_filter` does).
You would use my answer from this post to change the template: Redirect woocommerce single-product page Then you could use the following functions in your functions.php file to change the header and footer only on that template: function themeslug_footer_hook( $name ) { if ( get_page_template() == "Your Page Template" ) { <!-- New Footer Content --> } } add_action( 'get_footer', 'themeslug_footer_hook' ); function themeslug_header_hook( $name ) { if ( get_page_template() == "Your Page Template" ) { <!-- New Header Content --> } } add_action( 'get_header', 'themeslug_header_hook' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
Password Protect content() on homepage I need to password protect several pages and various areas of my templates if the page had a password enabled. This I can do on all subpages but on the homepage it's just not working. I do not want to whole site password protected, which many plugines seem to do - the built-in WP password protection is fine for this purpose apart from the homepage issue. When the visitor lands on the site, they can see elements of the page but some content is hidden. The content needs to be unlocked by just a password and not a registered WP account username/password. I assume the page used as home is treated differently than "normal" pages. The only thing I can think of is to instantly redirect the homepage to a "normal" pge that looks identical - then the password protection function would work? Google just offers either protecting the whole site (ie all you see in a login page) or protecting a normal page or using registered accounts to unlock content.
You can make the homepage password protected by creating a page and selecting it in the admin Settings > Reading > Homepage Displays. Then on the page settings make it password protected. Then create a template called front-page.php and use conditionals to show/hide the content. For Example... if ( ! post_password_required( $post ) ) { // Password Protected Content }else{ // Password Form echo get_the_password_form(); } More info on password protected pages. **Note** : If you have already entered your password, you can delete your cookies and refresh the page to see the password form again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "password" }
exchange words in echo with this code $wptitle = str_replace(array('Versandkostenfrei'), 'Kostenloser Versand', $wptitle); I exchange words in one of my loops. Now I am trying to change a word that is called with `echo $term->name;` how do I implement that? I tried <?php $wptitle = str_replace(array(' .echo ($term->name;)'), '', $wptitle); ?> but its obviously not working :-(
The PHP `echo` language construct that outputs the parameters passed. You don't want to do that in the middle of `str_replace`. To replace $term->name with an empty string, use: $wptitle = str_replace( $term->name, '', $wptitle ); Then when you want to print it, use: echo $wptitle;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
A number appears inside a div called wpb_wrapper, when I use a custom shortcode the page automatically display a number inside a div called wpb_wrapper, when I use a custom shortcode. but its nowhere in my function. When I delete the shortcode the number goes away. <div class="wpb_text_column wpb_content_element " > <div class="wpb_wrapper"> 1 </div> </div> Any clues? Is a custom Shortcode to display a grid of post, it contains PHP code, HTML tags and CSS. function millennium_grid(){ return include("mg-custom-grid.php"); add_shortcode('millennium', 'millennium_grid');
You can't `return` an `include` like that. A successful `include()` itself returns `1`, and since you're returning the return value of `include`, your shortcode is displaying "1". > Handling Returns: _include_ returns _FALSE_ on failure and raises a warning. Successful includes, unless overridden by the included file, return _1_. > > -- < If you want to output a template or similar file from shortcode, you need to capture it with output buffering: function millennium_grid() { ob_start(); include 'mg-custom-grid.php'; return ob_get_clean(); } add_shortcode( 'millennium', 'millennium_grid' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "shortcode" }
How to just show first line of content is it possible to show only the first line of content `<?php the_content(); ?>` or alternative only content between `<b>text</b>`?
you could also do something like: function rt_before_after($content) { $replace = "</b>"; $shortcontent = strstr($content, $replace, true).$replace; if ($shortcontent === false) $shortcontent = $content; return $shortcontent; } add_filter('the_content', 'rt_before_after'); It should look for the first `</b>` in your content and return everything before that. it then adds the `</b>` back. The function takes that string and replaces your content.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "content" }
How to set featured image as background for a specific category? I am currently trying to set the most recent post's featured image to be the background of my hero image. This is the code I'm using: <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?> Problem is, it shows the featured image of the most recent most on the entire site. I'm trying to make it use the most recent featured image from a specific category (ID is 42). Could I do something like this: <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID;cat="45"), 'full' );?>
I am not sure where you are trying to do this but give something like this a try. <?php $category_id = 45; query_posts('showposts=1&cat='.$category_id); if (have_posts()) : while (have_posts()) : the_post(); $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); endwhile; endif; wp_reset_query(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, thumbnails" }