INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to display custom taxonomy term meta on custom post type I am new to custom taxonomies, and created a taxonomy with 3 term meta fields using the generator on wp-hasty.com The taxonomy and new fields show up properly on the back end, and I am able to save to them. My problem is displaying them on the front end. I have a custom post type named "paint", and my taxonomy is named "colors", and the term meta fields are named "blue", "red", and "green". The term meta fields are regular text fields with text in them. I would like to display the contents of "blue", "red", and "green" on my custom post type page, if the page has the taxonomy tag colors. Online I found `get_term_meta()`, but I couldn't get it right. I appreciate all help. Please let me know if I'm not being clear enough with my question.
**1.** If you need to display this informations once. For example in the page header, use get_queried_object(). echo get_term_meta( get_queried_object()->term_id, 'blue', true ); echo get_term_meta( get_queried_object()->term_id, 'red', true ); echo get_term_meta( get_queried_object()->term_id, 'green', true ); **2.** If you need to display this informations in the each post, you must create a small loop. $terms = get_the_terms($post->ID, 'colors'); foreach ($terms as $term) { $term_id = $term->term_id; echo get_term_meta( $term_id, 'blue', true ); echo get_term_meta( $term_id, 'red', true ); echo get_term_meta( $term_id, 'green', true ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, terms" }
What matters should I care to make my theme SEO friendly? I want to know all the things that I should care for a well SEO optimizations for my theme. What options should I provide to users for SEO optimizations? Please suggest all the things those you know with a short brief. Thanks in advanced.
* The theme you are going to made has to be developed according to up-to-date coding standards and can be validate : < * You need to use semantic tags : <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "theme development, seo" }
Flamingo's Fatal error: Allowed memory size of 134217728 ... wp-includes/wp-db.php on line 2516 I’m exporting a report on Flamingo but receiving this error: **Fatal error** : Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in **/home/storage/.../public_html/wp-includes/wp-db.php** on line **2516** I updated memory_limit on PHP.ini top 512M and server says that this is an error on application, not on the server. Can anyone help?
It's pretty common that this error is due to a recursive loop, not to memory lack.. so I suggest to check the integrity of data first. Increasing memory limit will never solve the problem in these cases
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "fatal error" }
How to locate where an element is generated? I am trying to find where an element is generated (`<div class="slicknav_menu">`), this normally is easy, I just search on the theme folder for the class name (I normally use Grep for Windows and it "always" works), but I do not find it anywhere, at first I thought it may be generated by a plugin, but I disable them all and the element was still there, I changed to a default theme and it got removed, so I know it's generated by the theme but I am not able to find where is it. What do you do in similar situations? I am not sharing links to my website or the theme since I think it's more important to know how to solve similar issues in general.
SlickNav looks to be a "Responsive Mobile Menu Plugin for jQuery". Your theme probably ships with it. It's written in JavaScript so try greping for the class name `slicknav_menu` in the JavaScript files included with the theme. As an aside, another debugging tip for next time: Most browser dev tools allow you to disable JavaScript. If you can't find something in the PHP, try disabling JS on the page and reloading. If the _$thing_ is not there anymore, it's almost certainly due to JS.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "customization" }
Embedded Options in a Custom Metabox I am successfully able to create a number of custom metaboxes. There are a number of tutorials online that help with that. My question is how to include embedded options in a custom metabox? So, what are embedded options? Well, if you take the "Publish Post" metabox, for example, this is what you will see: ![enter image description here]( Notice that if you click on the "Edit" link that is circled in red in the image above, this is what you will end up with: ![enter image description here]( Those are what I call embedded options (I do not know the term for them, so I came up with that name). And what I want to do is something similar. I know I can achieve that with JavaScript/AJAX, but I like to know if there are already pre-written methods in WordPress and a process to follow for creating that part of the metabox so that I do not re-invent the wheel. Thanks.
After a long investigation, it turned out that there isn't any WordPress method that generates that information via methods/functions. That functionality should be built manually. For example, for the "publish post" metabox which contains the required functionality above, the code is listed here <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, metabox" }
Why is wp api returning old acf values? I have a list of custom post types (Events) with ACF fields for start and end dates that I'm getting using WP-API. I'm using the fetch api to make the calls. I have the acf-to-rest-api plugin installed and activated. I'm using the lastest versions of everything. I changed the start and end date fields of an event after it had been created. The new values are displayed in the post editor, and when I dig into the actual database it's got the correct updated values. But the WP-API call is return the old value. What could be going on? I've tried clearing all caches I could think of, messed around with transients... anything else?
I found the problem and I'm embarrassed... I had hardcoded one of the request urls in my js, but used the url to the staging site. So the value wasn't updated because the value in the staging site hadn't changed. #facepalm#
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, javascript, advanced custom fields, wp api" }
Matching slug terms from one array to those in array of WP_Term objects to output term names I'm using WordPress's `get_terms` to return an array of `WP_Term` objects containing the term_id, name, slug, etc. for the child terms of a given taxonomy. I've saved this array to `$tax_terms`. I have a different array—`$active_filters`—containing just the _slugs_ of terms that match certain taxonomy terms; for instance, from a `var_dump` of `$active_filters`: array (size=3) 0 => string 'term-1' (length=6) 1 => string 'term-2' (length=6) 2 => string 'term-3' (length=6) I'm wondering if there's a way I can run a `foreach` that will compare this array of term slugs to those in the array returned by `get_terms` and return the `name` for any matched slug? So, the example above would output "Term 1", "Term 2", "Term 3". I've tried using `array_search` but to no avail, thus far. Any assistance is greatly appreciated.
Perhaps array_map ? This will give you an array of term names which matched your slugs in $active_filters: $matched_terms = array_map(function($term) use ($active_filters){ if(in_array($term->slug, $active_filters)){ return $term->name; } else{ return false; } }, $tax_terms); //remove the empty array elements which came from terms which didn't match a slug $matched_terms = array_filter($matched_terms);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "array, slug, terms" }
Find a Javascript ID when trying to deregister? I am trying to remove a plugin from loading on a specific page. This is the idea I have to do it: //Remove plugin Javascript function de_script() { wp_dequeue_script( 'name-javascript-1' ); wp_deregister_script( 'name-javascript-2' ); } add_action( 'wp_print_scripts', 'de_script', 100 ); Problem is that when I view the source of the page there is no ID like there is for CSS? Any ideas how to do this when the Javascript does not have an ID? Thanks
There is a global variable `$wp_scripts`, so pop this in a PHP template and have a look: global $wp_scripts; print_r($wp_scripts); Found it in the Source section of the Codex entry for `wp_print_scripts`, btw - always a good place to look!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions" }
PHP Use Declared array Variable inside already Declared Array i have created one class in which i declared public associative array. class test{ public $basicCols= array( array('title'=>'KEY', 'field'=>'slug','options'=>$optList), array('title'=>'KEY', 'field'=>'slug'), } public $optList= array("one"=>"One","two"=>"Two"); } But when i execute code its giving me error. I tried $this->$optList $this->optList $optlist is there any other way to declare variable inside variable in class. thank you in advance.
This is more a generic PHP question than anything to do with WordPress, but I'd suggest setting the value in the constructor: class test { public $basicCols; public $optList = array( 'one' => 'One', 'two' => 'Two' ); function __construct() { $this->basicCols = array( array( 'title' => 'KEY', 'field' => 'slug', 'options' => $this->optList ), array( 'title' => 'KEY', 'field' => 'slug' ) ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, array, variables, post class" }
Using any plugin results in http 500 error (and only plugins) I am working on a site that was previously made by someone else. Whenever I try to use a plugin (eg. Dropbox Backup & Restore, Reset WP) I get an http 500 error.[I made a backup using filezilla.] **using any plugin results in http 500 error (and only plugins)** troubleshooting -htacces.bak (ftp) **x** -PHP memory limit (ftp) **x** -faulty plugins **x** -permissions for folders (ftp) **x** -corrupted core file (ftp) **x** -host end issues - **contacted** **I am at a loss here, and don't know what else to try. Now, it might be a fault on the hosting end, but I would really appreciate some input as to what else might be causing this.**
try these : go to dashboard >>updates>> reinstall wordpress if still does not work rename: plugins folder to "plugins-old" and create new empty plugin folder if still does not work try changing the theme let me know how it goes
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, ftp, 500 internal error" }
How to stop ultimate members to redirect comment authors to user profile? I'm having a problem with the Ultimate Member plugin. The comments author links get redirected to the user profile. I need the basic WP feature- pointing to author URL/website. The plugin is overriding the basic function. I checked the "redirecting the author page" on the plugin option, but that option is for author-posts-permalink but not comment author website URL. Now, how do I disable that?
with actual version of Ultimate Member (2.0.21), you can do that with this filter : add_filter("plugins_loaded", function () { remove_filter('get_comment_author_link', 'um_comment_link_to_profile', 10000, 3 ); }, 50);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "comments" }
PHP code printed into CSS classes So, I'm working on a site. I didn't develop and I don't have access to the developers. The site uses a custom designed Bootstrap based theme, built with Page Builder. I just moved the site to a development server, and added myself a user and updated. The issue I'm having seems to be that one of the functions that write the page's HTML is messing up somewhere, and printing PHP into the CSS classes. The page's theme renders correctly on the production server, but don't write the correct class and style attributes on the dev server. The output HTML with the PHP is `<div class="spacer spacer-60"></div></div></div></div></section><section data-anchor-title="Profile" data-anchor="profile" id="profile" class="<?print implode(' ',$classes); ?>" style="<?print implode(';',$styles); ?>">` I've poked around in the theme files, and there isn't an obvious place where the app is choking on this. Thanks
Well, previous developer was a little bit naughty (;)) and used PHP short tags, which is a bad practice... And even worse - he used them a little bit wrong, I guess... As you can see, there is something like this in your code: style="<?print implode(';',$styles); ?>"> Of course there is no such thing like `<?print` in PHP, it should be `<? print`. But you shouldn't use short tags (`<?`). They're turned off on some servers, so here's how to fix it: `<div class="spacer spacer-60"></div></div></div></div></section><section data-anchor-title="Profile" data-anchor="profile" id="profile" class="<?php print implode(' ', $classes); ?>" style="<?php print implode(';', $styles); ?>">` PS. Also... It would be nice to add some proper escaping in there...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, theme development, twitter bootstrap" }
How to receive all the meta information of a post ? How can I get all the meta information of a particular post_id, if my meta_key = 'title' and meta_value = 'My Content Template' meta_key = 'download_url' and meta_value = '< and i have 10 meta key and meta value for the same post. How can i get all the meta information in a tabular format such as: Title URL My Content Download Data I have tried below code: <table> <tr> <th>Title</th> <th>Download URL</th> </tr> <?php $stored_titles = get_post_meta( $post->ID, 'title' ); $stored_urls = get_post_meta( $post->ID, 'download_url'); ?> <tr> <?php foreach($stored_titles as $title) { ?> <td><?php echo $title; ?></td> <?php } ?> <?php foreach($stored_urls as $url) { ?> <td><?php echo $url; ?></td> <?php } ?> </tr> </table> Please any one help to get this done.
I'm not sure that this is what you wanted, but let me try... <?php $titles = get_post_meta( $post->ID, 'title' ); $urls = get_post_meta( $post->ID, 'title' ); ?> <table> <thead> <tr> <th>Title</th> <th>Download URL</th> </tr> </thead> <tbody> <?php foreach ( $titles as $k => $title ) : ?> <tr> <td><?php echo esc_html($title); ?></td> <td><?php echo esc_html( array_key_exists( $k, $urls ) ? $urls[$k] : '' ); ?></td> </tr> </tbody> </table>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "post meta" }
Wordpress redirecting to 127.0.0.1 when accessing the site from a remote device I've installed a Wordpress site on my local Apache Ubuntu 18.04 server with a fixed IP `192.168.100.150`. The website is working fine locally (`localhost/wordpress`), but when I try to open the site from another device (`192.168.100.150/wordpress`), it automatically redirects me to `127.0.0.1/wordpress` and I get a "`127.0.0.1/wordpress`" refused to host message. What is wrong?
Well, that was a problem related to my browser's cache - opening the site in incognito mode fixed the problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "redirect, localhost, apache" }
Create WooCommerce Product Category Programmatically I am having trouble creating a `woocommerce` product category programmatically. I plan to automate the creation of product categories based on the creation of a new term in a specified `custom taxonomy`. Any help is greatly appreciated, Thank you.
To create a taxonomy term programmatically you can use `wp_insert_term` function. <?php wp_insert_term( $term, $taxonomy, $args = array() ); ?> It has 3 params: > **$term** (int|string) (required) The term to add or update. Default: None > > **$taxonomy** (string) (required) The taxonomy to which to add the term. Default: None > > **$args** (array|string) (optional) Change the values of the inserted term Default: None WooCommerce categories are stored as terms in `product_cat` taxonomy, so if you want to create some new category, you can use this code: wp_insert_term( 'My New Category', 'product_cat', array( 'description' => 'Description for category', // optional 'parent' => 0, // optional 'slug' => 'my-new-category' // optional ) );
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "plugins, theme development, woocommerce offtopic" }
What is stored in the webserver? (Separated Database) Assuming a classified website where real estate agents post their houses advertisement for rent or sale When I built the server, I separated the database and the webserver > Database Server: Ubuntu and MariaDB only > > Webserver: Ubuntu, Nginx, PHP, Redis, Wordpress I have been wondering all the time what is actually being stored in webserver. Say, if I destroy the webserver and create a new set of webserver (of course complete with all the same Wordpress plugin + theme), what do I lose? I think I will only lose the house images that are uploaded by the house agents? Also, is there any guide to do set up load balancer? Couldn't find a good one so far. Thanks heaps
The WP database contains **everything** that is related to content: posts, pages, theme settings, plugin settings, media of all kinds. So if you were to replace the WP database with a brand-new WP database, **all of your content** \- and many of your settings - **will be gone**. The WP 'code' (PHP, CSS, JS source files) is stored in the wp-xxxxx folders, plus the site root. Some CSS might be stored in the WP database, but the 'core' code is in the site root and the wp-xxxxx folders. Can't speak to load balancing...perhaps someone else will chime in on that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "database" }
How can I show some description in the "All Posts" view of a custom post type in Dashboard? I want to show some short description in the **All`post_type`** view of a custom post type in the WordPress Admin Dashboard. For example: > For this custom post type, my shortcode is this `[shortcode]`. Is there any way to show this before all posts?
The filter `views_{$this->screen->id}` is fired just after the title of post edit screen has been print to screen, so it's a safe place to just echo what you want. So you can simply check here: function post_type_desc( $views ){ printf('<h4>%s</h4>', __('Your description here.') ); // echo return $views; // return original input unchanged } add_filter("views_edit-POST_TYPE_HERE", 'post_type_desc'); Replace `your_post_type` here in `POST_TYPE_HERE`. Hope this will help you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, dashboard" }
Woocommerce - Add HTML around Product description How can I add HTML around the product description? Exactly around the `Product Description` heading?
You can overwrite the default WooCommerce description template by copying the description template **`description.php`** from WooCommerce templates to **`/woocommerce/single-product/tabs/`** in your active theme folder. Refer WooCommerce documentation to understand how to overwrite WooCommerce default template files.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, templates" }
get the_content by ID and save the result to one array I try this: <?php function get_ct($id){ $ct = apply_filters('the_content', get_post_field('post_content', $id)); return $ct; } $arr = array('post_content' => get_ct(126)); echo json_encode($arr); ?> but the post_content 's values ist null any suggestion? thanks
You can use `get_the_content()` to fetch the post content, e.g.: $content = get_the_content( $post_id ); Then you can pass it through `the_content` filter and json encode However, based on your comments, it looks like you're creating an endpoint for AJAX calls that returns post content. Don't bother! WordPress comes with one out of the box! e.g. The response has a `content` field and even contains a `rendered` version that contains a fully rendered post as you desired. You don't need to do anything to get this, it's already on your site at `/wp-json`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "get posts, the content" }
Want to create Child theme, but already edited Parent theme css files and some php files I downloaded a WP theme and edited some `php` files and the `css` file to my liking (trial and error), and have been using that on my website - but didn't create a child theme. This means any updates I do to the parent theme, will override my changes - so I've done no updates so far. Is it possible to create a child theme now, somehow keeping the newly edited `php` files and `css` file that I possess by putting them in my child theme folder, (creating some kind of pointer `css` file to have the child override the parent) and then updating the original parent? If so, how? Or should I just scrap the theme entirely, look for a new theme and create a child immediately out of that before I make any edits?
In case you have access to the original theme files you can compare them using a tool for that purpose such as this, then when you identify which are the modified files you load those files to your child theme. This way you only have the modified files on your child theme and it won't matter if any update happens after that. If you progress so far isn't that big or that important you can analyze to see which option is more time-consuming, doing this or starting over with a new theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, themes, css, child theme" }
register widget class not written in theme I have a widget located at `/child-theme/includes/custom-widget.php`. How do I call `register_widget` and reference that widget? I've tried something like the following inside `functions.php`: function SER_register_widgets() { register_widget( 'includes/custom-widget.php' ); } add_action( 'widgets_init', 'SER_register_widgets' ); but this does not work. Help appreciated.
include that file in your functions.php file like `require_once('includes/custom-widgets.php');` then you can call `add_action()` hook, in your case `add_action('widgets_init', 'SER_register_widgets'); .` the idea is to make that function ( ser_register_widgets ) visible in current php file ( functions.php file in this case )
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets" }
Check if a value exists in database table I have a custom self made registration form where a user needs to enter his address, I need to check if his address is already added in a custom table(which I have made manually with table prefix). I am using a custom function in my function.php file. function my_custom_action(){ $myinput = $_POST['address']; global $wpdb; $table_name = 'wp44_predefined_address'; $result = $wpdb->get_row("SELECT * FROM wp44_predefined_address WHERE 'UPPER(Address1)' LIKE 'UPPER(%s)'", $myinput); print_r ($result); die(); } All I am getting is a **Null** value in my console. I have converted the strings into Uppercase also, I have used quotes also. I have used LIKE, but I also used = , I am using `$wpdb->get_row` , I have also used , get_var or get_result. So what I am doing wrong ?
Replace this: $result = $wpdb->get_row("SELECT * FROM wp44_predefined_address WHERE 'UPPER(Address1)' LIKE 'UPPER(%s)'", $myinput); with this: (just choose the appropriate `$like` based on your requirements) // Properly generate the LIKE query. $like = '%' . $wpdb->esc_like( $myinput ) . '%'; // e.g. '%input%' //$like = '%' . $wpdb->esc_like( $myinput ); // e.g. '%input' //$like = $wpdb->esc_like( $myinput ) . '%'; // e.g. 'input%' $result = $wpdb->get_row("SELECT * FROM wp44_predefined_address WHERE Address1 LIKE %s", $like);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, ajax, database, select" }
Which header is served I am using theme (Knowledgedesk) that includes a header.php in its child theme's directory. However the changes I make by editing header.php are not visibles. It cannot be the cache, I already checked (and editing style.css works fine). Then, is there a way to determine which header.php is loaded (using browser network tab, access.log, etc.)?
Problem solved by using a plugin: which template file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "child theme, custom header" }
How to show scaled featured image in template? I need to show the post featured image at the desired position on my theme template. At the same time, I need its width to be 300px and the height- adaptive. What code should I add to my template?
You can create custom size image with `add_image_size()` in the functions.php function add_custom_size_images() { // Add image size width 300 with unlimited height. add_image_size( 'featured-image-300', 300 ); } add_action( 'after_setup_theme', 'add_custom_size_images' ); And in the template to get the size that you created with `the_post_thumbnail()` the_post_thumbnail( 'featured-image-300' ); **Notice:** If you want it to work with the old images that you uploaded already you need to regenarate the thumbnails. There are some plugins for this. Plugin for example <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, post thumbnails" }
global $post; in WooCommerce Is there a reason when using the `add_meta_box()` callback, that when I do `global $post` I can't seem to access anything, or get the ID. I'm in WooCommerce, do I need to use `global $product` instead... if so why? When I do `add_meta_box( 'supplier_package_box', __( 'Supplier', 'supplier' ), 'populate_meta_box' );` In my callback: function populate_meta_box(){ global $post print_r($post); echo '</br>'; `$post` is always empty... for context I want to check if a post meta exists so I can populate an input box if necessary. :)
You should avoid using global variables where possible. For metaboxes you should use the `$post` variable that is passed to the callback function instead: add_meta_box( 'supplier_package_box', __( 'Supplier', 'supplier' ), 'populate_meta_box' ); function populate_meta_box( $post ){ print_r($post); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic, metabox" }
Preventing double loading JS scripts (like React) when developing for Gutenberg Gutenberg is mostly made in JS, so I'm using `create-guten-block` to create some custom blocks. If multiple plugins use this to create blocks, is it a problem that these scripts get compiled and loaded for each plugin instance. Like React, being enqueued multiple times, doesn't it slow the page down?
Any WordPress-packaged scripts enqueued properly via `wp_enqueue_script` won't load multiple times. If two different plugins rely on the same dependencies, thanks to the enqueue logic, those dependencies will only be loaded once. `create-guten-block` only contains javascript relevant to the custom block itself, and sets `wp-blocks`, `wp-i18n`, and `wp-element` (the abstraction layer WP uses on top of React) as its dependencies. See /src/init.php of the generated block code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, javascript, block editor" }
Description is not showing in plugin page I've just uploaded my plugin in `WordPress repository`, everything is ok, the only thing is that Description is not showing in the plugin page I've checked `readme.txt` file and main .php file but everything seems to be ok. The plugin page is this, and it's been created a couple days ago
Try just with one paragraph: > With SmartLink DU you can insert up to 5 URLs to a single link. Every time the page is loaded, one of the 5 URLs you’ve entered will be inserted in the link randomly. The only "weird" thing that I saw was that you have multiple paragraphs and they were all together, if you put only one paragraph and it works you can try to add a line break between them. It's a pretty buggy think, you could report it on: `[email protected]`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Set tags for a post - without tag creation I can use `wp_set_post_tags` to set tags for a post. According to documentation, > Every tag that does not already exist will be automatically created I **don't** want to automatically create tag if tag does not exit? So is there any function can I use?
OK, so you have something like this: $new_tags = array( 'tag1', 'tag2', 'tag3' ); wp_set_post_tags( $post_ID, $new_tags ); If you want to add only tags that already exist, then you have to filter your tags array: $new_tags = array( 'tag1', 'tag2', 'tag3' ); $existing_tags = array(); foreach ( $new_tags as $t ) { if ( term_exists( $t, 'post_tag' ) ) { $existing_tags[] = $t; } } wp_set_post_tags( $post_ID, $existing_tags ); Or a shorter version: $new_tags = array( 'tag1', 'tag2', 'tag3' ); wp_set_post_tags( $post_ID, array_filter( $new_tags, 'tag_exists' ) );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "posts, tags" }
How to make the first letter of a post title uppercase, in a plugin? I'm making a plugin that makes the first letter of the first word in a post title uppercase, if it was lowercase. I'm a beginner, so it's simple, but even so I struggle! The plugin can be activated without errors but it doesn't have the desired effect. Here's the code: <?php //Changes the first letter of post titles to uppercase function shikharfirstletter() { $title = get_the_title(); $title_first_letter = substr($title, 0); if($title_first_letter = 'a') { return str_replace($title_first_letter, 'A', $title); } elseif($title_first_letter = 'b') { return str_replace($title_first_letter, 'B', $title); } //So on for the other letters... } add_filter( 'wp_title', 'shikharfirstletter' ); ?> Any idea where I'm going wrong?
As maverick said in the comments, you need to accept the arguments which come along with the filter. Try this function shikharfirstletter($title) { $title = ucfirst($title); return $title; } add_filter( 'wp_title', 'shikharfirstletter', 10, 1 ); <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, functions, title" }
WordPress front page empty, however, there is content on website I am trying to set a simple informative WordPress site. I installed a theme called " **Stacy** " and trying to edit the home page now. If I go to the `wp-admin -> pages -> Home -- Front Page` it seems to be empty, however, when I navigate to home page of my website or click or "preview changes" there is a full working home page already set. Beginner with WordPress and this is driving me insane now... **How can I edit the home page?**
I can't comment yet, so I'll have to put this as an answer :-) What do you see when you go to Settings / Reading, in the section that says "Your homepage displays"? If it is set to "Your latest posts", the home page will be aggregating your post content and won't be using a particular page. Another thing to check, when you go to the "Home -- Front Page", what is set under "Page Attributes" and "Templates" on the right hand side? If it is using a custom template, the content may all be coming from here?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, homepage" }
Add the "active" class only to the first loop item in a WordPress query I have a query as shown below: <?php $query = new WP_Query( $wpplnum ); while( $query->have_posts() ): $query->the_post(); ?> <div class="carousel-item col-md-4 active"> <div class="card"> <img class="card-img-top img-fluid" src=" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">Card 1</h4> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> </div> I want to add the `active` class only to the first loop item: **`class="carousel-item col-md-4 active"`** the remaining loop items will be without the `active` class: **`class="carousel-item col-md-4"`**
**I'd use the`current_post` property of the `WP_Query` class instance**, which in your case is the `$query`. So here I check if `$query->current_post` is greater than or equals to `1`: <div class="carousel-item col-md-4 <?php echo $query->current_post >= 1 ? '' : 'active'; ?>"> Resource: <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "wp query, loop" }
Wordpress archive permalink with leaf category Wordpress Category Archive permalinks set up with %category% include the full category tree. I want to see only the leaf category in the URL, not the full tree. Example: Wordpress Category: recipes > baking > bread current permalink for archive: domain.com/recipes/baking/bread desired permalink: domain.com/bread I've been searching the web without any idea how to hook or filter this change into my wordpress code, so any ideas and help is highly welcome. thanks Jan
After some searching I found the answer, in case someone else has a similar issue. The following code will leave only the deepest category in the archive permalink and will remove all parent categories. add_filter( 'category_link', 'wpse7807_category_link', 10, 2 ); function wpse7807_category_link( $catlink, $category_id ) { global $wp_rewrite; $catlink = $wp_rewrite->get_category_permastruct(); if ( empty( $catlink ) ) { $catlink = home_url('?cat=' . $category_id); } else { $category = &get_category( $category_id ); $category_nicename = $category->slug; $catlink = str_replace( '%category%', $category_nicename, $catlink ); $catlink = home_url( user_trailingslashit( $catlink, 'category' ) ); } return $catlink; } kudos to Changing the category permalink structure.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks" }
How disable some product features on woocomerce? My website is a product review website. I'm using woocomerce in order to store all products and let user be able to search them by category and attributes. Due this, I would like to remove some unnecessary options from my wordpress admin like inventory and shipping. .![enter image description here]( How can I disable those functions from my wordpress??
Just add below function in your function file /*For remove tab from product tab*/ function remove_linked_products($tabs){ unset($tabs['inventory']); unset($tabs['shipping']); return($tabs); } add_filter('woocommerce_product_data_tabs', 'remove_linked_products', 10, 1); /*Remove Virtual and Downloadeble checkbox*/ function remove_product_type_options( $options ) { unset( $options['virtual'] ); unset( $options['downloadable'] ); return $options; } add_filter( 'product_type_options', 'remove_product_type_options' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, wp admin" }
Add audio file to post using custom term meta field as link I am trying to add an audio file to my custom post type using a custom term meta field as a link, but I can't get it right. Here is how I would normally display a custom term meta field: <?php $terms = get_the_terms($post->ID, 'taxonomy-name'); foreach ($terms as $term) { $term_id = $term->term_id; echo get_term_meta( $term_id, 'term-meta-field-name', true ); }?> I'm assuming I have to turn it into a variable, but I'm not sure how. Any ideas? <?php echo do_shortcode([audio src="link"]); ?> Thanks!
I figured it out! Using this code I was able to use my custom meta field as the link in the audio shortcode. First I created a function in functions.php: function audio_link() { $terms = get_the_terms($post->ID, 'taxonomy-name'); $result = ""; if (is_array($terms) || is_object($terms)){ foreach ($terms as $term) { $term_id = $term->term_id; $result .= get_term_meta( $term_id, 'term-meta-field-name', true ); } } return $result; } Then I inserted the function into the shortcode like this: `<?php echo do_shortcode('[audio src="'. audio_link() .'"]');?>` Hope this helps anyone else with this problem!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, variables, audio" }
Pagination for custom php code This page (body only) is made completely in a custom php code, based on a custom type created by Pods module. I would like to know if there is any module that can help me insert a paging control directly inside my php code?
<?php $pod = pods( 'my_pod' ); $params = array( 'limit' => 15 ); $pod->find( $params ); // Advanced Pagination echo $pod->pagination( array( 'type' => 'advanced' ) ); // Simple Pagination echo $pod->pagination( array( 'type' => 'simple' ) ); // Paginate echo $pod->pagination( array( 'type' => 'paginate' ) ); ?> From Pods documentation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, php, pagination" }
Wordpress loading very slow on MAMP Pro I've just installed MAMP and MAMP Pro on my Mac system and my Wordpress install is running extremely slow on MAMP Pro (much slower than it would on a remote server). The actual content of the site is loading fast - it's only when I try to access any backend content that everything slows down to a crawl. Any input on the potential reasons for this?
The local web server being slow is something that bugs me as well. Some tips might help: I think it is all about the database. 1. Check that you connect to the correct MySQL port (8889 is default). Even though 3306 (MySQL default) might work, changing to the "correct" gave me a boost. 2. In addition, you can try to connect to 127.0.0.1 instead of localhost. You might need to check "Allow network access to MySQL" within the MAMP PRO MySQL config. These settings helped me, though I am not completely happy with the response time.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "localhost, local installation" }
Wordpress Baskerville 2 translation I don't understand how translation works in Wordpress. I made my first wordress using Baskerville 2 theme and I would like it to be translated in French. How does it work ?
It's quite well explained here: < Basically ensure that all plain text uses the get_text functions with a text domain for your theme: < Add code to 'Load' any translations < Once you have done that, IF translations exist they will be used. THEN to get the translations. This is also useful **< There are a number of tools/plugins available to actually provide the translated texts. See here for some: < Often the non-english users of a plugin or theme will voluntarily contribute a translation .po file to the developer. I used to like the 'wordpress-plugin-codestyling-localization' as easiest for people new to translating, but sadly it's been not that usable for a few years. I don't have a preferred tool at the moment for actually translating the texts, but googling indicates various ideas from others for alternatives if non of the tools in the link above suit you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, translation" }
omit / remove '<br>' from category list used this code and that did not worked for me. echo str_replace( "<br>", "", wp_list_categories(array('title_li' => false, 'style' => false))); what did I missed?
You can replace '<br>' with '' by setting **separator** value echo wp_list_categories(array('title_li' => false, 'style' => false, 'separator' => ''));
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins" }
Show weekly posts statistic in WordPress I create a table in the footer. I would like to show some statistics, like total posts, weekly posts, total posts of the specific category. I just echo total posts with `wp_count_posts()->publish;` What can I do for the other one?
You already have the total post, so in order to get the total post within the last week, it's better if you do this on your `functions.php` file: function get_posts_count_from_last_week($post_type ='post') { global $wpdb; $numposts = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) ". "FROM {$wpdb->posts} ". "WHERE ". "post_status='publish' ". "AND post_type= %s ". "AND post_date> %s", $post_type, date('Y-m-d H:i:s', strtotime('-168 hours')) ) ); return $numposts; } And then use it in the footer. <?php echo get_posts_count_from_last_week(); ?> To work with categories we could use WP_Query: $args = array( 'cat' => 4, 'post_type' => 'videos' ); $the_query = new WP_Query( $args ); echo $the_query->found_posts;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "count" }
How can I stop 'in use' message from intermittently blocking my wp_posts table? How can I stop the 'in use' message from intermittently occurring in **phpMyAdmin** `wp_posts` table? I have no warnings and no error messages prior, but when it happens to my `wp_posts` table, all my content is blocked from loading. A repair table always fixes it, but this is a temporary fix until it happens again.
If repairing the table fixes it, you can schedule a repair database as often as needed, I use a plugin called WP-DBManager, after installation go to **Database > DB Options** and find **Automatic Scheduling** , you will have to work on **Automatic Repairing Of DB** , I think every hour is ok, not so often but often enough.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, database, bug" }
Contact Form 7 - Give each checkbox a class? I'm using Contact Form 7 and have a group of checkboxes in my form. I want to give each checkbox a class. CF7 lets us add a class, but this only applies to the parent object. I want my custom class on the inner divs. I want to add a custom class because I am using Bootstrap 4, and I want to have 3 checkboxes per row (for example), by giving the class 'col-4'. ![Picture of html to help explain]( Am I missing something? Will I need to use javascript?
with jquery in footer.php jQuery(document).ready(function($){ $('.wpcft-form-control div.checkbox').addClass('col-4'); } or via css (you will have to adjust for various screen resolution and make some test) <style> .wpcft-form-control div.checkbox{width:33%;max-width:33%;float:left} </style> But I think you can create separate n separate checkboxes and wrap them in a <div class="col-4">[checkbox checkbox-x "option1"]</div> <div class="col-4">[checkbox checkbox-x "option2"]</div> <div class="col-4">[checkbox checkbox-x "option3"]</div> in the form editor
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "javascript, html, plugin contact form 7" }
problem to delete page I have a "page" or "post" that I can not find anywhere. I would like to delete it, but I can not find it anywhere. I have already looked at the list of posts and pages, and even the database. Follow the link on the page ... enter link description here
This is attachment, you can find it in the **Dashboard > Media** menu. which id is: 497, you can find it and delete it. As I can see in Inspect element this is image: < But in your template, I can see you have hidden these things via CSS. Hope you know how to delete it from Media.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "posts, pages" }
Clone Wordpress site from development server to live server I created a site in WordPress on my development server. Now, I want it to go live. I copied over all the files from the development server to the live server. Created a new database for WP with new user and changed the credentials in `wp-config.php` file. I have also changed the `siteurl` URL and `home` URL in the database table `wp_options`, however, still can't access the site giving me " **Page Load Timeout** ". What am I missing out?
You sure you follow the Codex advises when Moving your WordPress, from what you said, it's not clear to me if you export/import the database or just did the changes you mentioned.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "migration, staging, clone site" }
Add active class to wp_nav_menu I'm using this code but it's not working function special_nav_class($classes, $item){ if( in_array('current-menu-item', $classes) ){ $classes[] = 'active'; } return $classes; } add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2); Inspect Element: <li id="menu-item-106" class="d-inline-block menu-item menu-item-type- post_type menu-item-object-page current-menu-item page_item page-item-32 current_page_item menu-item-106 active"><a href="#">Something</a></li> Add active class but still it doesn't change the design still the same.
You wont need that PHP code to style links to the current page in your nav. WordPress adds a class (current-menu-item) by default on links to the current page. But WordPress does not style the link for you. That would be part of the theme. You can add a rule to the theme's CSS ( typically /wp-content/themes/your_theme/style.css ) to style the link differently. For example : li.current-menu-item a { color: pink; // or whatever }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation, walker" }
Possibility to login without password I'm creating a webapplication for users that are racing in a rally. I have the following data from the different racers: * Username * Password * Mobile phone * Email The problem is they never know their password. Is it possible for them to login without password? Maybe with a code on their mobile phone or .. ? (they will always login with mobile phone)
Yes you can, you can easily just ask for a user name and/or email or text/email them their OTP(one time password). This is becoming more popular on mobile apps that ask for just a phone number and text a code to enter for authentication. Examples < < For wordpress auth there are plugins already. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, login, wp login form, authentication" }
WP_Query Ignoring `post_type` parameter <?php $args = array( 'post_type'=>'weather_today', 'orderby'=>'ID', 'order'=>'ASC', 'posts_per_page'=>1 ); $query = new WP_Query($args); if ($query->have_posts()) { while ( have_posts() ) : the_post(); the_content(); endwhile; } wp_reset_postdata(); ?> Outputs a post content (`the_content()`) that is not of a `weather_today` type. Why is this? I checked my SQL, in `wp_posts` I only have _one_ post of `post_type = "weather_today"` and it's not the one being outputted. This query is up in my header... and I believe above any other custom queries. Furthermore, it seems the other params are respected, the post I am getting is only `1` and is that last _regular post_ by `ID`. So why is the `post_type`, the most important param in this query, being ignored?
Try this <?php $args = array( 'post_type'=>'weather_today', 'orderby'=>'ID', 'order'=>'ASC', 'posts_per_page'=>1 ); $query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post(); //loop endwhile; wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query" }
fusion builder missing from custom post editor I appreciate all help in advance. I am building a fairly customised website using Avada theme and BNE Flyouts. I need to be able to enable the Avada's Fusion Builder when editing flyouts, so it can be edited in drag and drop mode. I have tried enabling both for custom post types, but still when I go to edit the flyout, none of the wysiwyg editors show: < I checked in the database and I am certain that flyouts are actually stored as posts: < Question: \- Is there a way to enable fusion builder on every editor window that I open, whatever is the post type \- Can I force particular post type to open fusion builder on certain post type? How do I determine the post type name for functions.php?
i actually found a solution o plugins developer support page, but it will work with small modification for any other plugin: add_filter( 'register_post_type_args', function( $args, $post_type ) { if( 'bne_flyout' === $post_type ) { $args['public'] = true; } return $args; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, functions" }
Retrieving all data from repeater fields I have a custom field in WP called `what_we_do_textarea_two`. what_we_do_textarea_two is a simple repeater field which allows you to add another item to a list. `what_we_do_textarea_two` has a subfield called `list_item`: ![enter image description here]( Since this list may have x amount of listings, what is the best way to retrieve the data from that field? At the moment I have: $textareaTwo = get_sub_field("list_item"); if ($textareaTwo && count($textareaTwo)>0){ foreach ($textareaTwo as $textareaTwos){ $res = get_post($textareaTwos); echo'Test'.$res; } } But it doesn't display anything? At the moment I have two listings in the repeater, so it should show two listings? I imagine it'll be a `for loop` since I want all data from the list the be displayed, but unsure as to why mine doesn't work?
> Please use below code to get list item <?php // check if the repeater field has rows of data if( have_rows('what_we_do_textarea_two') ): // loop through the rows of data while ( have_rows('what_we_do_textarea_two') ) : the_row(); // display a sub field value the_sub_field('list_item'); endwhile; else : // no rows found endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php" }
add external project to web site wordpress on production I have a website in wordpress that I just migrated to an ubuntu server, what I need to do is add a project developed with laravel that will be the section to make purchases for example www.example.com/store. I have the doubt, I can create a file as a template page.php and from there add the index of my new project?
I haven't touch Laravel recently. I hope my idea will help you. First of all, in general you can't run Laravel app using of Wordpress's wheel because of differences of mechanism and structure for each one. Second, let's think that you have two domains and one points wp and another points laravel app. Then you can set redirect wp's /store page to laravel app's domain. Third, if you are an advanced laravel user, you might be able to point public folder of laravel app to your wp's store folder. But what's the benefit of this instead of using 2nd idea. Fourth, how about making web app and that uses Laravel's api? I suppose this will be good solution.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, customization" }
get gravity form ID from backend/wordpress admin I want to add a filter to a form submission like it is done here. add_action('gform_pre_submission_6', 'capitalize_fields_6'); function capitalize_fields_6($form){ // Code here } My question is, how do you get the form ID on the WP admin side? Where is the number 6 coming from to access the form in the action?
If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says "ID: 6".
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, actions, plugin gravity forms" }
WP_Query no posts with tax_query When I add a new WP_Query, everything works, but if I add a 'tax_query' with a taxonomy, it doesn't pull the posts. post_count would always be 0. $products = new WP_Query([ 'post_type' => 'post', 'tax_query' => [ [ 'taxonomy' => 'show_product_on_only_premium', 'field' => 'slug', 'terms' => 'yes', 'operator' => 'AND', ] ] ]); echo var_dump($products); I've played with the tax_query with different values and I've had no luck. This works on production but not locally and I can't figure out why. edit> my database has the taxonomy Please help! Thank you in advance!
I was able to get it to work by just avoiding post_type since I had no idea what it was. $products = new WP_Query( array( 'tax_query' => array( array( 'taxonomy' => 'show_product_on_only_premium', 'field' => 'slug', 'terms' => 'yes', ), ), ) ); I tried to do it again with another taxonomy and I was so frustrated that it was still giving me no posts but it worked in production. Well it turns out my database locally has count: 0 but in production has count: 7. _face palm_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query" }
display 100 products per page on product category page I need to display 100 product on product category page at once, if there are 100 available . Is there any specific function to do it. Thanks, Nimesh
> I need to display 100 product on product category page at once, if there are 100 available . What should happen if you dont have 100 Products? Or do you want to show just **all** products? Anyway, you can try changing the query parameters (specifically here the `posts_per_page` parameter) on product category pages only. You can use a WooCommerce hook to do this. add_action( 'woocommerce_product_query', 'my_custom_query_code' ); function my_custom_query_code( $query ){ // only on product category pages, no other archives if ( is_product_category() ) { $limit = '100'; // the number of products // set the new "posts_per_page" parameter $query->set( 'posts_per_page', $limit ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, woocommerce offtopic" }
Divi Blog Module Plugin and YOAST SEO "Primary Category" I am using the Divi Template and have YOAST SEO installed. YOAST SEO has the great feature to assign "Primary Categoy" should a post have more than one category. Now the Divi Blog Module offers that you can display post meta (which includes the category, author etc). But the moment I activate to display the category it displays all categories and not the YOAST Primary category. I went to Elegantthemes/DIVI if they have an idea how to solve it but they have apparently no idea. Does anyone here have a workaround for this?
Neither Divi nor YOAST are able to help. I ended up hardcoding the entire frontpage.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, plugin wp seo yoast" }
Deleting All tags except categories Wp database Please Is there any way to run an SQL code to delete all post tags in wordpress except categories via database. I want to run an sql code that will delete all my tags in wp, but not deleting my post category and posts assigned to those category.
delete from `wp_terms` where `term_id` in ( SELECT `term_id` FROM `wp_term_taxonomy` WHERE `taxonomy` = 'post_tag' ) and `term_id` not like 1 The above Code was exactly what I was looking for.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "categories, database, tags, sql" }
Delete all post meta except featured image Using SQL Please I just migrated my site and I found out that wp_postmeta consumes most of my cpu resources, Is the any Sql code to Delete all post meta except the featured image. I dont want to Use wp functions for this. Just need only phpmyadmin sql code. I have read this similar Post, But I need the sql code for it, not functions
I rewrote the function from the link in your question to SQL. Keep in mind that this script will also clear the page-templates assigned to the pages. Make a backup of the `wp_postmeta` table first. DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts p ON pm.post_id = p.id WHERE (p.post_type IN ('post', 'page') AND pm.meta_key <> '_thumbnail_id') OR (p.post_type = 'attachment' AND pm.meta_key <> '_wp_attached_file' AND pm.meta_key <> '_wp_attachment_metadata')
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "database, post thumbnails, post meta, mysql, phpmyadmin" }
Write automatic title at save_post (infinite loop) I want to write the post title with the content of a custom field `$sentence_number`, this way: add_action('save_post', function ($title, $post_id) { $post_type = get_post_type($post_id); if ($post_type == 'sentence') { $sentence_number = get_field('sentencia_no', $post_id); wp_update_post($post_id, [ 'post_title' => $sentence_number ]); } }, 10, 2); But I get this error: **Uncaught Error: Maximum function nesting level of '200' reached, aborting!** How should I do it for avoid the loop? Thank you.
There is a simple way, You need to use filter hook **wp_insert_post_data** So the code should be like add_filter( 'wp_insert_post_data', 'set_post_title_with_field_value' ); function set_post_title_with_field_value( $data ) { if ($data['post_type'] == 'sentence' ){ $sentence_number = get_field('sentencia_no', $data['ID']); $data['post_title'] = $sentence_number; } return $data; } You need to add this code into theme's functions.php. So try the code and let me know the result. Thanks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "actions, save post" }
Checking if a post with certain meta value exists How do I check whether a post with a certain meta value exists? For instance, check if a post exists with `_sku = 1`?
One way would be to use `get_posts` function: $posts_with_meta = get_posts( array( 'posts_per_page' => 1, // we only want to check if any exists, so don't need to get all of them 'meta_key' => '_sku', 'meta_value' => '1', 'fields' => 'ids', // we don't need it's content, etc. ) ); if ( count( $posts_with_meta ) ) { // they exist } Currently it will search for published posts. You can customize it to your needs, so you can search for different types of posts or for posts with different statuses.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, post meta" }
How many meta-query fields support WordPress search at a time? I am new developer. I want know How many meta-query fields support WordPress search at a time? I saw that its getting (500 time out) errors after nine fields.
There's no hard limit, but meta queries are very inefficient, and in my experience things start to slow down dramatically after 3 or 4, depending on what type of query they are exactly (`=`, `LIKE` etc.) For querying based on that many fields you should consider a custom table, rather than meta. Or taxonomies where appropriate for the type of data being used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "metabox, search, meta query" }
Proper way of minifiying java script files in wordpress theme 1. How can make sure that java script minification in wordpress does not create issues once it is done in theme development point of view? 2. Does wp-enqueque script order matter in minification process? Thanks
**Ad1.** Just after make minification, do some tests with development tools (F12 in FF) There is a console where you will see all errors, warning etc. If something went wrong, you'll see it < * * * **Ad2.** Hard to say because every case is different but sometimes it's matter. Which plugin do you use for that? For example in W3 Total Cache you have an option which let you make order of your scripts for minification
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "javascript, wp enqueue script" }
echo product id and product_item_key in cart How can i echo product id and product_item_key of each cart item instead of total count ? function iconic_cart_count_fragments( $fragments ) { $fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>'; return $fragments; } Thank You
Techno Deviser, probably by mistake, in the `foreach` loop set value to `$fragments['div.header-cart-count']` instead append it. Try this modification: function iconic_cart_count_fragments( $fragments ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $fragments['div.header-cart-count'] .= '<div class="header-cart-count">' .$cart_item_key.'<br><br>'. $cart_item['product_id']. '</div>'; } return $fragments; } Or: function iconic_cart_count_fragments( $fragments ) { $cart = WC()->cart->get_cart(); if (!empty($cart)) { foreach ( $cart as $cart_item_key => $cart_item ) $output .= $cart_item_key. ' - ' . $cart_item['product_id'] . '<br>'; $fragments['div.header-cart-count'] = '<div class="header-cart-count">' . $output . '</div>'; } return $fragments; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "woocommerce offtopic" }
Server technical information and first respond time for WordPress I made a wordpress theme, when I compare mine with another website (similar) mine is smaller Page size 1.1 MB Load time 5.05 s Requests 99 but their website is Page size 1.4 MB Requests 132 Load time 2.78 s my question is, how server types affect load time? because mine take about 3 seconds to reply, but their 171ms. what can I do as developer to reduce first respond time? < <
Make sure you run each Pingdom test a few times to average out results! The two things that will most likely account for your difference in results here are : * The power and other specification of the server - the faster site is https, so may be able to use http/2; the faster site may be compressing the pages; Is your site on a low-powered shared server? Is the faster site on a dedicated server? * The location of the server relative to your Pingdom test location - I don't know where the 2 tested sites are located, but it will be difficult to do a decent like-for-like test if they are on different continents and the Pingdom test doesn't reflect that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "performance, server load" }
multiple search forms and search results I have 5 custom post types in my website and i need to make a search form for each one to show only results from it. What should be in the search form to only show results from the custom post type which it came from? How do i redirect from each page to a specific page results? <form role="search" method="get" action="/"> <input type="hidden" id="cat" name="paints_buildings" /> <input type="text" size="16" name="s" placeholder="Search" /> <input type="submit" value="Go" /> </form>
If you only want to search a particular post type include a hidden field with the name `post_type` and the value set as the name of the post type you want to search: <form role="search" method="get" action="/"> <input type="text" name="s" placeholder="Search"> <input type="hidden" name="post_type" value="post_type_name"> <input type="submit" value="Go"> </form> Just replace `post_type_name` with the actual name of your post type. Now when you search the URL will look like this: And only return results from that post type.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, search" }
How to insert wp_users ->user login name to wp_terms when a new user registering? i need to insert wp_users -> user_login field to wp_terms name and slugs field,when a new user registering. my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp_terms table also,so i will get the usernames as terms. i stucked here .please suggest some solution for this
i got the solution for this add_action('user_register', function ($user_id) { $user_info = get_userdata($user_id); $user_name = $user_info->user_login; wp_insert_term($user_name, 'user1', array()); }, 10, 1);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query, custom taxonomy, taxonomy, wpdb" }
Store brute-force IP addresses How can I store IP addresses which try to brute-force the login section or to login too frequent too fast? I need to store all IPs, then use them in another application, sort of like a learning routine. **UPDATE #1:** Here's a scenario (pseudo-code): function my_wp_login_failed($username) { store($username); store($ipAddress); } add_action('wp_login_failed', 'my_wp_login_failed'); How can I do this for all attack vectors? **UPDATE #2:** I need IP addresses trying to access the site more than X times get blocked for at least Y time. The initial phase will simply store these IP addresses. **UPDATE #3:** I have found this plugin - < \- which might do the job. I will need to rewrite it in order to pass the IP information to a database or a flat file.
You can use `wp_login_failed` action for that purpose... It's called at the end of `wp_authenticate`, if user credentials were incorrect. function my_log_brute_force( $username ) { $ip_address = $_SERVER['REMOTE_ADDR']; // store that info somewhere file_put_contents( 'bf-log.txt', date('c') . "\t{$ip_address}\t{$username}\n", FILE_APPEND ); } add_action( 'wp_login_failed', 'my_log_brute_force' ); Also this article may be helpful: Getting real IP address in PHP
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "login, security, ip" }
How do I set the url to make an ajax request for a html document? I have a javacript file that uses ajax to load an html document, but WordPress changes the url. Is there a way to set the url so that WordPress doesn’t change it? var file = ‘test/file.html’; WordPress appends the file to `/wp-admin/` and sets the path to ` When I change the file path to ` WordPress still uses the ajaxurl global variables and sets the path to the `wp-admin` directory. Here's the code: return $.ajax({ type: 'get', dataType: 'html', url: file, success: function (resp) { alert(‘Success’); }, error: function (jqXHR) { alert('Error ‘); } });
Yes, there is such way: you should pass absolute path in there... Let's say your JS file is enqueued like this: wp_enqueue_script( 'my-script', 'path-to-js-file.js'... ); Then you should use `wp_localize_script` and pass the value in there: wp_localize_script( 'my-script', 'MyScriptData', array( 'ajax_url' => site_url('/test/file.html') ) ); Then you can access this value in your JS file this way: return $.ajax({ type: 'get', dataType: 'html', url: MyScriptData.ajax_url, // <-- here you get that value... success: function (resp) { alert(‘Success’); }, error: function (jqXHR) { alert('Error ‘); } }); ## BUT... **You should know, that you SHOULD process AJAX requests using proper actions and not with some external file. Here you can read more about dealing with AJAX in WordPress:AJAX in Plugins**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "ajax" }
how to get the assigned child term of the term's parent I've read multiple stacks on different ways of doing this, but I've yet to find something that solves my problem. I have a parent term "Web" and a child of that term "Web Development". The current code that I have outputs "WebWebDevelopment": <?php $id = get_the_ID(); $taxonomy = 'portfolio_categories'; $terms = get_the_terms($id, $taxonomy); if( $terms ): ?> <div class="project-terms"> <p><i class="fas fa-folder-open"></i> <?php if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) : foreach( $terms as $term) : echo $term->name; endforeach; endif; ?> </p> </div> <?php endif; ?> I only want "Web Development".
This should work <?php if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) : foreach( $terms as $term) : if ($term->parent != 0){ echo $term->name; } endforeach; endif; ?> In the loop of the terms it prints only terms that have a 'parent term' given by `$term->parent!=0` which means that the term is a child.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "taxonomy, terms" }
Auto save permalink setting page with the plugin activation To add my personal content into my own endpoint of woocommerce my account page, I need to click on save in permalink setting page.But I would like to avoid this by auto reload this settings.
You should use `flush_rewrite_rules` function for that. You have to remember, that this is expensive task, so you should not do it every time the site loads (many tutorials are making such mistake). Of course you can use it in your plugin activation hook: register_activation_hook( __FILE__, 'myplugin_flush_rewrites' ); function myplugin_flush_rewrites() { // call your rewrite rules registration function here (it should also be hooked into 'init') myplugin_custom_rewrite_rules_registration(); flush_rewrite_rules(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, permalinks, autosave" }
wp_delete_user with username `wp_delete_user()` function requires user ID and [optional] reassign ID if the content is to be reassigned to another user. All users' user names are also unique as WP doesn't allow duplicate user names. If I know username, is there no way with just one PHP/mysqli query I can delete the user instead of run one query to find ID of that user first and then tell wordpress to delete that user ?
There is no way to do this with only one query. But to be honest - deleting user takes more than one query itself... You shouldn’t use custom SQL for that, because there are many things you could break this way... Always use WP functions, if they exists (what if some plugin logs every deleted user, or what if some other action is needed, etc.) You can use `get_user_by` to achieve that. Here's the example: $user = get_user_by( 'login', 'john' ); if ( $user ) { // get_user_by can return false, if no such user exists wp_delete_user( $user->ID ); } The fields you can get user by are: `ID` | `slug` | `email` | `login`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "functions, users" }
Cross Sells are not being shown in Cart Page. Please Help! I'm using " Consulting Theme" on Wordpress but the problem is I've linked my product cross-sells but they're not showing up on Cart Page. Can anyone help me with what I need to do to show them up?
Please check below scenario. Review below path(Theme folder path) file themes/consulting/inc/woocommerce_configuration.php Hide this 5th line remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display' ); it's working fine. Review below screenshot <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, woocommerce offtopic" }
Trying to enqueue script - Nothing Happens I am trying to enqueuer a script after registering it but I am getting an error. This is the script: function _test() { console.log("Test"); } That's the PHP: function fsg_shortURL() { echo "Funtion Called"; wp_register_script('_test','/wp-content/themes/theme-child/js/test.js'); wp_enqueue_script('_test'); } add_shortcode( 'fsg', 'fsg_shortURL' ); The console's suppouse to log `Test` but nothing happens.. Thanks!
Simply you've to call the function to execute it: function _test() { console.log("Test"); } _test();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp enqueue script" }
get deepest Woocommerce Product Category on Archivepage I use Woocommerce in my theme and was wondering how to get the unique category, when checking terms. what I did so far: 1. I enabled the theme supprt `add_theme_support( 'woocommerce' );` in the functions php. 2. I created a folder woocommerce and a file archive-product.php 3. The file is reached for the url `example.com/product-category/categoryname1/ 4. I use this code to get the categroies from woocommerce products: `$terms = get_the_terms(get_the_ID(), 'product_cat');` The thing is, that I get more than one categroy. Namely all of the first product (post) in my product list (starting with letter "A.." and allocated for the two main and two subcategories). I would like to get only the `categoryname1` entry. What did I do wrong? Has this something to do with the special permalink configuration for the category-base?
On category archives (or any the archive for any taxonomy term) you can get the current term with `get_queried_object()`. If you just need the ID you can use `get_queried_object_id()`. If you want to output the name of the term, you can use `single_term_title()`. Keep in mind that archive-product.php will also be used for the Shop page, for all products, so make sure to check `is_product_category()` before using any of the above functions.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "woocommerce offtopic, categories" }
How to get previous 10 days post from a specific date - WP Query I want to know how to get previous 10 days post from a specific date, as I know that it can be done from current date as below $args = array( 'post_type' => 'post', 'date_query' => array( 'after' => '- 10 days' ) ); $query = new WP_Query( $args ); But I want posts previous 10 days post from a **specific date**. Is it possible ?
Yes, it is possible. You can pass full date as before and after params, so: $given_date_as_time = strtotime('2017-11-22 00:00:00'); $args = array( 'post_type' => 'post', 'date_query' => array( 'before' => date( 'c', $given_date_as_time ), 'after' => date('c', strtotime( '- 10 days', $given_date_as_time ) ), ), ); $query = new WP_Query( $args ); above query is also correct and will give you result you wanted.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "posts, wp query, query posts, get posts" }
Concatenate site_url and string doesn't work I'm trying to concatenate my **site_url** and a string, but it doesn't work. This is what I'm doing: $myurl = site_url(); var_dump($myurl); $url = "https" . $myurl . "/inbox/?fepaction=viewmessage&fep_id=" . $inserted_message->ID; var_dump($url); die; The output looks like this: > string(31) "//zgp.mydomain.be" string(78) "https:/inbox/?fepaction=viewmessage&fep_id=4813" As you can see it isn't merged. How can this be?
Without knowing exactly what you are trying to do, it seems you want to append query variables to the URL. WordPress has methods for handling that properly, without manual string concatenation. Look at the documentation for `add_query_arg()` for details: < You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array. Using a single key and value: add_query_arg( 'key', 'value', ' ); Would create ` Using an associative array: add_query_arg( array( 'key1' => 'value1', 'key2' => 'value2', ), ' ); This would create `
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, urls, site url, query string" }
Should I change wp-config for SSL? Should I change wp-config for SSL setting to change define('SITE_URL','< to define('SITE_URL','<
You better use a .htaccess file, where you force https with: RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ [L,R=301] The file goes in the root folder of your WP installation. If there is any, put this code on the beginning of the existing file. And you can then change the settings in the WP backend Settings, if neccessary.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp config, ssl" }
Why .widget-area is outside of .site-content in Underscores starter theme? The Underscores starter theme offers a specific HTML structure: div.site header#masthead.site-header div#content.site-content div#primary.content-area main#main.site-main /* Here goes either article or archive content */ aside#secondary.widget-area section.widget /* Multiple widgets */ footer#colophon.site-footer The `aside#secondary.widget-area` seems to be out of place. Looks like it should be inside of `div#content.site-content`, as a sibling of `div#primary.content-area`. Is there a specific reason why Underscores theme HTML is structured this particular way?
The `.widget-area` actually **IS** inside `.site-content`. For anyone wondering why `.content-area` has a `<main>` child-element, rather than being the `<main>` element itself, here is the explanation: It allows for CSS styling while preserving HTML5 semantics. Namely it allows for easier negative margin management as well as background and other styling (full explanation here).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, html" }
URL rewrite with external JSON query I wrote a plugin that can fetch data from an external JSON source and displays a very few details in a list. Each item is clickable to be displayed with more details on a specific template. To do this, each item has its own URL like this : < The get parameter is meant to retrieve more data from the JSON source thanks to query_vars. It works without a hitch but I would like URLs to be rewrote this way : < Is that possible ? How can I do this ? (I can pass as many get parameters as possible from the list page if needed)
You can try URL rewriting like that add_action("wp_loaded", function () { add_rewrite_tag("%id%", "([^&]+)"); add_rewrite_rule( '^details/[^&]+/([0-9]+)/?', 'index.php?id=$matches[1]&pagename=details', 'top' ); }); And then flush rewrite rules cache one time in Settings -> Permalinks. With this rewriting, the identifier is no more in `$_GET` but you can get it with <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, url rewriting, rewrite rules, json" }
The plugin jetpack/jetpack.php has been deactivated due to an error: Plugin file does not exist When try to install the latest JetPack plugin, I got below error: The plugin jetpack/jetpack.php has been deactivated due to an error: Plugin file does not exist. Tried many times to install but same result.
After consideration, I decided to take backup of **wp-content/plugins/jetpack** and then delete **jetpack** folder, after that I installed the latest version with out any problem. I hope this will help you. For more information please check
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin jetpack" }
Install/Enable/Activate plugin on multisite without access to master site I have inherited a WP multisite without the access to the main site (network admin). I need to install a plugin and have unpacked it via FTP but need to enable it and can't. Any way of doing this via MySQL?
There's an option in the wp_sitemeta table with meta_key 'menu_items' ![enter image description here]( this value is referred to the checkbox "Administration menu" of the page /wp-admin/network/settings.php (accessible only to siteadmins) that allows the activation of plugins on single sites. ![enter image description here]( I've not tested but using the value `a:1:{s:7:"plugins";s:1:"1";}` and having the plugin uploaded via ftp you should see the plugin page on the site you've access to..
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, multisite" }
Change text size and color for tags and category meta description on product page how can I change text size and color for SKU, tags, and category meta description on the product page? It's too big and bright. Takes too much place especially in the mobile version. Thanks! ![enter image description here](
If you want all of the product meta to be styled in the same way, then add the following to your theme custom CSS or style.css in your child theme, and edit as required... .product_meta { padding-top: 6px; border-top: 1px solid #dadada; color: #666; font-size: 18px; } If you want something different for each of the product meta elements, then you would add something like the following... .sku_wrapper { padding-top: 6px; border-top: 1px solid #dadada; color: #666; font-size: 18px; } and .posted_in { padding-top: 6px; border-top: 1px solid #dadada; color: #666; font-size: 18px; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "page template" }
How to add taxonomy term under the thumbnail on woocommerce product page I have created a taxonomy names "status" for woocommerce product post type, I want to display the terms under the thumbnail on the main products page. I'd appreciate if anyone can help me to achieve this.
I have override template system in woocommerce and apply my script in loop --> price.php. the script goes above the price tag.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, taxonomy" }
Why won't my scripts load? I am having trouble loading scripts in functions.php I've done this before so I'm sure I'm overlooking something but as far as I can tell it is correct and I have tried copying and pasting from other answers. I am not getting any console errors. None of my scripts are loading in the source at all. Help is appreciated. **functions.php** /*SCRIPTS*/ add_action( 'wp_enqueue_scripts', 'theme_js' ); function theme_js(){ wp_register_script( 'bootstrap_min_js', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '', true ); wp_enqueue_script( 'bootstrap_min_js' ); }
I was missing the `<?php wp_footer(); ?>` call at the end of the footer.php file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, javascript, wp enqueue script, scripts, wp register script" }
Load JS Script only for custom post types I am using this code and I am not sure why the script is not loaded. I believe the syntax is correct since I am trying to load the script only on the "events" custom post type single posts. add_action( 'login_enqueue_scripts', 'wpse_login_enqueue_scripts', 10 ); function wpse_login_enqueue_scripts() { if( is_single() && get_post_type()=='events' ){ wp_enqueue_script( 'bootstrap', ' array('jquery'), '3.3.5', true ); } }
To enqueue scripts on the front-end, the hook should be `wp_enqueue_scripts`, not `login_enqueue_scripts`. Also, a better way to see if you’re on a single custom post type is to use `is_singular()` and pass the post type you want to check: if ( is_singular( 'events' ) ) { } `get_post_type()` relies on the global `$post` object, and not the main query. They're often the same but under some circumstances the `$post` object might not be the same post as the current single post.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, wp enqueue script" }
disable a wp javascript on live website, but not on wp-admin page I have a wp javascript, **wp-embed.min.js** , disabled on my WordPress theme by adding this sample code to my theme's function.php file: add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 ); function my_deregister_javascript() { wp_deregister_script( 'wp-embed' ); } The problem is that the javascript is disabled everywhere, including in the wp-admin page, and one of the plugins I want to use requires it to work. Is there a way to disable a specific wordpress javascript only on the live website, but not on wp-admin pages? Thanks
You can do a simple is_admin() check before dequeuing your script like below: **Code** : add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 ); function my_deregister_javascript() { if ( !is_admin() ) wp_deregister_script( 'wp-embed' ); } }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp admin, javascript" }
How to delete default themes Is it possible to delete the default Themes (Twenty Eleven, Twenty Twelve, Twenty Thirteen …) automatically … or - even better - disable the automatic re-installation on when updating WordPress? I've read this question and i know that many consider it useful to have at least on of this themes. But i never used one of these and just want them gone ;)
My approach is to delete the default themes using ftp or your control panel file-manager once you have your site up and running. These themes will not be re-installed when you update Wordpress, and will not show up in your update notifications. I usually **keep the TwentySixteen theme** on the system as this is the fallback theme in case you have problems with your installed theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "themes, customization, theme twenty seventeen" }
WooCommerce HTML after short description if product is in specific category I want to show HTML text after the short description on the product page, but only on specific products that are in a specific category (categories). I think I have to use in_category, but I can't figure out how to display the text right after the short description. My preference is to work with a function/filter/action. This code works: function filter_woocommerce_short_description( $post_excerpt ) { $your_msg='Test'; return $post_excerpt.'<br>'.$your_msg; }; add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 ); But this one works on all product pages..
Woocommerce's product categories are custom taxonomy terms, so you need to use the taxonomy functions (eg, `has_term()`) rather than WordPress' category ones. function filter_woocommerce_short_description( $post_excerpt ) { global $post; if ( has_term( "term-name", "product_cat", $post->ID ) ) { $post_excerpt .= "<br/>" . "Test"; } return $post_excerpt; }; add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "woocommerce offtopic" }
Check what Gutenberg blocks are in post_content I'm working on a design that has different styling if a certain Gutenberg block is present on a page. In other words, if the first block is a custom built Gutenberg block, the post_title is rendered elsewhere due to design choices made. Is there any function in WordPress to get a list of all Gutenberg blocks present in the post_content?
WordPress 5.0+ has a function for this: `parse_blocks()`. To see if the first block in the post is the Heading block, you'd do this: $post = get_post(); if ( has_blocks( $post->post_content ) ) { $blocks = parse_blocks( $post->post_content ); if ( $blocks[0]['blockName'] === 'core/heading' ) { } }
stackexchange-wordpress
{ "answer_score": 42, "question_score": 30, "tags": "post content, block editor" }
Add multiple tags to multiple posts I have an array of posts IDs like this: `$id_post_array_full=array(239,243,246,248,250,252,255,257)` I would like to add tags for each posts with this function of wordpress `wp_set_post_tags()`. My real problem is that I have multiple arrays of tags and for each of them I have to match with the array of posts IDs In the first red column I have the IDs and in the second red column I have the tags that I have to add for each one. **I was thinking about that:link** Thanks for your time
I found the solution: My array of IDs + tags is like this: $array_tags_and_ids = [ '239' => ["car", "animal", "dog", "cat"], '243' => ["dsa", "ewr", "bvc", "fgn"] ]; So I do: foreach ($array_tags_and_ids as $key => $value) { // re-call the value and get only the text value $implode_tags_names = implode( ', ', $value ); // wordpress function wp_set_post_tags( $key, $implode_tags_names, true ); } Done
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, tags, array" }
How to export post 2 posts Wordpress plugin data I have an old website which uses the post 2 posts plugin (< The plug in has been used to set up many relationships between custom post types. However I am now in the process of creating a new version of this website from scratch. I therefore have exported and imported all posts, custom posts and ACF data. However the export / import did not include the relationship data of each post. My question is how can I export the post relationship data that was created using "post 2 posts" from the old site to new site?
The plugins use 2 custom tables to store relations datas : < Then if the plugin has not foreseen a export functionality, you have to retrieve the tables.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin development, import, export, bulk import" }
in_category() not working in WordPress 4.9.7 I have the following code in a template that used to work until I upgraded to Wordpress 4.9.7 if (in_category( 'vid' )) { $vidliclass = ' class="vid"'; } else { $vidliclass = ''; } Since the upgrade, posts that are in category vid don't return true anymore. I used the following code, to check on the category names of the posts: $postcat = get_the_category( $post->ID ); if ( ! empty( $postcat ) ) { echo esc_html( $postcat[0]->name ); } And the posts that are in category "vid" are echoed as vid. I also tried to replace "vid" with the category ID. Can I replace `in_category()` with something else to check if the post is in category "vid"?
You're using `in_category()` outside of a loop, so you need to pass the post ID in as the 2nd argument. eg, `if (in_category( 'vid', $post->ID )) {` See Codex.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "categories" }
Prevent WordPress automatically processing certain URL queries I'm coding a custom plugin for a client and I want to use certain `$_GET` variables in the URL in my custom pages, such as `?s=$1`, `?p=$1` and `?paged=$1`. With some of these variables, such as `?paged=$1`, it redirects me to another URL: `[PAGE_URL]/page/$1`. Are there any filter or action hooks that I can use to remove these functionalities for particular pages?
You should find alternatives, as noted on the codex article of "Reserved Terms" in WordPress (emphasis mine): > There is a complete set of reserved keywords, or terms, in WordPress that should not be used in certain circumstances as they may conflict with core functionality. **You should avoid using any of these terms when** : > > * **Passing a term through a $_GET or $_POST array** > * Registering a taxonomy or post type slug > * Handling query variables > You could use `?search=` in place of `?s=` and `?pg=` in place of `?page=` for example. Or, depending on what exactly you're doing, you could create a custom rewrite rule with `add_rewrite_rule()` and then you could name the underlying query vars whatever you wanted.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, wp query, query" }
How to get posts on a specific date - WP Query I want to get posts of a specific date, I tried the following code but I did not get the result what I wanted. <?php $mil = 1532996880000; $seconds = $mil / 1000; $dt = date( "Y-m-d", $seconds ); $post_by_date = $wpdb->get_row(" SELECT * FROM {$wpdb->posts} WHERE post_date = $dt AND post_status = 'publish' "); **WP QUERY** $posts = get_posts(array( 'post_type' => 'post', 'date' => $dt, 'posts_per_page' => 1 )); * * * This did not work because, the output of `$dt = 2018-07-31`, but the output shows no results. Because it compares with `2018-07-31 09:09:40`. So is there any way to get posts of a specific date?
<?php // primarily get $year, $month and $day $args = array( 'date_query' => array( 'year' => $year, 'month' => $month, 'day' => $day, ) ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { // do whatever here } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, mysql" }
using wp_sprintf at wordpress option page, I'm using a custom option page to control default setting of my plugin, in one part I need to let the admin add a text which will be send through sms, I need using some predefined text (such as blogname) in this text something like : wp_sprintf(__('This is the smaple sms from %s', 'my_plugin_textdomain'), esc_attr( get_option('blogname'))); how could I do this? Is it even possible to perform such action using wp_option, I know many plugins such as woocommerce using this kind of saving text
When it comes to user-defined strings, it's best to use a placeholder or "merge tag" - so on your settings page, inform the user they can use e.g. `{blogname}` And then in your code: $message = get_option( 'option_name' ); $message = str_replace( '{blogname}', get_bloginfo( 'name' ) ); This is less error prone & clearer to the user than using `sprintf` style arguments.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp admin, options" }
Adding custom html/css/images to Theme I have a small header-of-sorts that's in a html file, with its own css file and a folder of images (svgs). I'm basically trying to put this on my site in the header, so I made a child theme and went to edit that theme's header.php with my html code, linking to the css file (which I added to the theme), and with the folder of svgs in the theme files as well. The svgs don't appear and neither is any of the styling though the html itself shows up fine. I even moved the css into my styles.css for the child theme and it doesn't make a difference. I'm basically wondering what the easiest way is to incorporate my code/file structure (html file, css file, folder of svgs). I can include code if it's relevant, but I figured right now my question is more of a general, how-to-approach-this-issue kind of question.
If your HTML is displaying but the images aren't that normally points to a path issue - doublecheck it by opening your browser's dev tools and checking whether the requested path to the images is correct. Make sure you're using `get_stylesheet_directory_uri()` to get the URI to the root of the child theme, as `get_template_directory_uri()` will point to the parent theme even when used in a child theme's template.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, themes, css, child theme, headers" }
Replace standard Login and Register form for Woocommerce When non-logged users click on "my-account" they see standard woocommerce login and register forms. I have a [short_code] of new login form. Is there any way to replace or redirect standard login and register forms which are a part of [woocommerce_my_account] with my [short_code] My new form is also combines both register and login. So, I need replace both login and register forms and use a new one instead. Thanks!
You can override pretty much every WooCommerce template by copying them into a folder named "woocommerce" in your theme. This is documented at Template structure & Overriding templates via a theme. The login and register forms non-logged in users see when they click "my account" are genetared by the template file `/myaccount/form-login.php` So what you need to do is copy this file from the directory to your theme's directory (so it is `/yourtheme/woocommerce/myaccount/form-login.php`) and from there edit it as desired
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp login form" }
Page content dissapears after loading the page All my pages work fine except those that are superior pages. After clicking the name of the page in the menu and loading the page the content shows itself for like a second and then it dissapears. Here. Every other page works. I am using the Avada theme.
Disable ConvertPlug plugin, for some unknown reason, it's adding `display: none;` to your content.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization, errors" }
Multiple arrays in post__not_in parameter Does the post__not_in parameter can have multiple arrays for excluding, for example, sticky posts and also the IDs of some other posts? Something like: 'post__not_in' => array( get_option( 'sticky_posts' ), array( 1, 2, 3 ) )
No, it doesn't. You'd just merge the arrays: 'post__not_in' => array( array_merge( get_option( 'sticky_posts' ), array( 1, 2, 3 ) ), ) And just because someone else will mention it if I don't: `post__not_in` has terrible performance and you'd be better off finding an alternate solution.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "exclude" }
Add option for editors through `register_setting` I want to add some options in wordpress admin panel which editors also can update through a form. I have used `register_setting()` function to add those options. For administrator this works fine, but for editors i get message `Sorry, you are not allowed to manage these options.`. Is there a way so editors can also edit these new options?
To allow users with capabilities other than `manage_options` to save a setting you can use the `option_page_capability_{$option_page}` hook. Despite the name, `{$option_page}` is the option _group_ , which is what you set for the first argument of `register_setting()` and `settings_fields()` on your options page. So if you registered a setting: register_setting( 'wpse_310606_setting_group', 'wpse_310606_setting' ); You can allow other capabilities to save it with: function wpse_310606_setting_capability( $capability ) { return 'edit_pages'; } add_filter( 'option_page_capability_wpse_310606_setting_group', 'wpse_310606_setting_capability' ); Editors and Administrators both have the `edit_pages` capability, so this would allow both roles to save this settings group.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "editor, options" }
Auto Submit Contact Form 7 I’m looking for solution whole day but can’t find anything that work. So I want to automaticaly submit CF7 on page load. If I use any jQuery or JS solution there is some endless looping on the site. So any solution for my problem? Thanks in advance
You need to call **submit()** function on **document ready** check the code <script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#wpcf7-f3857-o1 form").submit(); }); </script> In my code **wpcf7-f3857-o1** is the contact form's css id. You need to change that id. try the code and let me know the result. Thanks
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms, plugin contact form 7" }
wp-login.php entering password nothing happens I have a website prettypeople.nl and whenever I try to login as an admin whether at /wp-admin or /wp-login and input the correct credentials, nothing happens! The page refreshes and if I check the logs I cant find anything! What can I do? Link changes from `prettypeople.nl/wp-login` to: It authenticates the password credentials and wants to redirect me to the correct page, but doesn't.
Link ` redirects to According to me, the link should end like this: ?redirect_to= Check `siteurl` and `home` options in `{wp_}options` table and rewrite rules in `.htaccess` file .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, login" }
Missing privacy policy checkbox on login page (using Enfold theme) I have strange behavior as of late. Whenever I need to log in again on my site (< I get the following error message: "You must acknowledge and agree to the privacy policy". The weird thing is, I don't have this checkbox! I can't even find it as a shortcode. When I check the class of the message I see it's from WPUM (WordPress User Manager,i.e., _wpum-message error_ ) ![enter image description here]( Even weirder is that I **do** have it on the wp-login.php page: ![enter image description here]( When I check the code of this form, I see the name of the checkbox, i.e., _comment-form-av-privatepolicy_. So it does exist but **How do I solve this discrepancy?**
So after doing some investigating myself a couple of weeks ago, I found out that it's mainly due to Enfold. There was a conflict between Enfold and the WPUAM plugin. After disabling the checkbox through Enfold the issue disappeared. It seems like Enfold adds the checkbox to ANY login screen.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, login" }