INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Remove rel=shortlink from HTTP header HTTP header of posts on my site looks like this: accept-ranges:bytes cache-control:public, max-age=0,public,public content-encoding:gzip content-length:5369 content-type:text/html; charset=UTF-8 date:Fri, 08 Dec 2017 07:27:40 GMT expires:Fri, 08 Dec 2017 07:19:33 GMT link:< rel=shortlink server:Apache status:200 vary:Accept-Encoding How to remove this line from HTTP header responce: link:< rel=shortlink _Please, do not confuse this with`<head> </head>` section of HTML, I removed it from there already, I would like to remove it from HTTP header response too._
<?php add_filter('after_setup_theme', 'remove_redundant_shortlink'); function remove_redundant_shortlink() { // remove HTML meta tag // <link rel='shortlink' href=' /> remove_action('wp_head', 'wp_shortlink_wp_head', 10); // remove HTTP header // Link: < rel=shortlink remove_action( 'template_redirect', 'wp_shortlink_header', 11); } Tested in WordPress 4.4 and up to 4.9.1
stackexchange-wordpress
{ "answer_score": 12, "question_score": 2, "tags": "headers, http" }
How to change the link of product menu from wordpress admin panel I am using Woo-Commerce and after activating it a new tab appears with name product I want to change the link of that product tab like if anyone click on that button it will be redirected to the front side add product link instead of Woo-commerce add product page can some one please help me. ![Image will eloborate what I am trying to say](
You can modify the admin navigation using the `$menu` global var. The following will accomplish what you're after add_action( 'admin_menu', 'my_plugin_edit_admin_menu'); function my_plugin_edit_admin_menu() { global $menu, $submenu; foreach ($menu as $menuKey => $menuItem) if ($menuItem[0] == 'Products') $menu[$menuKey][2] = ' // wtv link you want // UPDATE: // remove the sub menu as well (note the GLOBAL var define above) $submenu['edit.php?post_type=product'] = ''; unset($submenu['edit.php?post_type=product']); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Template hierarchy override One of the best way to override the default template hierarchy is to use the child theme and copy and paste the template file (from parent theme to the child theme) you want to override and change the code of the template file according to your need (to display the content on the template page). The other way is to use filter ( `add_filter( 'template_include' , 'custom_template' , priority_value );`) to bypass the predefined structure of template hierarchy. Can any body explain how the second method works in detail?
To understand how this works, take a look at the source file `template-loader.php`. Here you see several lines of statements which determine which template WordPress will load. Near the end is the filter, which allows you to undo all the previous lines. For instance, one of the lines determines which template to load if `is_single` is true. You could use the filter to add extra conditions, for instance to load a different template if `is_single` is true and the post is in a certain category. Beware, this still means you would need to have a template file in your child theme (where you also have the filter in `fucntions.php`). Basically, for all templates that WordPress can find through the conventional naming of the template hierarchy, it doesn't make sense to use the filter. You would only use it if very specific conditions apply under which the template must be called.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "template hierarchy" }
How to use add_action('wp_ajax_[action name]',...) for a specific page with condition? In my plugin, I'm using wp_ajax, This hook does not work when I wrap the init function call with a condition like this : public function __construct(){ if( isset( $_GET["page"] ) && $_GET["page"] === 'edit-foo' ){ <-- This line prevents the call 'wp_ajax_foo' ! add_action( 'admin_init', array($this, 'init') ); } } init(){ ... <- initalize $this->editable_item->item add_action('wp_ajax_foo',array( $this->editable_item->item, 'foo' ) ); }
As foo is a static function you don't need to specify the object, so you can use it outside the condition to correctly load it like this : public function __construct(){ if( isset( $_GET["page"] ) && $_GET["page"] === 'edit-foo' ){ add_action( 'admin_init', array($this, 'init') ); } add_action('wp_ajax_foo',array( 'MyPlugin/Classes/MyClassWithFooFunction', 'foo' ) ); } init(){ ... <- initalize $this->editable_item->item }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, init" }
Switch position of elements in the footer I am new to Wordpress and I was wondering is there a possibility to customize a theme I got, to my desires. My footer has two content areas, one for the copyright content and one for the social links. The copyright content is on the left side, the social links on the right. I wish to change the copyright to the right and the social links to the left. I was trying to change the php files so the social icons will be included first and then the copyright section. But now I am stuck. Where can I just switch the php includes for this 2 items. Could anyone please advice
You can solve this by using Flexbox. Add the following CSS code somewhere in your theme stylesheet or via dashboard `Appearance > Customize > Additional CSS` .fusion-copyright-content { display: flex !important; flex-direction: row-reverse !important; } .fusion-copyright-content .fusion-social-links-footer { margin-right: auto !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, html, footer" }
Delete all users meta that named: user_avatar I want a code like this: UPDATE `jnkdadb7a_usermeta` SET `meta_key`='x1' WHERE (`meta_key` = 'x2'); I want a SQL command to search inside jnkdadb7a_usermeta table for meta_key (X) and delete it.
Is this what you are looking for? DELETE FROM jnkdadb7a_usermeta WHERE meta_key='X';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql, sql" }
How to Create a Multi Purpose Theme? I keep Seeing the new themes on themeforest comes with multiple layouts i mean they are multipurpose theme. how can i create a multipurpose theme having 7 different layouts, how could i connect them what are the functions??
The way I do it is create multiple layout files, add the option to choose which one to use on the template options panel: layout-left.php layout-right.php layout-both.php Then on the index page you setup if layout X is chosen, load X layout. This is an example using the option tree plugin theme options: <?php get_header(); ?> <?php if( get_option_tree( 'mz_layout' ) == 'right') { ?> <?php get_template_part( 'layout', 'right' ); ?> <?php } else if( get_option_tree( 'mz_layout' ) == 'two') { ?> <?php get_template_part( 'layout', 'two' ); ?> <?php } else if( get_option_tree( 'mz_layout' ) == 'left') { ?> <?php get_template_part( 'layout', 'left' ); }?> <?php get_footer(); ?> I'm sure there are other methods, but this should give you an idea.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "theme development, themes" }
After changing Site url to https, can't access login page I changed url from http to https from WP Settings. After refreshing I can't access wp-login page. It says site can't be reached or too many redirects. I have cloudlare SSL enabled. I am on VPS hosting. Thanks
I had the same problem. You need to install the plugin CloudFlare Flexible SSL < As you can't login in to dashboard so you can't add that plugin now. But there is a way for this. Just login to cpanel or just use ftp. Then createa folder inside wp-content named mu-plugins . Now download that plugin and upload all files of that plugin in mu-plugins folder. Make sure there is no folder inside mu-plugins folder. Just upload the plugin files to mu-plugins. Then this plugin will be active automatically and your problem will be solved right away. Hope this helps
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp admin" }
Failing in_category or has_category in the_content_feed I'm attempting to test post category within RSS output, however both in_category() or has_category() functions will fail. Testing category "manually" will work. What am I missing? add_filter( "the_content_feed", "RSS_my_filter" ); function RSS_my_filter($content){ global $post; if (has_category('Class Blog', $post-ID)){ // FAILS!!!! $content = '***************'; } $categories_list = get_the_category( $post->ID ); foreach ($categories_list as $category) { if($category->name == 'Class Blog'){ // WORKS $content = '***************'; } } return $content; }
`$post-ID` is not the same as `$post->ID`. You’re using the former for `has_category()`, but the latter for `get_the_category()`. `$post->ID` is correct.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, rss" }
Add link to parent page in list of child pages I try to add link to parent page to a working list of childpages. The parent page must be the first item's list whenever the list appear. Here is the actual code found here : //* List child pages [jla_childpages] function jla_list_child_pages() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = '<ul id="childpages-menu">' . $childpages . '</ul>'; } return $string; } add_shortcode('jla_childpages', 'jla_list_child_pages'); Anyone has an idea how I can transform this to add parent page to be the list first item whenever the list is shown ? Thanks !
you would add something like //* List child pages [jla_childpages] function jla_list_child_pages() { global $post; $parentID = ( is_page() && $post->post_parent ) ? $post->post_parent : $post->ID; $parentPost = get_post($parentID); $isParentCurrent = (get_the_ID() == $parentID) ? " current_page_item" : ''; $parent = "<li class='page_item page-item-{$parentID}{$isParentCurrent}'><a href='".get_permalink( $parentID )."'>{$parentPost->post_title}</a></li>"; $childpages = wp_list_pages( "sort_column=menu_order&title_li=&child_of={$parentID}&echo=0" ); if ( $childpages ) return '<ul id="childpages-menu">' . $parent . $childpages . '</ul>'; } add_shortcode('jla_childpages', 'jla_list_child_pages'); I haven't tested it, but all you're doing is figuring out the parent before everything, and including the parent above the children in the return.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child pages" }
Clean Custom URL for Serach + Custom Taxonomy I have a custom taxonomy, called `filter`. All of the following urls lead to the `archive.php` and should give me at least 1 post. * `/filter/bar` works by default, no custom rule needed * `/myCategory/filter/bar` works with my own custom rule, nice! * `/search/foo` works by my custom rule * `/?s=foo&filter=bar` works as expected * **`/search/foo/filter/bar`** **BOOM!** No entries Here are my rules: add_filter("rewrite_rules_array", function($rules) { $newRules = array(); // ... more rules $newRules["search/(.+)/?$"] = 'index.php?s=$matches[1]'; $newRules["search/(.*)/filter/(.*)/?$"] = 'index.php?s=$matches[1]&filter=$matches[2]'; $merged = array_merge($newRules, $rules); return $merged; }); * * * **EDIT** Query-Monitor for the desired URL (suche = search in german) ![enter image description here](
With Slam's kind tip to use query-monitor plugin, I could figure out what the problem was. Apparently the url `/search/foo/filter/bar` also fits the "general search" rewrite-rule. Makes sense, thinking about it– `(.+)` technically matches `/foo/filter/bar` aswell. So I could improve `(.+)` by excluding `/`s? But I found an easier solution! In hope "first match wins" I declared the more specific rule before the general rule– and e voila, it worked! add_filter("rewrite_rules_array", function($rules) { $newRules = array(); // more specific rule first $newRules["search/(.*)/filter/(.*)/?$"] = 'index.php?s=$matches[1]&filter=$matches[2]'; // general rule later $newRules["search/(.+)/?$"] = 'index.php?s=$matches[1]'; $merged = array_merge($newRules, $rules); return $merged; });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, url rewriting, search, urls" }
Full search and replace isn't enough to make all pictures to be loaded with https What else should be done if I went to my sites dir in Linux and ran this command: sudo wp search-replace ' ' --all-tables && wp cache flush and still, some images are loaded as http and not https. ?
In this site I use Elementor. I solved it by going to WP-admin > Elementor > Tools > Change address, and there I've changed all http:// to https:// as well. Then the problem solved. I admit I have no idea why the WPCLI search and replace operation didn't cover Elementor tables as well.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, javascript, https, wp cli" }
Specify custom php.ini to use with WP-CLI I have a Linux crontab that runs a bash script. In the bash script, it executes a few wp-cli commands. I want to apply a custom php.ini file when wp-cli runs to ensure timeouts are not an issue. Is there a setting/method that allows you to set a custom php.ini to use with wp-cli? Thanks!
If executing PHP scripts directly on command line, you can try the -d option. Another way is to make use of the `WP_CLI` constant: if ( defined('WP_CLI') && WP_CLI ) { // Load custom PHP configurations here. }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp cli" }
get data match with extra field value using wp_query for custom post I added post_meta 'batch' to 'assignment' custom post as follows: update_post_meta( $id, 'batch', strip_tags($_POST['batch'])); Now I am trying to retrieve this data as follows: $args = array( 'post_type' => 'assignment', 'post_status' => 'publish', ); $assignments = new WP_Query( $args ); I want to get all data having 'batch=2017'. How can I do this?
Change your WP Query arguments like this: $args = array( 'post_type' => 'assignment', 'post_status' => 'publish', 'meta_key' => 'batch', 'meta_value' => '2017', ); For multiple post meta you can use meta_query like this $args = array( 'post_type' => 'assignment', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'color', 'value' => 'blue', ), array( 'key' => 'year', 'value' => '2017', ) ), );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query" }
How to change thumbnail of embedded Youtube video? When I embed a Youtube video onto my page, is there a way to change the thumbnail displayed (screenshot)? I do not have admin access to the Youtube video in-question. I would prefer a non-plugin solution if possible. I found these instructions, but they did not work.
The [`[video]` shortcode]( can be used with the `src` being an URL of a youtube video. To set a placeholder, preview thumbnail use `poster`, it even works nicely via GUI. In the end it should look somewhat like the bellow example. [video src=" poster="
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "embed, youtube" }
Get the author meta adds <p> now I used to have this code which worked fine: <div class="kabaut"><?php echo get_the_author_meta('description'); ?></div> After the latest update, wordpress now adds `<p> </p>` tags for the output. How do I strip out these tags?
`get_the_author_meta` applies a filter `get_the_author_{$field}`, i.e. in your case it will be `get_the_author_description`: function stripp($value) { return str_replace(array('<p>','</p>'), '', $value); } add_filter('get_the_author_description', 'stripp'); In case the `p` tag has attributes, you may have to modify the above accordingly, or use `preg_replace`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, author" }
Change output based on text field value I need to change the output of my custom fields based on whether or not there is a specific word in the text field. For example, I need to show the French flag if a text field contains the word "France." Is that a possibility, and how would I go about it? Thanks!
What you can do is: $string = get_field( 'your_field_name' ); if (strpos($string , 'France') !== false) { // do your thing } _You can use the`stripos` for case-insensitive._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, advanced custom fields" }
How to display the percentage of the applied tax in woocommerce The problem is simple, the solution doesn't want to meet me. I want to display (echo) the percentage of the VAT I have defined in my woocommerce settings. Let's say it is 24%. I want to echo it (in the cart or checkout page somewhere, it doesn't really matter) as 0.24 . If I change the VAT to 22%, then automatically it should show 0.22 and so on... How can I achieve this? Many thanks in advance
For anyone still interested, this is the solution I found just yesterday afternoon. Create a shortcode using this function: // Function to add shortcode to display tax rates function woocommerce_template_display_tax() { global $product; $tax_rates = WC_Tax::get_rates( $product->get_tax_class() ); if (!empty($tax_rates)) { $tax_rate = reset($tax_rates); echo sprintf(_x('Price without %.2f %% tax', 'Text for tax rate. %.2f = tax rate', 'wptheme.foundation'), $tax_rate['rate']); } } add_shortcode('display_tax', 'woocommerce_template_display_tax'); Using the shortcode [display_tax]. It displays actually "Price witout xxx% tax. So, you can modify a bit the code above to just echo the tax amount. Initial code can be found here <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Insert sometext after first h3 in content I try to change something my wordpress page. I'm always writing contect with h3 tag but mutiple like each post 3 times 3h. I want to add some text after first h3 tag. function add_content_after_h3($content){ if (is_single()) { $div = '<div>sometext</div>'; $content = preg_replace('/(<\/h3>)/i', '\1'.$div, $content); } return $content[0]; } add_filter('the_content', 'add_content_after_h3'); But this code not working :(
Note returning `$content[0];` when `!is_single()` you'll get non-exist errors. * * * You can accomplish what you're after with somthing like: add_filter('the_content', function ($content){ if (!is_single()) return $content; $div = ""; return preg_replace('/<\/h3>/i', "</h3>".$div, $content, 1); }); note the third parameter of `preg_replace()` is the limit, setting to `1` will restrict the replace to the first match.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, single" }
Using jquery with wordpress using wp_enqueue_scripts I need to include jquery in a single page template of my theme. But it looks like it doesn't want to. I tried calling it with wp_enqueue_scripts() but i does nothing. Here is what is in functions.php add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' ); function custom_theme_load_scripts() { wp_enqueue_script( 'jquery' ); } And what I'm trying to do in page-template.php <?php custom_theme_load_scripts(); ?> <script type="text/javascript"> //stuff using jquery here </script> Even calling it before the header doesn't work. I don't want to load an external jquery file since wordpress already have one, but I'm banging my head against the wall as I have no idea why it doesn't work. Any ideas ?
Okay, this is awkward but I resolved my own issue. jQuery was indeed charging but... I was using `$this`. And as someone already said on another thread: > By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries). So, you must use `jquery` as a selector instead of `$`. Hope it can help someone else ! Thanks a everyone trying to help !
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, scripts" }
WP Archive & Category Pages not filtering I'm going bananas. I'm creating custom archive pages for a client because whoever originally developed their site didn't create any. I've got the pages there and working like they should, but it's not showing the appropriate posts per whatever category/tag page we're on. Here's my code snippet boiled down: <?php $args = array ( 'category' => single_cat_title(), 'posts_per_page' => 5); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li> <?php the_title(); ?> </li> <?php endforeach; ?> I'm not sure why I'm having such a hard time with this today. Geez.
From the codex for get_posts() > The category parameter needs to be the ID of the category, and not the category name. So you should either use `category_name` parameter with name or you could pass the ID to `category`. <?php $term_name = get_queried_object()->name; $args = array ( 'category_name' => $term_name, 'posts_per_page' => 5); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li> <?php the_title(); ?> </li> <?php endforeach; ?> or <?php $term_id = get_queried_object()->term_id; $args = array ( 'category' => $term_id, 'posts_per_page' => 5); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li> <?php the_title(); ?> </li> <?php endforeach; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "archives, categories" }
Hiding all products except for one in wordpress admin panel I just got very strange requirement from the client that he wants to hide all product from admin panel product tab except for one product **which has id 9** any one have any idea how to do that would be much appreciated. Thank you in advance. By the way I have tried it using css but logic doesn't make any sense I want the WordPress solution to do this.
You have to use `pre_get_posts` hook to alter the WordPress main query. `$query->get()` : < `is_admin()` : < `pre_get_posts` hook : < // Handle the main query and set the post ID to 9 function wpse_288586_hide_products($query) { // We have to check if we are in admin and check if current query is the main query and check if you are looking for product post type if(is_admin() && $query->is_main_query() && $query->get('post_type') == "product") { $query->set('post__in', array(9)); } } add_action('pre_get_posts', 'wpse_288586_hide_products');
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "woocommerce offtopic" }
How to display pictures from database? I am adding all the webpage content to the database. Later on I check the page id and select the corresponding post. There also picture for example: <img class="componentIcon" src="<?php bloginfo('template_url') ?>/img/bridge_ico.png"> <p class="boxTitle">Bridge</p> This will display the picture from the theme folder, but how to select a picture from the media library in wordpress and display it?
You'll want to use `wp_get_attachment_image_url()` or `wp_get_attachment_image()`. You just pass them the ID of the image in the database and the size you want. `wp_get_attachment_image_url()` gives you the URL of the image: echo wp_get_attachment_image_url( $attachment_id, 'large' ); // While `wp_get_attachment_image()` gives you a full image tag: echo wp_get_attachment_image( $attachment_id, 'large', false, [ 'class' => 'my-image' ] ); // <img src=" class="my-image" etc... If you do want it from your theme folder, then a better method these days is `get_theme_file_uri()`, because it supports being filtered or being replaced by child themes: echo get_theme_file_uri( '/img/bridge_ico.png' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, css, page template" }
How to remove sticky post capability for a specific user role? All is in the title. Does someone know a way to do that ? Thanks !
Though may not be intuitive, one needs the capability `edit_others_posts` to make posts sticky. If you don't want a user to have that ability just remove the `edit_others_posts` capability from the user.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "user roles, capabilities, permissions, sticky post, featured post" }
post_exists() in an external script? I use this code to import posts from an external script. < This works but I need to check if a post exits. So I want to use post_exists(). if(post_exists("test") > 0) { } I got this error: Fatal error: Uncaught Error: Call to undefined function post_exists() Is it possible to check in an external script for posts?
`post_exists()` doesn't exist because you forgot to include the file where the function is declared. Looking to < you can see that it's declared in `wp-admin/includes/post.php` Add this to your existing code juste after the `require` of taxonomy. require_once ABSPATH . '/wp-admin/includes/post.php'; The best way to achieve what you want is to use wp-api in my opinion !
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts" }
How to generate page content from database the right way? I am creating many pages and store them into the database. I am first styling them and than storing them. The idea is to use page.php to check the page id and display the needed post. This is all good, but I have many pages in the website. WHich means I have to perform the following statement many time. <?php if(is_page(14)) { global $wpdb; $findContent = $wpdb->get_var("SELECT post_content FROM wp_posts WHERE post_title = 'Why ......'"); get_template_part( 'localnav' ); echo $findContent; } ?> My question is is that a good rpactice or is there a better idea? Note there asome pages which look alike, maybe I can create catogories, but is it possible to select part of the content and put it in a div for example?
WordPress is fetching current post for you, you have to only type to the right url. When you get e.g. to `example.com/lorem-ipsum/` WordPress will load automatically post with title `Lorem ipsum` and display it using `page.php` template. Your `page.php` template should be looking something like that. <?php get_header(); ?> <div id="content"> <?php while ( have_posts() ) : the_post(): ?> <h1><?php the_title(); ?></h1> <?php the_content(); ?> <?php endwhile; ?> </div> <?php get_sidebar(); get_footer(); The concept of a loop is difficult to understand for novice developers. Only in the loop you can use functions like `the_title` or`the_content`. Outside of the `loop`, these functions won't return you anything. <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, database, sql" }
Insert wp_query after the_content with plugin (filter the_content won't work) I would like to insert a wp_query after the post content. After looking in different website, they all suggest using a filter on the_content. Example: add_filter( 'the_content', 'filter_the_content_in_the_main_loop' ); function add_query_after_content( $content ) { echo $content; echo *** The query ****; } add_filter( 'the_content', 'add_query_after_content' ) However it creates an infinite loop (the content in the query is filtered as well). What is a good way to entering the query automatically after the post, **using a plugin that will work on most themes** ?
You should remove your hook before query. function wpse_288691_add_query_after_content( $content ) { $ouptut = ''; remove_filter( 'the_content', 'wpse_288691_add_query_after_content' ); // Do your *** WP_Query *** and assign result to $ouptut. // Reset query by executing `wp_reset_query`. add_filter( 'the_content', 'wpse_288691_add_query_after_content' ); return $content . $ouptut; } add_filter( 'the_content', 'wpse_288691_add_query_after_content' ); Do not `echo` anything inside the filter, only return values.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, filters, the content" }
why is the delete option missing from just one category? A site I'm working on had one big category called `News`. I wanted to be a little more specific and create `Industry News` and `Company News`. Not a big deal at all, but when I go to delete `News`, I saw that delete options are missing! Both the checkbox... ![in the markup, there is a non-breaking space entity instead of a checkbox!]( ...and the link that appears when you hover are just not there. ![where is that link?!]( I know I can delete this category directly from the database, so this is more for curiosity than anything...but what could make these options disappear for _just one category_?
You're unable to delete just one category because it's your default category. You may change the default category via via **wp-admin > Settings > Writing > "Default Post Category"** .
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "categories, wp admin, customization, admin ui" }
Check if column exists for one table in DB In my addon, I would like to check on activation, if a column of a specific table in the DB already exists to avoid to implement it for each activation. Something like this : class MainClassAddon{ public function __construct(){ register_activation_hook( __FILE__, array( $this, 'install' ) ); } public function install(){ if( /*Checking if column c in table wp_t exists*/ ){ $wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1"); } } } new MainClassAddon(); register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );
I found this solution : here So... class MainClassAddon{ public function __construct(){ register_activation_hook( __FILE__, array( $this, 'install' ) ); } public function install(){ $row = $wpdb->get_results( "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'wp_t' AND column_name = 'c'" ); if(empty($row)){ $wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1"); } } } new MainClassAddon(); register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "database, columns" }
How to use a capture from a rewrite rule inside a php file (like single.php)? My rewrite rule to make a convenient url for deep-linking into podcasts add_filter("rewrite_rules_array", function($rules) { $newRules = array(); $newRules["(.*)/time/([\d|\:]+)s?$"] = 'index.php?name=$matches[1]&t=$matches[2]'; $merged = array_merge($newRules, $rules); return $merged; }); Query Monitor shows me this rewrite rule is working; I get to single.php with the right post, Woop Woop! But `$_GET["t"]` is not set. I also don't see a `t` in `$wp_query->query_vars`. How can I now make use of `t` inside the `single.php`? . . What confuses me: My rewrite rule for `/email` works similar; but `email.php` can make use of the get-vars; add_rewrite_rule( '^email/(.*)/(.*)/?$', 'wp-content/themes/myTheme/email.php?to=$1&subject=$2', 'top' );
Nicolais Tip got me on the right track; Here is the working code: // add a query_var first add_filter("query_vars", function($vars) { $vars[] = "myTheme_podcast_time"; return $vars; }); add_filter("rewrite_rules_array", function($rules) { $newRules = array(); $newRules["(.*)/time/([\d|\:]+)s?$"] = 'index.php?name=$matches[1]&myTheme_podcast_time=$matches[2]'; $merged = array_merge($newRules, $rules); return $merged; }); And then in `single.php`: $time = get_query_var("myTheme_podcast_time"); // do stuff
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, rewrite rules, single" }
replace existing menu programtically I create my own menu programatically: $menu_id = wp_create_nav_menu($menu_name); wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __('Home'), 'menu-item-classes' => 'home', 'menu-item-url' => home_url( '/' ), 'menu-item-status' => 'publish')); wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __('Custom Page'), 'menu-item-url' => home_url( '/custom/' ), 'menu-item-status' => 'publish')); wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __('SHIT'), 'menu-item-url' => home_url( '/custom/' ), 'menu-item-status' => 'publish')); Now i can to replace my menu with the existing one. What code should i call? Thanks From Peter
Add this code to `functions.php` of your current theme ( preferably child theme ): $menuName = 'Your menu name'; $locationID = 'primary'; $myMenu = get_term_by('name', $menuName, 'nav_menu'); $locations = get_theme_mod('nav_menu_locations'); if($myMenu->term_id !== $locations[$locationID]) { $locations[$locationID] = $myMenu->term_id; set_theme_mod('nav_menu_locations', $locations); } Remember to change values of first two variables to match your requirements.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "menus" }
How to make unique add_filter to the_content of specific page template files - so each template gets its own addition I have made a couple of custom page templates files: page-florida.php page-texas.php etc. Now I want to add some php after the_content so that each page template get their own php addition script just after the content. I am thinking something along the lines of adding to the functions.php - but I am having trouble properly identifying the right page template, for instance "page-florida.php" ... function floridacontent($content) { global $post; if ($post->page_template == 'florida') { $content .= 'Forida added content'; } return $content; } add_filter('the_content', 'floridacontent');
You can get the name from the global `$template`. I don't know of a way to get it with an API call instead of a global, but such is life. function floridacontent( $content ){ global $template; $name = basename( $template, '.php' ); if( 'page-florida' == $name ){ $content .= 'Forida added content'; } return $content; } add_filter( 'the_content', 'floridacontent' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "functions, filters, page template" }
How do i output images from URL's added to the same custom field key This is my array of image URL's added to the same custom field named images. $images = get_post_custom_values( 'images' ); I need to print all these images in a template file.
This is how i ended up coding the solution : $images = get_post_custom_values( 'images' ); if ( $images ) { echo '<div class="image-wrap">'; if ( $image_header ) { echo '<div class="header">' . esc_html( $image_header ) . '</div>'; } foreach ( (array) $images as $image ) { $url = esc_url( $image ); $alt = esc_html( the_title_attribute( 'echo=0' ) ); if ( $url ) { echo '<img class="image-section" src="' . $url . '" alt="' . $alt . '" />'; } } echo '</div>'; } **To get the i.d from a URL** You can use attachment_url_to_postid like this : $url = ' $id = attachment_url_to_postid( $url ); $alt = get_post_meta( $id, '_wp_attachment_image_alt', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "custom field, array, post meta" }
How to on/off woocommerce filter with redux framework I am using this woocommerce filter in my function file add_filter ('add_to_cart_redirect', 'redirect_to_checkout'); function redirect_to_checkout() { global $woocommerce; $checkout_url = $woocommerce->cart->get_checkout_url(); return $checkout_url; } How can i get on/off system to this filter with redux framework. I already created Option in redux. But i am not sure how can i use redux option in function file.
Just add redux global variable between funtion add_filter ('add_to_cart_redirect', 'redirect_to_checkout'); function redirect_to_checkout() { global $xpanel; if ( isset( $xpanel['woo-option'] ) && $xpanel['woo-option'] == TRUE ) { global $woocommerce; $checkout_url = $woocommerce->cart->get_checkout_url(); return $checkout_url; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
error_log() output for print_r() appearing on page I am trying to debug a plugin and am using `error_log()` in various places to see what various things are. I am using the following: error_log( print_r( $variable ) ); When I look at `debug.log`, all I see is `1` and the actual output of the `error_log()` function is sent to the browser instead. I know another plugin is not doing this as all are disabled with the exception of the one I am writing. In my `wp-config.php`, I have defined `WP_DEBUG_DISPLAY` as `false`. The same thing happens if I use `var_dump()` and `var_export()`. Other functions like `gettype()` work just fine. Is there any way to get the output into `debug.log`?
The print_r function accept second parameter for `return` so it retrun the variable instead of printing it. print_r($expression, $return) So you can do error_log( print_r( $variable, true ) );
stackexchange-wordpress
{ "answer_score": 14, "question_score": 10, "tags": "php, plugin development, errors, debug" }
Wpdb->query result show 1 but is not an integer I have a weird result. I'm trying to add a column in an existing table. When I check the result _$res_ , I have a result like 1 but seems to be not an integer. **php code** $res = $wpdb->query("ALTER TABLE " . $table_name. " ADD " . $column_name . " varchar(35)"); error_log( $res ); error_log( "int ? : " . ( is_int( $res ) ? 'true' : 'false' ) ); **output** 1 [18-Dec-2017 16:32:02 UTC] 1 2 [18-Dec-2017 16:32:02 UTC] int ? : false The column is created. I have a problem only with the returned result to continue my program. Someone knows why ?
I found the solution. The result 1 for my query means true and it's a boolean so > $wpdb->query can return true, not only int|false as it is written above the public function query : wpdb::query **PHP code** $res = $wpdb->query("ALTER TABLE " . $table_name. " ADD " . $column_name . " varchar(35)"); error_log( $res ); error_log( "bool ? : " . ( is_int( $res ) ? 'true' : 'false' ) );'false' ) ); **output** 1 [18-Dec-2017 17:10:10 UTC] 1 2 [18-Dec-2017 17:10:10 UTC] bool ? : true
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, database" }
Is it possible to use child theme of child them? I am using iStore free WordPress theme for a website. It is a child theme of MaxStore. Now I need to modify the iStore themes. Since iStore is a already child theme, I don't know that is it possible to create a child theme of iStore ? Is it possible? If not what is the alternative way to change child theme?
> Is it possible? No. There's no such things as grandchild themes. > If not what is the alternative way to change child theme? Many things can be done from plugins. It could be from very easy to very hard depending on how things are actually done in the theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "themes, child theme" }
Limit WP_Query to only X results (total, not per page) How to limit WP_Query to grab only let’s say 5 results? What I mean is actually only 5 results rather than 5 posts per page. This > How to limit the number of posts that WP_Query gets? provides some insight and advices to use `no_found_rows=true` but do you use it with posts_per_page or do you need to limit results somewhere else? In my case (search) `get_posts` doesn’t work as I need to provide a search query.
As you already mentioned, to limit the number of posts retrieved by the query, you can use `posts_per_page`. This argument works both for `get_posts` and `WP_Query()`, for example: $args = array( 'posts_per_page' => 5, ); $posts_array = get_posts( $args ); And as stated in the link you provided, `no_found_rows = true` will end the query after it reached its criteria. It's totally optional, and not very common.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "wp query" }
Get a Taxonomy values in an array I have a Taxonomy type named: Products:product_cat I need the term names inside this field in an array. Is there any way to get them?
You can retrieve a taxonomies terms with `get_terms()`. Via their docs: $terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false, )); And it returns: > (array|int|WP_Error) List of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies do not exist. Which you can view by doing somthing like echo "<pre>".print_r($terms,true)."</pre>";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, functions, advanced custom fields, advanced taxonomy queries" }
Custom Post Type UI for custom tables I am working on a plugin and I like to utilize the WordPress's native admin UI for post listing and post editing screen for my own data structure. Does anybody has an idea or guidelines please?
The tables are built with WP_List_Table class, but can be re-built visually (no ordering/filtering built in) by copying html. The post list and the posts edit screens for custom post types will be the standard UI - its your metaboxes that will require some manual copying of Wordpress styles. There's these site and project that helps with classes and colours: * < * < Using web browser inspector you can find the classnames of Wordpress elements and reuse them, for example for grey vs blue main buttons it's: `.button` and `.button.button-primary.button-large`
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "admin ui" }
Changing the server path We have a WordPress multisite set up and working fine, but now the owner wants to change the server path to a different name. Will WordPress be able to automatically continue working with the new server pathname, or is there something we need to configure?
WordPress doesn't rely on server path, it relies on the URI. When the WordPress code is loaded, it will define the proper paths itself dynamically by using PHP constants like `__FILE__`, such as `ABSPATH` which is the absolute path to the WordPress's installation. So, as long as your domain remains the same, you should not experience any problem.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "server, paths" }
Removing storefront-sorting div from the before section of Shop page I have already found out that I can remove sorting drop down menu and pagination from the shop page using: function delay_remove() { remove_action( 'woocommerce_after_shop_loop', 'woocommerce_catalog_ordering', 10 ); remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 10 ); remove_action( 'woocommerce_before_shop_loop' , 'woocommerce_result_count', 20 ); remove_action( 'woocommerce_after_shop_loop' , 'woocommerce_result_count', 20 ); remove_action('woocommerce_before_shop_loop','storefront_woocommerce_pagination',30); } The problem is that I still have an empty div there: <div class="storefront-sorting"></div> I could use style to hide the div but that would defeat the purpose of using remove_action. Is there any remove_action that I can use to remove that div as well?
storefront theme has its own file where you can find all hooks and filters its adding for woocommerce. you can find it at this path: **storefront/inc/woocommerce/storefront-woocommerce-template-hooks.php** To remove storefront-sorting div, you can add the following in your child theme's functions.php: remove_action( 'woocommerce_after_shop_loop','storefront_sorting_wrapper',9 ); //.storefront-sorting opening after products loop remove_action( 'woocommerce_after_shop_loop','storefront_sorting_wrapper_close',31 ); //.storefront-sorting closing after products loop remove_action( 'woocommerce_before_shop_loop','storefront_sorting_wrapper',9 );//.storefront-sorting opening before products loop remove_action( 'woocommerce_before_shop_loop','storefront_sorting_wrapper_close',31 ); //.storefront-sorting closing before products loop
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Custom taxonomy template for custom fields loop I have jobs custom post type which contains custom taxonomies * Location * Company * State * Qualification and added custom fields * Name of company - text field * Post Name - text field * Number of posts - number field * qualification - text field * Last Date - text field more * details - text field(Post link) now how can i add these custom fields of custom post type in a custom taxonomy template. In custom taxonomy template these fields should be displayed in a table.
Not sure what the exact query is but these fields can be accessed on the taxonomy template in the same way as they are accessed elsewhere - using `get_post_meta()`. The code in your taxonomy template has a part which loops through all the relevant posts and gives back the info. You can sort the post ID from it and use it in `get_post_meta()` Sorry if this is not what you are looking for. **EDIT (Code Added)** if ( have_posts() ) : while ( have_posts() ) : the_post(); echo $company_name = get_post_meta( get_the_ID(), 'name-of-company', true ); endwhile; endif;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, custom field, loop, templates" }
Create rewriterules for different domains in htaccess file with WP multisite Normally if you have one WordPress website it is easy to create rewrite rules in the `.htaccess` file for your domain. For example, if your domain is DomainA.com and you have the following rewrite rule: RewriteRule ^i-like-([a-zA-Z0-9-]+)/$ wp-content/themes/customtheme/custom-pages/ilike.php?like=$1 [L] You will get DomainA.com/i-like-... But what if I have a multisite with the following domains: * DomainA.com (primary domain) * DomainB.com (Mapped domain) * DomainC.com (Mapped domain) And I want to create a rewrite rule for DomainB.com for a specific file like above? Is there a way to achieve this?
If you wanted to target a specific domain then you need a _condition_ (`RewriteCond` directive), preceding the `RewriteRule` that checks for the specific domain (`Host:` header). For example: RewriteCond %{HTTP_HOST} ^domainb\.com [NC] RewriteRule ^i-like-([a-zA-Z0-9-]+)/$ wp-content/themes/customtheme/custom-pages/ilike.php?like=$1 [L] The `HTTP_HOST` server variable contains just the `Host:` header sent in the request. Reference: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, htaccess, rewrite rules, domain mapping" }
is there a way to retrieve posts that do not have a featured image assigned? so as the questions states, what im trying to accomplish is to fetch only the posts that do not have a featured image set. i tried looking through the docs and i noticed you can use the - symbol to exclude something from your argument, but that isn't working for me. Is there something else i can do in my query args to achieve this? thanks for your help! $mediaargs = array( 'post_type' => 'media', 'posts_per_page' => 1, 'paged' => $paged, 'order' => 'DESC', 'orderby' => 'modified', 'meta_key' => '-_thumbnail_id', );
$mediaargs = array( 'post_type' => 'media', 'posts_per_page' => 1, 'paged' => $paged, 'order' => 'DESC', 'orderby' => 'modified', 'meta_query' => array( array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS' ) ), );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, posts, wp query, post thumbnails, exclude" }
extract serialized array to use for wp-query I use wp-query and I need to display posts by author, using author id. This is the serialized array: a:19:{i:0;s:2:"89";i:3;s:3:"105";i:4;s:2:"74";i:5;s:3:"111";i:6;s:3:"167";i:7;s:2:"83";i:8;s:2:"54";i:9;s:2:"87";i:10;s:2:"85";i:11;s:2:"77";i:13;s:2:"82";i:14;s:2:"60";i:15;s:3:"149";i:16;s:3:"160";i:17;s:2:"71";i:18;s:1:"3";i:19;s:1:"2";i:20;s:3:"121";i:21;s:2:"57";} This array includes the author's id so my question how can use wp-query 'author' or 'author__in' by using a serialized array? Like this: $first_post_ids = get_posts( array( 'fields' => 'ids', 'post_type' => 'the_posts', 'author__in' => get_user_meta($current_user->ID, 'following_users', true) ));
You need to `unserialize()` if its serialized string. In your case from what I understand you store the array in the user_meta so its serialize it when you store it. but it will unserialize it when you use the `get_user_meta` so you dont need to `unserialize()` Your code seems fine. $author_in = get_user_meta($current_user->ID, 'following_users', true); $first_post_ids = get_posts( array( 'fields' => 'ids', 'post_type' => 'the_posts', 'author__in' => $author_in ));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query, array" }
get_posts - check if custom field has content? I have this loop that works fine but I have to check if the custom fields of the post objects ("houses") have content. I try this with "isset" and nothing happens. Tried "isset", too but same problem. $args2 = array ( 'numberposts' => -1, 'post_type' => 'houses' ); $custom_posts2 = get_posts($args2); foreach ( $custom_posts2 as $custom_post2 ) { // check here if custom post type opjects custom field "sz_website" has content if ( !empty ($custom_post2->post_website)) { echo '<div class="wpcf7-list-item-field">' . $custom_post2->sz_website . '</div>'; } else { echo "do nothing"; } } wp_reset_postdata();
Try this: $args2 = array ( 'numberposts' => -1, 'post_type' => 'houses' ); $custom_posts2 = get_posts($args2); foreach ( $custom_posts2 as $custom_post2 ) { // check here if custom post type opjects custom field "sz_website" has content $sz_website = get_post_meta( $custom_post2->ID, 'sz_website', true ); if ( !empty ($sz_website)) { echo '<div class="wpcf7-list-item-field">' . $sz_website . '</div>'; } else { echo "do nothing"; } } wp_reset_postdata(); Let me know if helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "get posts" }
Allowing Admins to edit Pod Templates on a Network/MultiSite install For a client I'm running Pods WP Networks install. A multisite Administrator reports that she can't edit any of the Pod Templates (found under `/wp-admin/edit.php?post_type=_pods_template`). I can edit these as a Network Super-Admin, but she can't as a Site Administrator. Is there a way to allow the Admin to edit her Pod Templates without prompting her to a SuperAdmin temporarily)?
You can add the capability of all adminstrators to use Pods in putting this code in a plugin : add_filter("pods_admin_capabilities", function ($pods_admin_capabilities, $cap) { $pods_admin_capabilities[] = "administrator"; return $pods_admin_capabilities; }, 10, 2);
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "pods framework" }
Allow user to select categories that will display in post loop I am building a simple theme from scratch (really just for fun, and for the purpose of learning about WordPress development) but I have an idea I want to implement. I have built a page template that will display a loop of posts from a certain category, however I want the user to be able to select the categories they want to display in that loop, preferably when they create the page and select the template. How best to develop this?
Use `wp_dropdown_categories()` to do so, I've addressed this before, here and here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, theme development, loop" }
How do you get specific tags from the_content? How would I grab specific tags from the_content? For example, I'd like to pull a list of all h1 tags.
Using `preg_match_all()` you can create a regex pattern to find and extract tags (and their content). With Wordpress's `post_content` hook, you can find and list all the H1's within current posts content with something like: add_action('the_content', function ($content){ // look for <h1> tags and text therein, anticipate class/id name $findH1s = preg_match_all('/<h1 ?.*>(.*)<\/h1>/i', $content, $h1s); // if found, show above content if (is_array($h1s) && isset($h1s[0])) return "<pre>H1's in this post: ".print_r( $h1s[0] ,true)."</pre>".$content; // if none found, just return content as-is return $content; });
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "filters, the content" }
Hide post title when single post with specific category May I know is there a way I can show my blog post title under the below condition? <header class="single-header"> <?php if(is_singular('post') && (!is_category('campaign-post'))) : ?> <h2 class="page-title"><?php the_title();?></h2> <?php endif; ?> </header> I have a few different categories, which I have created within Posts. One of it (campaign-post), I wish not to show the post title. So I have written the above condition. Unfortunately, no luck. The title still showing. Can anyone show some clue how I can solve this problem?
Instead of !is_category('campaign-post') I think it's !in_category('campaign-post') * * * `is_category()` is used within Archives pages, when it's in WP Query. Like your viewing a category archive page, and you're asking: _is this the category queried_. `in_category()` (which uses `has_category()` which then uses `has_term()` which then uses `is_object_in_term()`) relates to single posts, asking: _does this post have this term_.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts" }
Nested Page Template not showing in page attributes I have a custom page template that I am trying to use on my WP site (version 4.9). The folder structure where I am placing my page templates are as follows. theme-root (/wp-content/themes/mytheme/) |-landing |-template-name |-index.php etc... When all of the template files are placed up one level in theme-root/landing I can see the template in the page attributes box on the admin screen when editing the page. When it is placed inside the template-name folder it doesn't show up. I have a plugin to clear the file cache so the problem isn't from the caching of files. It is structured this way because the site uses multiple page templates.
In WP 3.4 they allowed adding template files one level deep. Since then code has changed, however in `wp-includes/class-wp-theme.php`, in `offsetGet()` (from `__get()`) you'll see: case 'Template Files' : $files = $this->get_files( 'php', 1 ); Although I can't fully unravel the maze of code for loading a theme, the above suggests the second argument, `$depth`, is still set to only `1` deep for `Template Files`. Which would coincide with the troubles your experiencing. You may want to re-think your themes folder structure, and/or your logic for selecting a template. If you're conditionally checking which template was chosen based on a user selection in the first place, on your conditions using the `load_template()` andor `template_redirect()` might help out more than leaving it to Wordpress defaults.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, page template" }
Apply Additional Discount after coupon I want to provide special discount on cart items but want to apply right after the coupon OR when proceed to checkout is clicked. **Example:** The customer added an item in cart with total price $100 and he applied the coupon e.g `10%OFF`. Now the total remaining cost is $90 and now I want to apply additional 30% discount which will be on remaining cost ($90). I found this but it does partial job: function custom_wc_add_fee() { WC()->cart->add_fee( 'Fee', -10 ); } add_action( 'woocommerce_cart_calculate_fees','custom_wc_add_fee' ); First, it applies when the cart page is loaded. (whenever I need after coupon). Secondly, I'm unable to get the cart price so unable to apply percent discount. What I like about hook is that it adds a little description so customer knows what happened.
Put this code in your current theme function.php file. Set how many discount as per your require. function add_extra_discount( $cart ) { $discount = $cart->subtotal * 0.3; $cart->add_fee( __( 'Extra Discount', 'twentyseventeen' ) , -$discount ); } add_action( 'woocommerce_cart_calculate_fees', 'add_extra_discount' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
wp mail smtp earlier version Dose anyone have an earlier version of the plugin wp mail smtp? It doesn't work when I update the plugin. Send the earlier version to my email [email protected] will be appreciatted. Thanks in advance!
Are you looking for this SVN depot ? <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp mail, phpmailer, smtp" }
How to list all tags except the current tag in tag.php I'm struggling to find a way to list all my tags without the current tag showing when i'm on a tag.php page. All I have is **this** , but it's not the current tag?
You may try `get_tags` with `exclude` parameter. < `get_queried_object_id` get the tag ID from tag page. $tags = get_tags(array( 'exclude' => get_queried_object_id(), )); $tagList = array(); foreach($tags as $tag) { $tagList[] = '<a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a>'; } echo implode(', ', $tagList);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags, exclude" }
ACF Filter return value I'm working on a relationship filter using this documentary. I made so far but can't make my return value. Normally in a custom Template I just echo it, but it's different in a function I think. function soup_filter( $args, $field, $post_id ) { $args = array('post_type' => 'menu'); $query = new WP_Query( $args ); $soups = get_field('soups'); foreach ($soups as $soup) { //return value stored here in $soup } // return return $args; } add_filter('acf/fields/relationship/query/key=field_59f736725fe5d', 'soup_filter', 10, 3);
I am not sure it is supposed to work like this. Maybe try calling the get_field like this. If the get_field is not called within the loop, it needs the post_id parameter $soups = get_field('soups', $post_id )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, filters, advanced custom fields" }
Font Awesome Icons Won't Work I do have font awesome installed with my theme. The icons on my home page was working well before. I dont know why but the shortcodes of my icons now stopped working. I do have empty white square instead of the icons. Or nothing at all. I am not skilled so can please check my site and help me out how to fix this problem? www.ekn.sinankarabulut.com Shortcode for an icon is; [iconbox title="Başarı" icon="star-empty"]Çözüm üretiyoruz...[/iconbox] You can inspect them from my home page, icons were in the orange boxes. Thanks for your time...
Try this one [iconbox title="Başarı" icon=" fa fa-star"]Çözüm üretiyoruz...[/iconbox] [iconbox title="Başarı" icon=" fa fa-html5"]Çözüm üretiyoruz...[/iconbox]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, icon" }
Loop through an array inside a class using foreach I'm creating a class in my **WordPress template** and I have a multidimensional array as **protected** member. The array at second level contains some _email addresses_ as **string** and I want to get those emails through a `foreach` loop. The code is like below. class myclass { private $arr = array( 'emails' => array( '[email protected]', '[email protected]', '[email protected]' ) ); protected $emails = array(); foreach($this->arr['emails'] as $email) { $this->emails[] .= $email } } * * * ### PHP Giving Error **Parse error** : syntax error, unexpected `for` (`T_FOR`), expecting `function` (`T_FUNCTION`) or `const` (`T_CONST`) in **C:\xampp\htdocs\wp-content\themes\mytheme\functions.php** on line `no need of this`
You can't have code directly in the class definition. If you want it on instantiation, put it in the `__construct` function. Also, be aware that you were missing a semicolon and `.=` is used to append to strings, not to add to arrays. I've fixed those as well: <?php class myclass { private $arr = array( 'emails' => array( '[email protected]', '[email protected]', '[email protected]' ) ); protected $emails = array(); function __construct() { foreach($this->arr['emails'] as $email) { $emails[] = $email; } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, errors, array, oop" }
Delete a white space using css How can I eliminate the white space between the normal price and the digital price in my single product page? Take a look to this screenshot:![screenshot]( Here the URL: <
You may add this to your custom CSS in order to remove margin bottom of price and reduce this white space : p.price { margin-bottom: 0; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "css" }
Reduce size of responsive title When using a mobile device or a tablet, the titles of my products are cropped. I'd like to simply reduce their size. Take a look to the image:![Cropped title]( Is there a way to change that? Is it CSS or Php? The URL of the product is this: <
You can add custom CSS where you use media query in order to reduce the font-size of the title in small devices. You also have some styling that remove the **line break** and add the **3 dots** at the end. So you can also remove them. You can try this code : @media all and (max-width:480px) { .woocommerce div.product .product_title { font-size:18px; white-space: initial; text-overflow: initial; } } You may adjust the value of font-size as you need.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, css, title, responsive" }
Change directory of javascript files I'd like to move all my assets (CSS, JS, Images, Fonts) in an asset folder in my theme. I did it very well for the fonts and images. For the CSS, I just kept the style.css with the style meta information in it (as advised here). But I'm using the great underscores.me starter theme for Wordpress and I have in my theme a JS folder containing customizer, navigation.js and skip-link-focus-fix.js All these scripts are included in my footer via the wp_footer() function. So, if I move these scripts to my /assets/js/ folder, I have three missing files called in the footer. Is there a way to (1) not load these scripts or (2) change the directory and tell the wp_footer to call /assets/js and not /js/ ? Thank you for your help.
go to your themes `functions.php` and find line 122. You will find navigation.js function. get_template_directory_uri() . '/js/navigation.js and change it to get_template_directory_uri() . 'assets/js/navigation.js do it again for `skip-link-focus-fix.js` code located on line 124. For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js` Don't forget to move your files :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "directory, footer, scripts" }
How to add gallery support in WordPress? I'm creating a custom post type and I have it support featured images but I don't know how to add support for galleries as well as WooCommerce does. The idea is to add another featured image panel which accept multiple images that I can show on the front end. Thank you for you suggestions on how manage both adding support in back end and echo it in the front end.
You can use gallery-metabox. Its open source and easy to use; < From Readme ; Include the `gallery.php` in your `functions.php`: `require_once 'gallery-metabox/gallery.php';` Specify where you want the gallery metabox to show on line 17 in `gallery.php`. You can pass an array to have it show up on multiple post types, custom post types are also allowed: `$types = array('post', 'page', 'custom-post-type');` In your template inside a loop, grab the IDs of all the images with the following: `$images = get_post_meta($post->ID, 'vdw_gallery_id', true);` Then you can loop through the IDs and call `wp_get_attachment_link` or `wp_get_attachment_image` to display the images with or without a link respectively: `foreach ($images as $image) { echo wp_get_attachment_link($image, 'large'); // echo wp_get_attachment_image($image, 'large'); } `
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post thumbnails" }
Wordpress query reverse order $args = array('post_type' => 'etlap', 'posts_per_page' => 5, 'post__in' => $ids, 'post_status' => 'any', 'orderby' => 'post__in'); I want to make the orderby status reversed. How is it possible? Sorry if I ask stupid question, but I couldn't find any documentary about that.
Since you are using `'post__in'` in the `'orderby'` parameter, the `'order'` parameter will have no effect, however, you can simply reverse the array you are passing to `'post__in'`: $args = array( 'post_type' => 'etlap', 'posts_per_page' => 5, 'post__in' => array_reverse($ids), 'post_status' => 'any', 'orderby' => 'post__in' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query posts, get posts, order, array" }
override the default WooCommerce products search form how can I do override the default WooCommerce products search form on my custom WooTheme ? Thank You
Exists the template `product-searchform.php`, you have to override it in your theme. More information here about how to override WooCommerce templates from your theme. Basically the WooCommerce search forms returns only products and not also other post types because the product post type is specified in an hidden input: `<input type="hidden" name="post_type" value="product" />`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, search" }
Get category URL knowing it's id I have id of WP category on external resource. I know that if I have id of post I can create url like > < But what if I know id of category? How can I generate link to it? Category permalinks look like > < and I need to use something like > <
If you have category ID you can create link to category like below : <a href="/index.php?cat=7">Category Title</a> For more details read from this link : < Thanks!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "categories, permalinks" }
Search and Replace in Windows XAMPP site In my Ubuntu VPS, to search and replace in a DB of a site I do for example: cd /var/www/html/example.com sudo wp search-replace " " --all-tables Yet in Windows 10 I use XAMPP and can't do this action with WSL + WP-CLI because one cannot use Bash inside windows (yet). ## My problem I have installed a backup version of an online website in Windows XAMPP and all main menu links turn to the online site so I need to change in DB from ` to `localhost://`. ## My question How could I easily and efficiently change the DB from ` to `localhost://`. in XAMPP in Windows?
you have the new database selected, then run some sql updates and replacement commands on the tables notably, wp_options, wp_posts, wp_postmeta. UPDATE wp_options SET option_value = replace(option_value, ' ' WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, ' UPDATE wp_posts SET post_content = replace(post_content, ' ' UPDATE wp_postmeta SET meta_value = replace(meta_value, ' '
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql, localhost, xampp, windows" }
Why does wordpress only look at certain child theme pages, but not all of them? I created a child theme for Twenty Seventeen Wordpress theme and made copies of the parent Twenty Seventeen's header.php, template-parts' header and navigation folders into the child theme. Wordpress isn't recognizing the child theme's new files. The filepath of one of the files: ![enter image description here]( The child theme's style.css and function.php files are acknowledged. As seen as below (well at least you can see the functions.php): ![enter image description here]( I'm trying to edit the child's site-branding file, but the wordpress is still looking at the parent's site-branding file. Why is this happening? How do I correct it?
Try renaming "templates-parts" to "template-parts" in your child theme
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php" }
How to change DASH-ICON color with CSS? It is possible to change colors of DashIcons with CSS? I couldnt get it to work.
Yes, this is possible. Make sure your CSS selector is correct. You can target the specific HTML element or its `::before` pseudo element and change colour with CSS. Can you post your HTML snippet of the element you want to change and the CSS selector you are using? Maybe you mean to change the colour inside WP admin area for all dash-icons? In that case: .dashicons { color: red; }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "css" }
how to access query string in wordpress? There are several ways I have seen this question worded, so I tried to make mine generic. Let's say I go to this page: `example.com/page/?utm_source=test&s=test&page=12` `get_query_var('utm_source')` returns nothing. `$_GET` returns `Array ( [s] => test [page] => 12 )`. `$_GET` returns `Array ( [utm_source] => )` from `example.com/page/?utm_source` (key only, no value), which I really don't understand. I've done this in `functions.php`: add_filter( 'query_vars', 'add_query_vars_filter' ); function add_query_vars_filter( $vars ){ $vars[] = "utm_source"; return $vars; } ...just like ye olde codex says, so I would expect to be able to access `utm_source` through `get_query_var('utm_source')`. What am I missing?
The answer to my general question has a very specific answer, and I found the answer by running across this answer to more or less the same problem. Basically GoDaddy hosting does something special to `utm_`-type query strings. Tech support could provide no detail. In case anyone else runs across this, it looks like something mysterious happens to the standard Google Analytics query strings such as `utm_source`. Example: `utm_source` will not show up in `$_GET` (much less using `get_query_var`), but `utm__source` (2 underscores) is just fine.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "wp query, functions, filters, query variable, query string" }
Theme JS is available but theme CSS isn't In `functions.php` I used the following code to enqueue assets, but for some reason all CSS is ignored (JS isn't ingonred): function my_theme_enqueue_assets() { wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) ); wp_enqueue_script( 'behavior', get_theme_file_uri( 'behavior.js' ), array(), null, true ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' ); What's bad with the above code?
It seems to me best to separate styles, from scripts and other assets. This worked: function my_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_parent_theme_file_uri() . 'style.css' ); } add_action( 'my_theme_enqueue_styles', 'wp_enqueue_styles' ); function my_theme_enqueue_assets() { wp_enqueue_script( 'behavior', get_theme_file_uri( 'behavior.js' ), array(), null, true ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, css, javascript, wp enqueue script, wp enqueue style" }
Database size Widget Is there any way to show the database size on a WordPress Admin Area widget? I don't want it at the top or bottom of the page, i need it in my widget I'm creating.. Thanks.
Add the following code to your widget code: function fileSizeInfo($filesize) { $bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); if ($filesize < 1024) $filesize = 1; for ($i = 0; $filesize > 1024; $i++) $filesize /= 1024; $dbSizeInfo['size'] = round($filesize, 3); $dbSizeInfo['type'] = $bytes[$i]; return $dbSizeInfo; } function databaseSize() { global $wpdb; $dbsize = 0; $rows = $wpdb->get_results("SHOW table STATUS"); foreach($rows as $row) $dbsize += $row->Data_length + $row->Index_length; return fileSizeInfo($dbsize); } $dbSize = databaseSize(); echo "<b>Database size</b> = {$dbSize['size']} {$dbSize['type']}";
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "widgets, database, admin, statistics" }
Why is there a class="screen-reader-text" on my search button? i was going through a search and found this button in search form. <button type="submit" class="search-submit"> <span class="genericon-search"></span> <span class="screen-reader-text"><?php echo esc_html_x( 'Search', 'submit button', ); ?></span> I want to know what's the use of the `<span class="screen-reader-text"><?php echo esc_html_x( 'Search', 'submit button', ); ?>` in this search form, its also working when i remove this line.
This class is used to visually hide elements from sighted users but still allows assistive technologies like screen readers to still present those elements to users who are visually impaired. For example you may have an icon with Facebook's logo as a link to your page/profile. A sighted user will know that's Facebook but a blind user won't so you would still want "My Facebook Profile" or some other descriptive text to let visually impaired people know more about the link.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "search, forms, accessibility" }
Sharing post in Facebook shows UTF8 invalid character � I try to share posts from my website. The thing is the famous question mark diamond shows up on some of the posts description. All the OG Meta looks good (using Yoast SEO), it's 'just' the text on the share post itself that has this sign. I understand it's probably due to some file not encoded in utf-8. I've added `default_charset = UTF-8` to my `.ini` file but no change. The `content-type` is also properly set to `utf-8` I've also did a validation check on w3 validator and didn't find anything related The website shows up just fine with no weird characters, it's only when trying to share a post on Facebook. How can I find the source for the wrong encoding ?
I've found the issue. UTF8 might produce a multibyte string (when using Hebrew characters for example). Facebook truncates this string a post is shared to keep the description under max number of characters. However, they might truncate a multibyte character in the middle which will result in UTF8 invalid character: This issue actually reproduces in all multibyte websites. The only workaround I've found is limiting the `og:description` to Facebook's max number of characters (about 110 in comment and 300 in post) I've submitted a bug to Facebook OpenGraph platform and I hope it will be fixed shortly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "open graph" }
Wordpress Redirect / Add_Rewrite_Rule - Non Index.php Page Trying to redirect visitors from `www.domain.com/abc`to `www.domain.com/company/?code=abc`, After some research and some messing around, I am currently using the code below, which doesn't work. I flush the permalinks after each attempt. function custom_rewrite_basic() { add_rewrite_tag('%code%', '([^&]+)'); add_rewrite_rule('([A-Za-z0-9]+)$', 'company/?code=$1', 'top'); } add_action('init', 'custom_rewrite_basic'); My .htaccess page updates, and is the following: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^([A-Za-z0-9]+)$ /company/?code=$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress Can anyone identify the issue?
If `company` is the page slug try 'index.php?pagename=company&code=$matches[1]' If you want it in .htaccess to intercept it before it goes to index.php try 'index.php?pagename=company&code=$1' If `company` is a folder, there should be an index.php (or whatever the default file name is for your server) inside it that will process `code`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, redirect, htaccess" }
Child theme CSS not applying to element I'm working on a child theme for a client and I have a few overriding styles. However, they're not even showing up in the Chrome inspector. For example if you go to this page: < and click on "Sign up", I'm trying to override the header background-color. Look at my CSS file here: < Last line. Any help is greatly appreciated. This is happening on more than just this page.
Remove the marked '{' from line 295 of your child theme styles.css file. Check the bellow image to be sure what to remove. ![Remove the marked '{' from line 295 of your child theme css.](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "css, child theme" }
how to link to detail page(single.php?) in a wp_loop I have made wp_query like below. This is some part of them. And it works. $args = .....; $query = new WP_Query($args); while($query->have_posts() ) : $query->the_post(); ?> <div class="each"> <h4><?php the_title(); ?> </h4> </div> <?php endwhile; wp_reset_query(); ?> This shows like this. <div>title 1</div> <div>title 2</div> <div>title 3</div> ... At this point, when I click one of the titles, it needs to link to the details of the clicked post. But I don''t know how to link to the detail page. I think it should be linked to 'single.php'. is this right? and how to link to that detail page(maybe singles.php)? thank you.
Replace with below code : <?php $args = .....; $query = new WP_Query($args); while($query->have_posts() ) : $query->the_post(); ?> <div class="each"> <h4><a href="<?php the_permalink();?>" title="<?php the_title_attribute();?>"><?php the_title();?></a></h4> </div> <?php endwhile; wp_reset_query(); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query" }
Custom font size nav bar I'm trying to increase the font size on my nav bar. I'm using Monstroid2. < I'm guessing I'll need to add custom css somewhere. Can anyone help?
your current activate theme style.css in put this css .main-navigation ul li a { font-size: 16px !important; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, menus" }
wp-config.php modified? This might be a broad topic but I am searching and reading but not able to clear my doubts, please advice in answer or links from where I can understand about how codes are injected to WP by attackers. While clicking on site name from google search it was taking to spam links. After doing some scanning I found there was plugin < we were using which was outdated. And in wp-config.php there was some code like below screenshot : ![enter image description here]( Is that means site got hacked ? I have performed all required updates or core and plugins etc and gone thorugh Verifying that I have fully removed a WordPress hack? Is that kind of code means site is hacked. We are on shared hosting Bluehost. I am not sure if that code is due to hosting installation process. I have gone thorugh video < as well. Please give some valuable thoughts if thats malicious code and how is malicious code like this normally injected into WordPress pages? Thanks!
Once hacked there is no real (at least not easy) way to verify that you have removed all traces of the malware. Good malware will leave an hard to detect backdoor, and there is always the question of whether you have actually removed the attack vector. Therefor the only 100% working way to remove a malware is to revert to a known good backup first, than improve your security. It seems like your core security failing is to let the webserver to write to your config (and I assume also code) files. This is just going to make it harder for you to avoid being hacked again with the next software bug.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "security, hacked" }
Javascript not loading after the document ready if ( ! function_exists( 'loadingscripts' ) ) { function loadingscripts() { // Register the script like this for a theme: wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true ); wp_enqueue_script( 'custom-js' ); /* Load the stylesheets. */ // wp_enqueue_style( 'fontawesome', THEMEROOT . '/inc/lib/fontawesome/css/font-awesome.min.css' ); wp_enqueue_style( 'layout', THEMEROOT . '/css/layout.css' ); wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css' ); } } add_action('wp_enqueue_scripts','loadingscripts'); I think the Javascript is loading before the DOM because in its pure HTML version I was loading the javascript in the footer, but in the WordPress conversion, it doesn't work. What is the fix?
Javascript runs as soon as it's loaded, you need to wait for the DOM ready event, and you do that in JS, not in WP: jQuery(document).ready(function(){ /* your code here */ });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, javascript" }
echo a specific custom taxonomy term on a different custom taxonomy archive I'm not having much luck trying to find anything to help with this... I have a custom taxonomy('XYZ') archive all the posts in this archive also have an other common custom taxonomy('ABC'). I'm looking for a way to echo the other custom taxonomy similar to `<?php single_term_title(); ?>` something like `<?php single_term_title_ABC(); ?>` Does this make sense?
To get the terms applied to a post from a certain taxonomy, use `wp_get_post_terms`. Inside the loop add: $abcterms = wp_get_post_terms( $post->ID, 'ABC'); foreach($abcterms as $abc) echo $abc->name;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
WP-CLI Get Site ID from its url I know I can get a site list with wp site list --path="$pathtowordpress" What I want to do though is get one site's ID by knowing only it's url. Does anyone know if this is possible ? Tnaks.
It looks like `--url` isn't working to filter the `wp site list` output. So instead one could try: wp site list | awk '{ if( $2 == SITE_URL_STRING ) print $1; }' where we use the `awk` trick from here, to filter the `url` column and display the `blog_id` column. Here we must replace `SITE_URL_STRING` with e.g. `" _Update:_ Here's a bash example to find the exact site url string: #!/bin/bash site_url=" wp site list | awk -v site_url=$site_url '{ if( $2 == site_url ) print $1; }' where we use the `-v` option to pass a shell variable to awk. Got that idea from here.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp cli" }
Make logo dynamic in wordpress I have a problem with my wordpress site logo. I cannot make the site logo dynamic. here is my code (displaying logo) which is in header.php page: <a href="<?php echo get_home_url(); ?>" id="logo"> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/logo.png" class="img-responsive" alt="" title=""> </a> ***** when I want to change it from Customize > Site Identity, here it shows that no logo is attached, yet the logo is displaying successfully at front-end. Even when I try to change it, nothing happens. Kindly help me to solve this issue.
Theme header logo function `get_theme_mod( 'custom_logo' );` $custom_logo_id = get_theme_mod( 'custom_logo' ); $image = wp_get_attachment_image_src( $custom_logo_id , 'full' ); echo '<img class="header_logo" src="'.$image[0].'">';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development" }
Change recent posts widget title How can i change the recent post widget title programmatically? I use this code in my footer.php to add recent posts widget. <?php the_widget( 'WP_Widget_Recent_Posts' ); ?>
I had a similar situation. Add the following code to your functions.php and see if it works for you. function my_widget_title($title, $instance, $id_base) { if ( 'recent-posts' == $id_base) { return __('New Title'); } else { return $title; } } add_filter ( 'widget_title' , 'my_widget_title', 10, 3); > Note: this will change the title of all the "Recent Post" widgets.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets, recent posts" }
Can I upgrade a plugin to a specific version? I am testing plugin upgrades on a staging instance before applying them to production. But if there are any delays in this process, I may end up being prompted to upgrade to a newer, untested version on production. If prompted to upgrade a plugin, how can I choose an intermediary update, rather than the latest?
Using WP-CLI you can specify this as described in the official documentation. $ wp plugin update <plugin> Using either of the following arguments --minor > Only perform updates for minor releases (e.g. from 1.3 to 1.4 instead of 2.0) --patch > Only perform updates for patch releases (e.g. from 1.3 to 1.3.3 instead of 1.4) --version=<version> > If set, the plugin will be updated to the specified version.
stackexchange-wordpress
{ "answer_score": 26, "question_score": 15, "tags": "plugins, updates, upgrade" }
Configuring WordPress Auth Cookie Expiration I'm trying to configure the WordPress cookie expiration time, but for some reason it's not working. I went here: < And put the following hook based on the doc: function init() { // ... $expiration = 60; apply_filters( 'auth_cookie_expiration', $expiration ); } This code is called from a hook in my plugin's constructor: add_action( 'init', array( $this, 'init' ) ); And I have verified that it runs. I expected this to produce a cookie that expires in 60 seconds, but it doesn't. Instead it sets a regular expiration time of 48 hours (WP default). I suspect this might be because when the user actually logs in, it doesn't create this expiration date, and running this function later has no effect. I haven't yet figured out how to make it work though. Any help appreciated.
Note that you're not adding any filter callback with: apply_filters( 'auth_cookie_expiration', $expiration ); Instead use: add_filter( 'auth_cookie_expiration', $callback, 10, 3 ); where `$callback` is the appropriate filter callback that modifies the expiration. Here's an example add_filter( 'auth_cookie_expiration', function( $length, $user_id, $remember ) { return $length; // adjust this to your needs. }, 10, 3 ); or to fit with your current class setup: add_filter( 'auth_cookie_expiration', [ $this, 'set_auth_cookie_expiration' ], 10, 3 ); where `set_auth_cookie_expiration()` is the appropriate method, e.g.: public function set_auth_cookie_expiration ( $length, $user_id, $remember ) { return $length; // adjust this to your needs. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugin development, cookies, authentication" }
What tools respect `.distignore`? You can create a plugin using the `wp scaffold plugin PLUGINNAME` command. It creates a bunch of files, including `.distignore`, `.editorconfig`, `.gitignore`, `.travis.yml`. Here is the contents of `.distignore`: # A set of files you probably don't want in your WordPress.org distribution .distignore .editorconfig .git .gitignore .gitlab-ci.yml .travis.yml .DS_Store Thumbs.db behat.yml bin circle.yml composer.json composer.lock Gruntfile.js package.json package-lock.json phpunit.xml phpunit.xml.dist multisite.xml multisite.xml.dist phpcs.xml phpcs.xml.dist README.md wp-cli.local.yml yarn.lock tests vendor node_modules *.sql *.tar.gz *.zip My question is: what tools recognise `.distignore`? Are they just wp-cli commands that recognise it? Do some online hosts like WP Engine recognise it?
This is file for WP CLI. the command `dist-archive`: wp dist-archive . Note that you need to install both WP CLI and this plugin: wp package install wp-cli/dist-archive-command
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "wp cli" }
Still relevant method of embedding images in WP Theme in 2018 <img src="<?php echo get_bloginfo('template_url') ?>/images/logo.png"/> Is the above still a relevant method of embedding images in the Wordpress theme or an obsolete? If obsolete then what will be the correct method? someone questioned me today that I am not doing it correctly?
> someone questioned me today that I am not doing it correctly? <?php echo get_bloginfo('template_url') ?>/images/logo.png There are 2 possible reasons this could be considered 'incorrect': * `get_bloginfo` is a very old function that does multiple things, this particular function was replaced by `get_template_directory_uri` and `get_stylesheet_directory_uri` * Security! You didn't escape anything! The entire thing should be wrapped in an `esc_url`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, bloginfo" }
wp-json and what data does it give away? I just discovered `/wp-json` and it seem to give away some unwanted information. The entire json file is too big to scan everything so I decided to ask a question. One particular thing I am concerned about is, it gives away user slug. Which kind of seem unnecessary to publish user id of site author. Should I be concerned or it is pretty common thing? What other information does it give away? Should I be concerned and take any precautions? Thanks.
`/wp-json/` is the base part of the Wordpress REST API < An authors ID isn't a big deal. I would imagine on your theme, every time the post authors name shows, within the HTML showing the name, there'd be element classes containing the authors ID. It's normal to have shown in publicly viewable source code, and it's easy to discover "hack" an id by simply making a query on your site `/?author=x` and manually mapping IDs to usernames. The link above details the REST API, and what it does and can show. I'm over simplifying it, but: the REST API acts as basically your entire Wordpress site, in JSON format - with availability to query and do specific things. If nervous about the API and not using it, it's easy to remove.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "security, rest api" }
Modular theme settings I'm looking for advice on the best way to store a series of settings for a modular theme. To note: * The settings will not be user facing (not suitable for the customiser api). * Ideally the options would not be stored in the database as they will be static (for performance). * The theme is not public, it will be used as a framework for multiple sites. I have discarded `add_option` / `get_option` which uses the database, and likewise for `get_theme_mod` / `set_theme_mod`. Am currently using a global scoped array - which is not ideal (from what I read). Any other thoughts / suggestions?
If a user can not change them then they are not options, they are constants. Declare them using `const` in your maim theme file (probably `functions.php` but any other files that is being always loaded will do), and use them wherever you have use the "options" array now. If you want to control it without editing you theme files, you can use a conditional `define` instead (check if value is not defined yet and if not define it). That way you will be able to override the default values by defining them at the `wp-config.php` file per site. ... But this all question sounds wrong. The DB is there, so just use it, and a basic UI to control the options is easy to come up with. There is no real reason to resort to code changes every time you want to active/deactivate a module.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "theme development, options" }
getting post thumbnail within loop causes an error I have this code that I've been using to pull images from my posts: while ( $query->have_posts() ) : $query->the_post(); if (has_post_thumbnail()){ $nevent .= '<a href="'.get_permalink().'">'.get_the_post_thumbnail($post_ID,'full', array( 'class' => 'greenbg' ) ).'</a>'; } else { $nevent .= '<img class="wp-post-image" src="'. get_stylesheet_directory_uri().'/images/node-summit-event-logo.png" alt="'. get_the_title().'"/>'; } $nevent .= '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>'; $i++; endwhile; The code works and shows my image and post titles, but i get an error: > Notice: Undefined variable: post_ID in /home/nodesummit/public_html/wp-content/plugins/rt-cpts/events.php on line 671 Can a kind person please let me know what I'm missing?
The `get_the_post_thumbnail()` internally uses the `global $post` to get the post ID. That is why the code works while you are getting errors. it's not required to pass the post ID to this function, so you can pass `null` to it. But the error is because there is no defined `$post_ID` variable. If you want to get the post's ID, you should either use `global $post; $post->ID;`, or better use `get_the_ID()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, post thumbnails" }
Change pricing in Woocommerce based on Category and Product I am new to Woocommerce and PHP and I'm trying to create a product page exactly as on this site < i.e. it should be a 2 step checkout. On the first page I can choose the box and pick my plan and the price should get updated accordingly. On the second page I can fill the checkout form and pay. I have tried searching plugins for this conditional logic but couldn't find any where. Is there a plugin for Woocommerce which can help me make this kind of product page or it is only possible by coding in PHP?
Think of this page: < as your single product page. On click of "proceed to payment" you are effectively adding the product to the basket with your selected options (a variable product) and going direct to checkout to fill in the form. You won't be able to get the desired effect as your example site without a little development knowledge.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, plugin development, woocommerce offtopic" }
Hide terms if they aren't the same as the current term This snippet shows all terms within the custom taxonomy 'state'. This snippet is in my taxonomy.php. I'd like to hide all the terms that don't have the same term as the current term page being viewed. $terms = get_terms( array( 'taxonomy' => 'state', 'hide_empty' => true, ) ); $sep = ''; foreach ( $terms as $term ) { if( ++$count > 60 ) break; // number of tags here. echo $sep . '<a href="'.get_term_link($term).'?suburb=armadale">'.$term->name.'</a>'; $sep = ', '; // Put your separator here. }
If you are on a term archive page, you already have the term object available to you via `get_queried_object`: $term = get_queried_object(); echo get_term_link( $term ); echo $term->name;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
how to save wp_editor html content in options table wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) ); submit_button('Save', 'primary'); I want to create a mail template where admin can change content and put shortcode where he wants. created a form and wrote the code above but when I click on save it not save the HTML formatted content. please help any one
echo '<form action="" class="booked-settings-form" method="post">'; $default_content='<p>Mail formate</p>'; $editor_id = 'customerCleanerMail'; $option_name='customerCleanerMail'; $default_content=html_entity_decode($default_content); $default_content=stripslashes($default_content); wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) ); submit_button('Save', 'primary'); echo '</form>'; if(isset($_POST['customerCleanerMail']) ){ $var2=htmlentities(wpautop($_POST['customerCleanerMail'])); $fff=update_option('customerCleanerMail', $var2); } In form section i used wp_editor with his options, wp_editor work like html editor but when you store these data it not storing html data. so we found solution how to store html data wpautop() and htmlentities() both two functions help to store html formated data
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, customization, wp editor, options" }
height should be set to auto to avoid pixelation in the post thumbnail function The code in question → <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?> The generated output in **browser** is like this → <img width="1620" height="973" src="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg 1620w, 300w, ....../site04/wp-content/uploads/2018/01/audi_ileana-768x461.jpg 768w, 1024w" sizes="(max-width: 1620px) 100vw, 1620px"> # Anticipated result → I want that height should output as "auto" value. * * * **I tried this:** <div class="pimg"> <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?> </div> and its css: .pimg img {max-with:100%; height:auto;}
You can use a filter to remove height and width attributes from images, as explained in this CSS Tricks. Place the following in your themes `functions.php` file. add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 ); add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 ); function remove_width_attribute( $html ) { $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); return $html; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, css, post thumbnails" }
Preventing BFA in WordPress without using a plugin I use Ubuntu 16.04 Nginx environment and **SSHguard** to prevent Brute Force Attacks (BFAs) on the machine VPS environment itself but I'm not sure how I could prevent BFAs on WordPress without using a plugin. Unlike Drupal that has an application layer BFA prevention mechanism, WordPress has none. What is the most minimal way, without a "complex" plugin like WordFence, to prevent BFAs in WordPress admin? The end state should be that IPs trying to enter more than x times get blocked for at least x time (presumably, the default values). **Edit: Maybe SSHguard could help with that too?**
One **_plugin-free_** layer of protection you could implement is to route your traffic through a site like CloudFlare that has built in brute force protection. The free version is a great layer of protection with paid tiers if you need the added features. I have used this for several of my sites. I am with you in that I try to use as few plugins as necessary. *note: felt this would have been better as a comment but _did_ not have the necessary reputation.*
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, customization, security, password, server" }
Do I need to use the esc_html() function on hard coded links? I understand when using certain WP functions like site_url(); you should escape these with the esc_html(); function in the following manner: <?php esc_html(site_url()) ?> My question is, if I have inputted the site url manually in a template file such as front-page.php like this: <a href="//mysite.com">My Site</a> Do I still need to use the esc_html() function? It doesn't mention anything about this use-case in the docs. And if so how do I go about this? Many thanks
Nope, you don't need to escape hard-coded URLs.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "security, links, site url, escaping" }
Is there a name for trivial WP PHP files like functions.php, archive php entry.php, page.php and so forth? Is there a name for trivial WP PHP files like functions.php, archive php entry.php, page.php and so forth? Is there a "category" (in the general sense of the term) they all fall into? I want to know how to name them so I could read about them so I could figure our which of them is actually mandatory in the latest versions of WordPress.
They don't have a special name, they are just theme / template files. If you want to read more about them in general, see template files in the codex. The template hierarchy is also something you'll need to know about, it explains what file gets chosen when.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, theme development, wp filesystem" }
Can I get some product is virtual in Woocommerce by hook? I custom a tab in panel (post.php page) like this: ![enter image description here]( But I want to hide it if it isn't virtual product. And if it is virtual product, show it. I don't know how can I get the value of product which is virtual or not.
call this on product-page template where you want to handle icon or tab: <?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $post, $woocommerce, $product; if ($product-> is_virtual('yes')) { // your logic to display tab or image etc }else{ // your logic not to display tab or image etc } ?> follow this link for details For more related details see this link and this one Hope this will give you idea and help! According to comment to get product type with ID : For details $product = get_product(619); echo $product->product_type;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Is "the loop" a template tag? Template tag is defined the following here: > Template tags are used within themes to retrieve content from your database. **The loop** retrieves (posts) content from database in templates, so it seems she would fall in that category. Hence I ask: Is "the loop", the loopish function that shows posts while we have posts, based on if we have posts, should actually be considered a a template tag?
The `Template tag` is just a name chosen for a variety of function. It doesn't really matter what you call them, and they are functions. However, the `while( )` loop itself is a simple PHP feature. It uses the `have_posts` method of the `WP_Query()` class to detect whether there is any posts to display or not. The main query itself is already set when you load a page, which can be accessed via `global $wp_query;`. So, putting all together, this can be an opinion based question. The `WP_Query()` class doesn't exists in the File section of Template Tags page, so I would call it a _"No"_.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, templates" }
Custom Post type in Author.php Please i have been battling this issue for days now... I want to display custom post types in author archive and was able to get this code to display them earlier today: add_action( 'pre_get_posts', function ( $q ) { if( !is_admin() && $q->is_main_query() && $q->is_author() ) { $q->set( 'posts_per_page', 10 ); $q->set( 'post_type', 'design', 'accessory'); } }); The post types in the field above is my custom post types. The problem now is it only displays one of the post types(design). Please any help will be greatly appreciated. Thanks
You need to pass the post types as an array, not each as its own argument. $q->set( 'post_type', ['design', 'accessory']); // ^ ^ Or if you're on older PHP systems $q->set( 'post_type', array('design', 'accessory'));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types" }