INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I duplicate categories and tags? Is there a way to sync categories and tags? I want a way that every post will have a tag that is the same as the category or categories that its in.
add_action( 'save_post', 'add_tag_based_on_category' ); function add_tag_based_on_category( $post_id ) { $args = array( 'fields' => 'names' ); $categories = wp_get_post_categories( $post_id, $args ); $cat_names = implode( ', ', $categories ); wp_set_post_tags( $post_id, $cat_names, true ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, tags" }
Category name as page title I'm using a theme from Envato Market (Painting). What I need to do is to replace a generic page title which is displayed when I open a category page from Shop or Portfolio, with the actual name of the category. The developer of the theme said that I can’t dynamically display the title. But in the same time I see that the breadcrumbs shows the correct title of the category. Could the page title be grabbed from the breadcrumbs and displayed? Or maybe there is another solution. Can someone help me and explain it for a noob? Thank you!
You can change the code in the theme files to do this. Open the file `category.php` (if this file doesn't exist, try `archive.php`) and replace the text you want to change with `single_cat_title()` Here is the documentation **However these changes will be overwritten if you update your theme** You can create a child theme or use plugins to get around this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, title, breadcrumb" }
How to make Pull Requests on a wordpress.org plugin? How can I submit pull request to other's plugin, which is hosted at **wordpress.org**?
No, the wordpres.org SVN repositories are not for development and there are no plans to change this. So you either have to ask on support forum, or if the plugin is on an open GIT repository search for it on GitHub.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "plugins, repository, plugin repository" }
wordpress.com website url structure Should I able to change URL structure of WordPress blog? (Free WordPress hosted blog) Right now I have this way: (see URL structure) helloworld.wordpress.com/london But I want to use as this way: helloworld.wordpress.com/carhire/uk/london Is this achievable?
Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area. There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/) /carhire/uk/%postname%/ If your logic is more complex, I suggest using a plugin such as Custom Permalinks. **Edit:** I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, htaccess, wordpress.com hosting" }
How to Implement "Notice: This theme recommands the following plugin:xyz" in wordpress? how to add list of plugin that recommended for the theme to run. see below image: ![in this the theme recommend me to install :*kirki* ](
TGM-Plugin-Activation library is the best choice for installing required plugin. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "plugins, themes, plugin recommendation" }
How to get a list of users who like a current wordpress post I am using this post like system in my WordPress theme and its working fine. My WordPress theme is only for registered user, i mean only registered user can read my post. Now want to display all users list who liked the post in single page under any specific div. can someone help me with a solution? thanks
According to the code samples in the article `_user_liked` post meta should hold all the user ids of those who liked it. Something like this should be able to solve it for you <?php $post_id = get_the_ID(); $users_liked = get_post_meta( $post_id, '_user_liked', true ); if ( '' !== $users_liked && ! empty( $users_liked ) ) { ?> <ul> <?php foreach ( array_values( $users_liked ) as $user_id ) : $user = get_user_by( 'id', $user_id ); if ( false === $user ) { continue; } ?> <li><?php echo $user->user_login; ?></li> <?php endforeach; ?> </ul> <?php }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How i can extract data Hello i have form with nested repeater field, all data in nested repeater group saving in database like this: `a:6:{i:0;a:4:{s:5:"title";s:21:"Initial ";s:11:"description";s:78:"Please show identify.";}}` in database all ok, but how i can get title value, description value, when i try `get via get_post_meta`, for example: `get_post_meta( get_the_ID(), 'part_0_module[0][title], true )` \- nothing, `part_0_module[0][title]` \- this my field name. Can you help me solve this problem and get data?
You should use unserialize() function to access data. For example: <?php $data = get_post_meta( get_the_ID(), 'field_name', true ); $data = unserialize($data); // Print the data print_r($data);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "array, post meta" }
Woocommerce: order posts by meta key I have the following args array { "ordreby":"meta_value_num", "meta_key":"_price", "posts_per_page":10, "offset":0, "post_type":"product", "post_status":"publish", "order":"asc", "suppress_filters":false, } when i do $myposts = get_posts($args); the order by **_price** (or other meta keys) is not working. any idea?
Change `"ordreby":"meta_value_num"` for "orderby":"meta_value_num" a dyslexic error xD
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, woocommerce offtopic, post meta, get posts" }
CSS in child theme isn't working properly I am trying to get a child theme to work. At first it didn't load because it didn't recognise it as a child theme. Now it does work but when I activate it, it loads a version of my page seemingly without any css or something. There's only text and images there, but no styling. Is it that it isn't using the parent theme fully or something? I am just starting with Wordpress so I'm sorry if I'm not very clear or using the right terminology. Thanks in advance. This is my functions.php file: <?php function my_theme_enqueue_styles() { $parent_style = ‘twenty seventeen-style’; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?>
You'll have to enter that code at the start of the functions.php file in your child theme to include the parent theme's `style.css` file <?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } visit this page for more information
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, css" }
How do I move the sidebar more to the right in TwentySeventeen? I have tried adding this to `style.css`: .sidebar, .widget-area, .secondary { position: absolute margin-left: 120px; max-width: 250px; } But it won't move. If I remove `position:absolute`, it is pushed down, getting under all the other content.
You have 2 options: **Option 1.** Just add negative margin to the sidebar CSS like this: @media screen and (min-width: 48em){ #secondary{ margin-right:-150px; } } **Option 2.** Add more max-width to the wrapper: @media screen and (min-width: 48em){ .wrap{ max-width: 1340px;//the default is 1000 padding-left: 348px;//you have to add padding left so the left side doesnt move, the amount needs to be proportional to the amount of max-width you are incrementing } } i added the media query, its needed so this CSS doesnt affect the mobile view.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "sidebar, theme twenty seventeen" }
how to show all post in my page-grid.php template page I have custom my template and trying to convert my html into wordpress template, i have created one page page-grid.php .and i want to show all my post with images .but don't know how to do this .and where to put my scripts.my html is having diffrenet background color whenyou scoll all post. can anybody help guide me?
<?php $args = array( 'post_type' => 'put your custom PostType name here', 'posts_per_page' => '-1' ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // Contents of the queried post results go here. } } // Restore original post data. wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, pages, templates, page template" }
How to hide few theme customization options - TwentySeventeen theme I am just trying to modify Twenty Seventeen theme by and I want to hide few customize options like **Header Media** and **Colors** how can I do it ? ![enter image description here]( I have researched it but it seems like the given options are unable to hide these menus. Can someone give me a hook or something to be able to hide this please. Thanks
You can change `active` status of section using `customize_section_active` `filter`. It gives 2 parameters `$active`-`bool` and `$section`-`object`. Haven't tried it so you can try and see if works for you. Located in `\wp-includes\class-wp-customize-section.php`, for your research. As second option you can try altering capability for the section. Note: I'm just giving options, and have not done any of these before. So not sure about it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme customizer" }
Update WP option by plugin I wanted to set value of **WP option** (more specifically - 'admin_email') by using plugin, **its option** (plugin option) and update_option(). I tried using lines like below, but when plugin code contains them - it gets disabled. Any ideas why? $helper = (get_option('plugin-option'); update_option('admin_email', $helper ); **EDIT** $helper = get_option('plugin-option'); update_option('admin_email', $helper ); Now it's not disabling (due to bracket), but it still doesn't change option value
That option is special in that WordPress has code to intercept your call for security reasons: < > This function intercepts changes to the administrator's email address. It keeps the address from being updated and instead sends the user a confirmation email, with a link to confirm the change. What you're trying to do could be easily abused, and any change of the administrators email should trigger notices as a basic security measure. Luckily the documentation for that function also includes an example on how to bypass it
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, options, settings api" }
Primary menu shortcode name I have a shortcode that will put a menu where I want it, but it only works on the primary menu. I don't want to use the shortcode for the primary menu, I would like to create a new menu called shortcodemenu and have the shortcode call it when it is used. function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts)); return wp_nav_menu( array( 'menu' => $name, 'menu_class' => $class, 'echo' => false ) ); } add_shortcode('shortcodemenu', 'print_menu_shortcode');
You basically have everything set. You simply need to call the shortcode: [shortcodemenu menu="slug-of-your-menu"] Remember to use the SLUG of the menu you want to show instead of its name.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, shortcode" }
Hardcoded paths in my plugin Sorry for the stupid question: I'm trying to create a basic plugin and from its main file I want to refer files in two directories that are in the same directory as the main plugin. I tried to reference them this way: `plugin_dir_path( __FILE__ ).'js/my.js'` or `plugin_dir_path( __FILE__ ).'imgs/myImg.jpg'` but it crearly creates a path that doesn't work for me. Anything works fine if I hardcode the absolute path, so this is working fine: < No luck with relative paths too. What's the best way to avoid hardcoding my paths? :-)
You want to use `plugin_dir_url()`: $url = plugin_dir_url( __FILE__ ) . 'js/my.js';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, paths" }
What is this mark for "? function()" I was working through someone else's code trying to understand their plugin so I could combine it with another plugin to do something different. I have no clue why this question mark is here in the middle of this entry. The code appears as such in one line: `$variable = !empty( $_POST['variable_b'] ) ? explode( "\n", trim( $_POST['variable_b'] ) ) : array();` I understand what the empty, explode, and trim functions do here. I assume that is all being amended to the array. The question mark almost seems like a mini conditional statement.
That's called Ternary Operator. if( ! empty( $_POST['variable_b'] ) { $variable = explode( "\n", trim( $_POST['variable_b'] ); } else { $variable = array(); } You can see PHP Shorthand If/Else Using Ternary Operators (?:) for more details.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "php, plugin development, array" }
How can I get users email (and additional data) from the rest API? How can I get the email adress from the users by using the REST API? I'm authenticating with nonce, and it seems to be working since I can do POST requests and change stuff. Do I have to add something to make it return all the user info? This is my JS: (function($) { var nonce = WPsettings.nonce; var rest_url = WPsettings.rest_url; $.ajax( { url: rest_url + 'users/', dataType: "json", beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', nonce ); } } ) .done( function ( response ) { console.log( response ); } ); })(jQuery);
To add the user's email address in the REST API response, register an additional field to the `user` object and add the email address: register_rest_field( 'user', 'user_email', [ 'get_callback' => static function (array $user): string { return get_userdata($user['id'])->user_email; }, ] ); Please note, however, that this is _strongly_ discouraged because anyone can then see the email addresses if the code is running on a publicly accessible website.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "users, email, rest api, endpoints" }
Reduce nonce lifespan for a personal plugin (nothing going to the public or commercial), I built an AJAX form and its endpoint is a custom endpoint (REST Api). When a certain Page containing my form is accessed, I generate a nonce. Then, the user sends the form, I add the conventional header (`X-WP-Nonce`) and in the endpoint function I validate the nonce I first created when the page was loaded. I would like my nonce to be short-lived, that is, 12 hours is too much. I found I can use `apply_filters('nonce_life', timeHere)` but I don't know where this line is supposed to be: should it go right before this one? $nonce = wp_create_nonce('wp_rest'); Moreover: could this line change the lifespan of ANY nonce in my WP or does the change affect only my nonce? I wouldn't want to break other plugins. Thanks!
Yes, using that filter will affect the lifespan of all nonces created after this filter is added, and while it remains in-place. So your best bet is to add it, create the nonce, remove it: function my_nonce_lifetime() { return 600; // 10 minutes } add_filter( 'nonce_life', 'my_nonce_lifetime' ); $nonce = wp_create_nonce( 'wp_rest' ); remove_filter( 'nonce_life', 'my_nonce_lifetime' ); EDIT: As suggested by someone in the comments, you'll need to use the same filter later on when you're verifying the nonce, as below: add_filter( 'nonce_life', 'my_nonce_lifetime' ); wp_verify_nonce( $your_nonce_value, 'wp_rest' ); remove_filter( 'nonce_life', 'my_nonce_lifetime' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, rest api, nonce" }
Settings API and 'type' => 'font' array( 'name' => 'textarea', 'label' => __( 'Textarea Input', 'wedevs' ), 'desc' => __( 'Textarea description', 'wedevs' ), 'placeholder' => __( 'Textarea placeholder', 'wedevs' ), 'type' => 'textarea' ), Just like in the above example the `'type' => 'textarea'` what is its equivalent for a font? I tried → `'type' => 'font'`; but that didn't work.
There is no field in HTML called font. You need to create select dropdown. Also change it's name for uniqueness.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "options, settings api, fonts" }
How to customize the author page in wordpress? Actually am getting the author URL by `get_author_posts_url($authorID)` It is redirecting to some page like < So on this page, I need to do some extra modification, couldn't figure out which template.page to edit. I searched `author-template` in wp-includes but did not find a way to customize the page. So please guide me how to customize that page?
It is not possible to answer without looking at the codebase of your theme. You may need to edit the author.php file. If that file does not exist in your theme, look for the next file in the hierarchy. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, author, author template" }
How to check if a post is published today? How to show something if a post is published today? Like this: The Post. _new_ The Post. _old_
You can use `get_the_time()` to get the date of the current post. Just use a format that only includes the year and date, and compare it to the current date using the `current_time()` function with the same format: if ( get_the_time( 'Yd' ) === current_time( 'Yd' ) ) { // Post was published today. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Configuring WP-CLI on Windows 10 I've installed `php5-cli` using bash, but Wordpress is using XAMPP's PHP 7 install. I've added `/mnt/c/xampp/php` to the PATH, and I've explicitly used `export WP_CLI_PHP='/mnt/c/xampp/php'` in `.bashrc`. But when I do `wp --info`, I get: PHP binary: /mnt/c/xampp/php/php.exe PHP version: 5.5.9-1ubuntu4.22 php.ini used: /etc/php5/cli/php.ini `PHP binary` seems correct, but the last two variables refer to PHP 5.
Actually, I figured out how to do this, and it's actually really easy to do! Which is awesome because I think it's a great simple way to work! First up, you don't want to change the PATH for PHP in bash. So you'll want to remove that. Instead, what you are doing is using bash based PHP and MySQL, but connecting to your Windows MySQL (installed by XAMPP). **Step 1:** `sudo apt install mysql-client php-cli php-mysql` **Step 2:** Create a symlink in bash to your website files, so something like this: `sudo ln -s /mnt/c/websites /var/www` **Step 3:** You need to connect to you MySQL db with an IP address, not localhost. So when creating your config do something like this: `wp config create --dbname=wpdbname --dbuser=wpdbuser --dbpass=securepswd --dbhost=127.0.0.1` If you want more info, I also wrote a blog post about this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, wp cli" }
How to use mhchem in wordpress? I need to write chemical formulae in WordPress posts. For this I want to use mhchem package. I am open to use a plugin for that but there seems to be none in WordPress.org repository. As mentioned here, mhchem extension can be enabled in mathjax configurations by adding following to the extensions array in the TeX block. TeX: { extensions: ["mhchem.js"] } I am able to load Mathjax on my server (usingMathjax-Latex Plugin.) Since Mathjax is available on my server, I hope mhchem package can be used through above mentioned tweak in Mathjax, but can't figure out where and how? I have asked for help on the Mathjax-latex Plugin support forum but got no response even after a year. Any help in this regard is welcome. It would be fine for me no matter it is through Mathjax-Latex Plugin. or otherwise.
The Mathjax plugin provides a filter named `mathjax_config` that can be used to add config parameters, something similar to this should do the trick: add_filter( 'mathjax_config', function() { return ['Tex' => [ 'extensions'=> [ 'path/to/mchem.js'] ] ]; }); In the event you'd like to remove dependency on the plugin, you'll need to enqueue the mathjax library, whitelist all the relevant tags so they aren't
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugin mathjax" }
I lost the link to my posts in my menu bar I lost the link to my posts. Originally, when I went to "all pages" one would show up as "posts." Therefore it would show up in the menu bar. I think when I set up my site, I wanted to change the posts page to show up as "articles" or "news" instead of "home" in the menu bar. But when I tried to change that I must have screwed something up in the code, or deleted that page or link or something? "Posts" no longer shows up in my list of pages. My theme is set so that the front page or landing page is the "latest post." So if you go to my site, yes, the latest post is there. However, if you click on any other page on the site, there is no way - in the menu bar- to get back to the posts. I would like a drop down menu of the posts to be there. I did put a widget in the side bar that lists the latest posts but I would like it in the menu bar as well. Did I do something wrong? Can I get it back? Thank you Thank you!
I'd check/adjust the Menu (under Appearance, Menu; also usually within Appearance, Customize). Create a menu if not already there. Then add a "Custom Link" to the menu. The URL is your home page, the Link Text is something like "Home". Drag that menu item to the spot on the menu (the vertical list of all the menu items). Once you save the Menu, use the "Manage Locations" tab to assign it to the menu area the theme uses. Add additional menu items as needed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, menus, pages" }
Redirect only Blog posts to new I have Copied over all blog posts to a new domain. I would like to create redirects for all blog posts to new URL but keep the pages as they are. Is there a wildcard Solution for this?
What you'll want to do is, check if it is a post via `is_single()`, get the current URL (or at least that part after the domain), and redirect to the new domain. Here I am using `parse_url()` to easily differentiate between host, path, etc. add_action('template_redirect', 'wpse_redirect_posts_to_new_page'); function wpse_redirect_posts_to_new_page() { // if this is not a single post or not of type post, do nothing if ( ! is_single() || get_post_type() != 'post') return; $url = parse_url(get_the_permalink()); $newdomain = ' // no trailing slash! wp_redirect($newdomain . $url['path']); exit; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect" }
How do I remove search bar that isn't a widget? I'm a newby and don't have much knowledge of programming. My website is < I'm using the Divina theme and I can't figure out how to remove the search bar. I tried to see if it's a widget but it appears to be hardcoded into the theme. It shows up under the menu I put in. Can somebody explain to me in very specific terms how to fix this? I'm using a plugin called advanced code editor but I really don't know what I'm doing. I tried putting in a show: none phrase in around where I thought the programming was for the search in the css styles sheet but it didn't change anything. Thanks for any help you can give me. :)
You can that by css : 1. Appearance -> Customize -> Additional CSS 2. Paste this code AFTER all the contents **.main-navigation .menu-item-search { display: none; }** 3. Save You can also do that by adding this code of line in the bottom most part of the functions. 1. Login to Dashboard 2. Go to Appearance -> Editor 3. Click Theme Functions at the right side 4. Add code at the last part after all the content remove_filter( 'wp_nav_menu_items', 'divina_add_search_box_to_divina_menu', 10, 2 ); 5. Save.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, search" }
WordPress Comments are automatically publishing I want to manually approve comments when someone will comment on any of the post. Right now when someone comment on any of the post these are automatically approved and published. I have changed settings in Discussion for comments but still these are automatically approved may be because the author of comment is admin. But i want to manually approve comments for all users whether admin or subscriber. Is there any way to do this. I will appreciate your guidance. Thank you!
An administrator is normal the highest level of user in Wordpress. If you want to approve every comments, even administrator comments, maybe you can use the moderation filter. If you go to `Settings` > `Discussion Settings` > `Comment Moderation`. You could setup an "cache all" filter. If you put all letters of the alphabet and the numbers 0 to 9 in as an filter, every comment should be send to the "moderation queue" for your approval.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments, publish, draft" }
I want to include My theme file (testing.php) to inside my plugin folder (myplugin/mypugin.php) Any One can suggest me.. I have a theme file testing.php(this is a theme file). I want to include this file to myplugin folder file.
Using hooks is what plugin is supposed to do. Using hooks ensures that core files are not changed. Woo theme files from the theme are based on the core Woo files from WooCommerce plugin, so they share same hooks. And that is the way it should work. Also, you can't include files from theme into a random plugin, it doesn't work that way. And since that YTH plugin already uses hooks, that is all OK, and no core files will be changed. All WooCommerce plugins work that way.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, theme development" }
In which file to use $wpdb and its functions for database operations and queries in wordpress? I have created Page template in wordpress called student to insert data in database using wpdb but i got error insted like this-![enter image description here](
About your specific Problem? maybe you should have a look at your permalink settings. index.php/students doesn't look right. The other thing: Why would you want to insert data into the database by using wpdb with data that is submitted from the frontend? The security risk is monumental, and if you don't exactly know what you do (which i assume looking at the question, no offense), you can not possibly make it safe. Or, to say it in memes: Do you want a hacked database/site? Cause that's how you get a hacked database/site. ;)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, wpdb" }
Adding a third custom taxonomies where the default category to is titled 'Games'. In the functions.php I have added this code to give each page a second category. <?php add_action('init', 'build_taxonomies', 0); function build_taxonomies() { register_taxonomy('players_team', 'player', array( 'hierarchical' => true, 'label' => 'Players Team', 'query_var' => true, 'rewrite' => true )); } However I need a third added. I have duplicated the code above in "functions.php" however I get an error on website. TBH didn't think it would be just a simple copy & paste. Im looking to add a third category called "Region". Any help is appreciated.
For every taxonomy you have to choose a unique name, which is used in the database. so so your new e.g. `players_region`. <?php add_action( 'init', 'build_taxonomies' ); function build_taxonomies() { register_taxonomy( 'players_team', // Unique name. 'player', // Post type. array( 'hierarchical' => true, 'label' => 'Players Team', 'query_var' => true, 'rewrite' => true, ) ); register_taxonomy( 'players_region', 'player', array( 'hierarchical' => true, 'label' => 'Players Region', 'query_var' => true, 'rewrite' => true, ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, taxonomy" }
woocomerce products and categories don't display fixed I have a issues with wordpress the products and categories don t display someone help me and the file error.log placed in path /var/log/nginx i was delete different file compressed with extension alternative.gz because already contact support to my hosting and any resolve someone can help me the message error.log link here :< ![see the picture issues](
Update permalinks, check the visibility of your products (can't be hidden) and make sure the products are published. If none of these works, try deactivate your plugins one by one (checking your site after deactivate).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Cannot get grandparent object I'm using the following code in order to get the ID of the current page's grandparent and great grandparent: <?php $current = get_post($post->ID); $grandparent = $current->post_parent; $greatGrandparent = $grandparent->post_parent; ?> <h2>$current: <?php echo $current->ID; ?></h2> <h2>$grandparent: <?php echo $grandparent->ID; ?></h2> <h2>$greatGrandparent: <?php echo $greatGrandparent->ID; ?></h2> However, when I try to echo them, I only get the value of the current page: > $current: 335 > > $grandparent > > $greatGrandparent: I am sure to be viewing a page that actually has great/grandparent pages... can anyone see what I'm doing wrong?
just a small error. To get the parent and Grandparent objects, you need to get_post them also. The property "post_parent" only gives you the ID of that post, not the post_object itself. So you change your code like this: <?php $current = get_post($post->ID); //Conditional to be sure there is a parent if($current->post_parent){ $grandparent = get_post($current->post_parent); //conditional to be sure there is a greatgrandparent if($grandparent->post_parent){ $greatGrandparent = get_post($grandparent->post_parent); } } ?> <h2>$current: <?php echo $current->ID; ?></h2> <?php if($grandparent){ ?> <h2>$grandparent: <?php echo $grandparent->ID; ?></h2> <?php if($greatGrandparent){ ?> <h2>$greatGrandparent: <?php echo $greatGrandparent->ID; ?></h2> <?php } } ?> And everything is fine!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "pages, variables, id, get post" }
Display published time for today's posts only I'm building a blog theme. I know that `the_date()` and `date()` functions display published date of posts. And I know how to get posts' published time with `the_time()` function. I want today's posts to show published **time** and all other old posts to show published **date**. For example, today is September 8. All the posts that were published today should show published time ( **08:40** , **16:30** , etc). But the posts that were published yesterday or longer before should show only date (September 07, July 26, etc). How can I achieve this goal? I guess there's a way to compare post's published date with today's date and make decision whether to display time or date that way. But there must be more optimal and easier way.
$post_date = get_the_date('d/m/Y'); $today = date('d/m/Y'); if ( $post_date == $today ) { echo get_the_date('h:m'); } else { echo get_the_date(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "date, date time" }
simple wordpress form redirection I am trying to create a simple form on one of my wordpress pages. The code used is as basic as it can be, namely the following: <form action="" method="GET"> <select> <option value="test" >test</option> </select> <input type="submit" value="search"> </form> the problem is, every time i click the search button, i get redirected to the homepage! Shouldn't this small little form be redirected to the page containing the form, since action is empty?
Alright guys, believe it or not, but the underlying problem had to do with permissions on the root folder! the aforementioned `<form action="#" method="GET">` didn't work either, so i digged a little deeper, and i found out certain pages couldn't be opened either. Why this causes every single simple form to be redirected to home is beyond me, but the solution was to change the permissions of the .htaccess file (which WAS present by the way), to 775. Out of caution i also changed the root folder permission to 775, and all is well now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, forms" }
Text Not Wrapping Around Right Floated Image I created a page where I have text wrapping around a right floated image using shape-outside polygon (yes, I will be using the cross-browser polyfill). Outside of Wordpress it works fine: < The problem is when I put it into a Wordpress template < I done lots of searching, but I can't seem to figure out why it won't wrap. FYI: I'm using using the Underscores blank theme. Any ideas?
Your heading is clearing the float. This is in your stylesheet: h1, h2, h3, h4, h5, h6 { clear: both; } You'll need to get rid of that, or overwrite it in this context, to allow headings to wrap around floated images.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, templates" }
creating new field on mysql I would like to add extra sections like "gender" on the WordPress user database. I would like to draw information from this information later. For example, let's say I want to attract gender. I created custom registration pages using the "ultimate member" extensions for this, but nothing changed in the database. there is still information like "user name, nickname, e-mail, registration data" only.
You can find any additional information in the usermeta table as meta_key meta_value pairs. Wordpress doesn't create additional database columns for custom fields. That's one of the great concepts that make Wordpress so smart and flexible.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "database, mysql, wp user query, customization" }
Necessary css classes to be included in theme stylesheet Developing a WordPress theme. I've got two questions 1. Does the first response here hold true even after 5 years? 2. Is it necessary / considered a good practice to include all the default html tags, for example `h1,h2,h3,h4,h5,h6,blockquote,acronym,abbr,code,pre,address` etc in my theme css file? P.S: My aim is to publish the theme in wordpress.org. Even if they did allow me to publish it without the extra styling, I would like to know if it is a good practice to include it in any theme.
1. So far, this is the most comprehensive list of all styling that theme might need for styling default widgets and other elements: Default WP CSS classes for a theme. You don't need to style all of them, but it is a good idea to use Theme Checker plugin to scan your theme before submitting it to WordPress.org, because it should pick up all the things that you might be missing, including in CSS. 2. Your theme should have good typography, and that requires you define styling for all typography elements, like headings (h1...6), paragraph (p), blockquote, pre... If you don't do that, browsers fall to default styling for those elements, and your theme might look different in different browsers. My suggestion is to start with some boilerplate stylesheet like Normalize.css or some CSS/JS/HTML framework (like Foundation, but that might be an overkill, depending on your theme).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, css" }
Get rating product by product id How to get product rating by product_id without loop? I have one product_id and i want get product rating, how can I do this and it is feasible? Thank
Given a product ID you can get the average rating like this: $product = wc_get_product( $product_id ); $rating = $product->get_average_rating(); That'll return the raw number (4.00, 3.50 etc.). To output the rating HTML for a given product you can use this code: $product = wc_get_product( $product_id ); $rating = $product->get_average_rating(); $count = $product->get_rating_count(); echo wc_get_rating_html( $rating, $count ); Or, if you're in the loop you can use this function to get the HTML for the current product: woocommerce_template_loop_rating()
stackexchange-wordpress
{ "answer_score": 14, "question_score": 6, "tags": "rating" }
Avada resources still loading from localhost after database migration I am using WP Migrate DB to migrate WordPress website built with Avada from local to a VM. I am doing a find and replace with Find: `//localhost/website` and Replace: `//10.60.8.118/website` Find: `C:\xampp\htdocs\website` and Replace: `/var/www/html/website` All the links are fine but fontawesome, icomoon and fonts which are being loaded from Avada are showing an error in console. I don't understand why still I have localhost URLs. (When I search for the term localhost in database I get no results) **Access to Font at '< from origin '< has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '< is therefore not allowed access.** and so on. Also I get an error "URL can't be found" when I go to inner pages. (Note that I have reset my permalink and also checked .htaccess file which is default from WordPress) May I know what might be wrong?
This issue with your **file path** URL. Still, Fontawesome trying to load fonts from "//localhost/website/wp-content/themes/Avada/includes/lib/assets/fonts/" Change all of your file path URL with your new site URL.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, migration, virtual hosts" }
Page appears after de registering from menu I have created a menu and registered its location in functions.php function register_my_menus() { register_nav_menus( array( 'footer-menu' => __( 'Footer Menu' ) ) ); } add_action( 'init', 'register_my_menus' ); Then I added menu in footer.php <?php wp_nav_menu( array( 'theme_location' => 'footer-menu', 'menu_class' => 'footer-links-menu', ) ); ?> The menu appeared in menu section and worked perfectly displaying sample page, custom link and sample post. ![enter image description here]( ![enter image description here]( Now I unchecked the menu in back end. (Footer Menu) The custom link and sample post are not coming. But the sample page link appears. Can some one help me if I am missing anything as the whole menu should not appear.
This is controlled by the `wp_nav_menu` argument `fallback_cb`, which is the `wp_page_menu` function by default. Set it to `false` to show nothing in the case a menu isn't assigned. wp_nav_menu( array( 'theme_location' => 'footer-menu', 'menu_class' => 'footer-links-menu', 'fallback_cb' => false, ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, pages" }
How to return a string that has a variable inside in a shortcode? $output = '<p class="one"><small>'.$newsletter_one. '</small></p>' Generally, when we write short codes we publish HTML like the above one, and instead of echo use return function. How should we write this one → <span class="class2" id="class3-<?php echo $random;?>"> </span> Like this → $output = '<span class="class2" id="class3-.$random."> </span>' or does this has some flaws?
When you want to return a data combined with a string, you can use one of the following methods: Either open and close the string using `'`: return '<span class="class2" id="class3-' . $random . '"> </span>'; Or use the double quote: return "<span class='class2' id='class3-{$random}'> </span>"; You can simply use `$random` without the `{}` curly brackets, but it's easier to read if you use `{}`. You can even use double quotes for the inner string, but you need to escape them: return "<span class=\"class2\" id=\"class3-{$random}\"> </span>"; As pointed out in comments by @birgire, to make it more WordPressy, we can also escape the variable: return sprintf( '<span class="class2" id="class3-%s"></span>', esc_attr( $random ) );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "php, shortcode" }
auto generate title of custom post type which concludes id not working I create the title of the custom-post-type "produktionsauftrag" automatically. The script in my functions.php works but i cant get the postid at the end of my title. Filter in my functions.php file: add_filter('wp_insert_post_data','update_pa_title',99,2); function update_pa_title($data, $postarr) { global $post; if ( !is_admin() ) return $data; if ($data['post_type'] == 'produktionsauftrag') { $data['post_title'] = 'Produktionsauftrag - ' . $post_id; return $data; } else { return $data; } }
I found the solution with title_save_pre add_filter('title_save_pre','auto_generate_post_title'); function auto_generate_post_title($title) { global $post; if (isset($post->ID)) { if (empty($_POST['post_title']) && 'produktionsauftrag' == get_post_type($post->ID)){ // get the current post ID number $id = get_the_ID(); // add ID number with order strong $title = 'produktionsauftrag-'.$id;} } return $title; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions" }
WooCommerce widget "WooCommerce Products" template There is a task to display on the main page two widgets "WooCommerce Products", the problem is that they have a completely different design. I overwritten the "content-widget-product.php" file in my theme, everything is fine with the first widget, but what should I do to create a template for the second widget?
You should write a new widget that matches the required design
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "woocommerce offtopic" }
Remove Number Of Pagination When I visit to my category page (example page 6) then my pagination is like this -> [Prev][1][…][5][6][7][…][12][Next] In this case, we are in the [6] button now. So, [5] button is same function with [Prev] button, and [7] button is same function with [Next] button, right? How to remove the left and right number (in this case [5] and [7]) button? No matter if I can remove it via .php file or custom css. Regards
Check the function which outputs pagination. It could look like this: <?php the_posts_pagination( array( 'mid_size' => 2, 'prev_text' => __( 'Prev', 'textdomain' ), 'next_text' => __( 'Next', 'textdomain' ), ) ); ?> You need to change `mid_size` parameter. This parameter determines how many page numbers to display to either side of the current page. So try change to `'mid_size' => 1` <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination" }
Using main style.css with add_editor_style All the resources I've read online suggest using a different CSS file (i.e. `editor-style.css`) in order to style the WYSIWYG editor to better resemble what the actual content will look like. For the purpose of testing I tried to just use the main `style.css` file that I've been using for the rest of the site and the styling in the WYSIWYG editor looks great and so far I haven't noticed any problems by doing this. Should I still create a new `editor-style.css` and use that or is it an acceptable practice to use my main `style.css`? For reference, this is the code I used below: function wysiwyg_styles() { add_editor_style( 'style.css' ); } add_action( 'init', 'wysiwyg_styles' );
The simplest answer is: you can use whatever stylesheet you want for the editor. `editor-style.css` is just the default stylesheet loaded if none is passed to `add_editor_style()`. This will load the specified stylesheet: add_editor_style( 'some-stylsheet.css' ); This will load editor-style.css: add_editor_style(); Use whatever better fits your needs. By the way, it is better practice to add the editor stylesheet using `after_setup_theme` action, not `init`, as it is something specific for the theme: add_action( 'after_setup_theme', 'cyb_theme_setup' ); fucntion cyb_theme_setup() { add_editor_style(); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "tinymce, wysiwyg, add editor style" }
How to change window ratio in teachpress "tplist" I am using teachPress to create list of publications. Picture below is a result of this code: [tplist order="title ASC" style="simple" year="2017" image="left" image_size="300"] Is there any adjustable parameter to **divide window** (illustration/article detail into different ratio than 1/2 + 1/2? For example to 1/3 + 2/3? * * * ![enter image description here](
You will have to create a custom template for displaying the publication. Follow the documentation on how to do this. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "parameter" }
pre_get_posts shows posts in random order sometimes I'm using the following filter in order to increase the amount of posts shown on category templates from 10 to 30 (I want to keep 10 for the rest of the site) // Modify number of results shown function modify_query_amount_shown($query){ if ($query->is_category) { $query->set('posts_per_page', 30); $query->set('orderby', 'menu_order'); } return $query; } add_filter('pre_get_posts', 'modify_query_amount_shown'); However, when I refresh my page several times, I notice the order of my posts changes each time. I can confirm that it has something to do with this code, because as soon as I comment it out, it returns to normal.
`pre_get_posts` is not a filter hook, it is an action. Also you should not set `orderby` to `menu_order` for posts as they are not hierarchical. Set `orderby` to `date` instead. function modify_query_amount_shown( $query ) { if ( $query->is_category ) { $query->set( 'posts_per_page', 30 ); $query->set( 'orderby', 'date' ); } } add_action( 'pre_get_posts', 'modify_query_amount_shown' ); Now the order of posts displayed will be consistent, regardless of the number of refreshes.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "order, pre get posts" }
How to calculate post index when using offset in custom query Not sure if I'm using the proper terminology in my title so feel free to correct. Say I have a custom post type called colors with say 40 posts that are in the default order in single_colors.php I have: $my_query = new WP_Query( array( 'post_type' => 'colors', 'posts_per_page' => 5, 'offset' => 2 ); if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) : $my_query->the_post(); ?> <?php the_title(); ?> <?php endwhile; ?> <?php endif; wp_reset_query(); ?> That would echo 10 posts from the custom post type starting with the 2nd in the list of available posts. I'd like to put the post number before each title. So in the above example would then echo: 2 Red 3 Blue 4 Green 5 Black 6 Yellow I was able to add a count feature but no matter the offset it would start the count at 1. Is there a variable, function or something to accomplish this?
In your case, count would be offset + current_post: $my_query = new WP_Query( array( 'post_type' => 'colors', 'posts_per_page' => 5, 'offset' => 2 ) ); if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) : $my_query->the_post(); echo $my_query->query_vars['offset'] + $my_query->current_post; the_title(); endwhile; endif; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "offsets" }
Select two value from meta key and post meta I want to ask best method to select two meta value from same column my code global $wpdb, $bp; $user_id = get_current_user_id(); $vlues=$wpdb->get_results(sprintf(" SELECT rel.post_id as id, rel.meta_value as val FROM {$wpdb->posts} AS posts LEFT JOIN {$wpdb->postmeta} AS rel ON posts.ID = rel.post_id WHERE posts.post_type = 'books' AND posts.post_title LIKE '%%fire' AND posts.post_status = 'publish' // Select specific book id AND rel.meta_key = 'books_id' AND rel.meta_value = '1351' // Check complete book AND rel.meta_key = %d AND rel.meta_value > 0 ", $user_id) );
You just need to join postmeta twice: global $wpdb, $bp; $user_id = get_current_user_id(); $query = $wpdb->prepare( "SELECT rel.post_id as id, rel2.meta_value as val FROM {$wpdb->posts} AS posts LEFT JOIN {$wpdb->postmeta} AS rel ON posts.ID = rel.post_id LEFT JOIN {$wpdb->postmeta} AS rel2 ON posts.ID = rel2.post_id WHERE posts.post_type = 'books' AND posts.post_title LIKE '%%fire' AND posts.post_status = 'publish' AND rel.meta_key = 'books_id' AND rel.meta_value = '1351' AND rel2.meta_key = %d AND rel2.meta_value > 0", $user_id ); $values = $wpdb->get_results( $query ); Also note that I used `$wpdb->prepare()` in place of `sprintf()`. It's the preferred method for safely putting values into a query with WordPress.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, wpdb" }
The best way to display taxonomies I have a custom hierarchical taxonomy named custom_taxonomy. For example: **Term 1** * term 1_1 * term 1_2 * term 1_3 **Term 2** * term 2_1 * term 2_2 * term 2_3 I want to display them on the post page as like in example above: name of parent taxonomy and all its childs, then another parent taxonomy and all childs of this one. Could you please advice the best way to do this. I thought to take only parents taxonomies via `get_terms` and then through the loop take childs elements by `get_terms` or `get_term_children`. Only one thing, I don't know how to display only terms related to current post in this case.
This has been already answered here Both the loops needs to exist and you can display it however you like. foreach( get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) { // display top level term name echo $parent_term->name . '<br>'; foreach( get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term ) { // display name of all childs of the parent term echo $child_term->name . '<br>'; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
WP_User_Query counter not updating with pagination Below is the code that I found (thanks to The_Sumo) on this link and the code works like a charm. I am trying to add an additional column to the table that displays the ordered list number of the users like: > 1 John Doe [email protected] > > 2 Jane Doe [email protected] One method I tried that kinda worked - i.e. I created a counter before the condition statement (`$counter = 0`). Then right after the opening bracket of the foreach loop, I am incrementing the counter by 1 (`$counter = $counter + 1;`) and printing the value of `$counter` within the table. The issue I am facing is - when I click next page, the counter value starts from 1 again instead of continuing from where it left of. So lets say I want to display 5 items in each page, so page 1 should display 1 - 5 and on page 2 6-10 - instead page 2 shows 1-5 again. Just the numbers. Any idea how to fix that? Thanks.
You can try: $number = $counter + ( $current_page - 1 ) * $users_per_page; with your increasing `$counter` variable in the loop. Here we assume `$counter >= 0`, `$current_page >= 1` and `$users_per_page >= 1`. We might combine it into: $number = ++$counter + ( $current_page - 1 ) * $users_per_page; with `$counter = 0` as initial condition.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination, wp user query" }
Static news page has for thumbnail the featured image of the first posts So I have a static page for the news page in wordpress, and its featured image as a breadcrumb image. I query it with this: `<?php the_post_thumbnail_url(get_option('page_for_posts')); ?>`. The problem is this function for whatever reason outputs the featured image of the first post instead of the featured image for the posts page. My entire `home.php` looks like this (with irrelevant html code cut out) <?php get_header(); ?> <?php the_post_thumbnail_url(get_option('page_for_posts')); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <!-- code for the posts --> <?php endwhile; endif; ?> <?php get_footer(); ?>
`the_post_thumnbail()` doesn't accept an arbitrary post id as an argument. It just takes a size to display. To get the post thumbnail URL of a given post, you need to use `get_the_post_thimbnail_url()`: <?php echo get_the_post_thumbnail_url( get_option( 'page_for_posts' ), 'full' ); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "post thumbnails, homepage" }
Send email to admin user when custom post type is created I need to send an email to the admin user when a post of the post type "task" is created. Any help would be really appreciated. Thanks!
If you want to send an email **on first publish and on updates** , you can avoid many extra checks by using {`status`}_{`post type`} action hook. Put the code below into the current theme's functions.php: add_action( 'publish_task', 'wpse_admin_email', 10, 2 ); function wpse_admin_email( $post_id, $post ) { // prepare and send email code goes here... } If you want to send an email **on first publish only** , use the code below: add_action( 'transition_post_status', 'wpse_admin_email_once', 10, 3 ); function wpse_admin_email_once( $new, $old, $post ) { if ( $post->post_type == 'task' && $new == 'publish' && $old == 'auto-draft' ) { // prepare and send email code goes here... } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
Apply a filter only once I want to remove automatically the _Home_ menu item, **but only once** , more precisely **at the first run of Wordpress or at the first child theme activation/loading**. Now I have a function in the functions.php of my child theme that checks if the _Home_ menu item exists and delete it from the menu. Of course, this function runs every time when Wordpress loads. **How to make it to run only once?** I tried the `add_filter_once()` function, but I got only a `PHP Fatal error: Call to undefined function add_filter_once()`. function filter_wp_nav_menu_objects( $sorted_menu_items, $args ) { foreach( $sorted_menu_items as $data ) { if ( in_array( "menu-item-home", $data->classes ) ) { wp_delete_post( $data->ID ); } } return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'filter_wp_nav_menu_objects', 10, 2 );
There is no native WordPress hook called `add_filter_once()`. This is an custom solution which will help you to run your hook only once. For example if inside a loop or whatever situation you are facing. However, The basic idea is to check when you need to stop using your hook and simply **remove_hook** from WordPress and once all done, you need to registere it again. example code: function add_filter_once( $hook, $callback, $priority = 10, $args = 1 ) { $singular = function () use ( $hook, $callback, $priority, $args, &$singular ) { call_user_func_array( $callback, func_get_args() ); remove_filter( $hook, $singular, $priority ); }; return add_filter( $hook, $singular, $priority, $args ); } The best way to understand what I try to explain to visit this link
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "filters, actions" }
How to add custom text near category/tag title in Wordpress Twenty Fifteen Theme? You can see the archive.php's title php code on twenty fifteen theme here: <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> I would like to add some custom text after category/tag title. Can I do that with archive.php? How to do that? In twenty fifteen theme both category and tag pages use archive.php.
Before anything, you should create a child theme, so you can update the parent (Twenty Fifteen) without worries. Looking at the WordPress hierarchy, you could copy the archive.php to the child theme and edit it, but would need to check what archive it is, of posts, custom post types, etc. Instead, copy archive.php twice, rename one to category.php and one to tag.php. You could even use category-{slug}.php for specific categories (same goes for tags). // in category.php / tag.php / ... the_archive_title( '<h1 class="page-title">', '</h1>' ); _e('Some custom text','twentyfifteen-child'); the_archive_description( '<div class="taxonomy-description">', '</div>' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, archives" }
looking for a hosting company for wordpress I've never purchased hosting space from any company before. I have looked around and I saw that some of these companies claim that they specialise in wordpress hostings. Initially I thought I'd just purchase a normal hosting page, maybe their most basic package as I won't be expecting many visitors. Maybe under 10k visits per month with at least 10GB of space. Also, what's the difference between a normal hosting space vs a specialised one for wordpress. If I'm using wordpress as a CMS, must I absolutely choose a specialised wordpress host? Currenty, my wordpress website is being developed on my localhost and nearly done. How would I go about transfering that website to the hosting space?
WordPress is extremely lenient to the hosting requirements. It is likely one of the most forgiving CMSes to run on the least capable PHP hosts. That said there _are_ advantages to _some_ of hosts that specialize in WP. Those that _do_ specialize and not just slap it on as marketing gimmick. I would put advantages in roughly two categories: 1. Expertise. Specialized hosts have better awareness of WP as a solution, what it takes to run it smoothly, and keep it secure. 2. Tooling. Specialized hosts can offer server configuration and features specifically fine–tuned for WordPress, such as object cache backend or reverse proxy. So while specialized hosts is completely unnecessary, there are some concrete benefits that make sense if budget works out for it. Personally I highly value reverse proxy feature, since it removes the need for flaky static page cache plugins.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "domain, hosting" }
How can I make an image full width inside a paragraph which is 70% (text) Got this small riddle: How can I make an image inside the_content() be full width, when it is inside a content paragraph which is `70% width`. I've look around and I don't seem to find the answer. I tried making the img absolute positioned `right:0 left:0`, but i cannot clear it and next paragraph goes underneath, since you cannot clear an absolute positioned element like you do with floated elements. I don't rule out a JS solution, but whatever it is I need little direction because I'm pretty lost at the moment.
Solved, JS with jQuery width(), removeAttr() to avoid wordpress inline width and height. Also negative margins. var anchoArticulo = $('article.single-post').width(); $('article.single-post div.single-post img.ancho_completo') .removeAttr('width height') .css('margin-left' , -(winWidth - anchoArticulo)/2) .css('width' , winWidth); Class `ancho_completo` is added in dashboard to the image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }
Exclude category by slug in pre_get_posts? Is it possible to exclude categories by slug in `pre_get_posts`? I can exclude categories by ID but it would be better if I can exclude posts by category name or slug.
Here's one way with the following tax query: 'tax_query' => [ [ 'taxonomy' => 'category', 'field' => 'slug', 'terms' => [ 'foo' ], 'operator' => 'NOT IN' ], ], where the `foo` term slug is excluded.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, pre get posts" }
Use $_POST data in functions.php I want to pass a parameter to a page from the one visited before and use it in a shortcode function. For this, I am writing in the scope of a function in functions.php : `$currency=$_POST['currency']` But it always return empty. What is the correct way to do this ? EDIT: My guess is that functions.php has an empty $_POST when called as it is called by an other file, not directly by the user. How can I access the _POST data in functions.php then ?
Try adding you query variable to the public query variable list like this. function wp280272_query_vars($vars) { $vars[] = 'currency'; return $vars; } add_filter( 'query_vars', 'wp280272_query_vars' ); you then can access it via get_query_var('currency');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "forms" }
site identity section name? In the customizer, the site identity section is missing a logo upload field. Adding such field is not a big deal: A field can be added, but I don't know the section name that is created in the core of the WordPress. Can someone help me in that? The field can be created like this: $fields[] = array( 'type' => 'color', 'setting' => 'links_color', 'label' => __( 'Links Color', 'twentytwelve' ), 'section' => 'header', 'default' => '#00A2E8', 'priority' => 10, 'output' => array( 'element' => 'body #page a, body #page a:link, body #page a:visited, body #page a:hover', 'property' => 'color', ) ); The below is a section for the header: 'section' => 'header', I want to know the section name of the site identity so that the logo option can be added there.![enter image description here](
The “Site Identity” section has the ID of `title_tagline` for historical reasons. If you want to see the IDs for the core sections, all you have to do is look at the source for `WP_Customize_Manager::register_controls()`. Alternatively, you can get a list of all the sections registered, whether by core or by plugins, by opening your console and entering: `_.keys( wp.customize.settings.sections )`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "theme customizer, settings api" }
SQL query for custom taxonomy slugs I need an array of custom taxonomy slugs. In the front-end, I get it using `get_terms():` $tax_slugs = get_terms( 'course', array( 'fields' => 'slugs', 'parent' => 0, 'hide_empty' => 0 )); print_r($tax_slugs); result: Array ( [0] => breakfast [1] => lunch [2] => dinner [3] => dessert ) In the admin, the "Invalid Taxonomy" error will be raised by the function `get_terms()` because I've registered my taxonomy on the `init` action hook. I need a function with SQL query and prepare method, to get an array of custom taxonomy slugs, like the one obtained with `get_terms()`
global $wpdb; $slugs = $wpdb->get_col( "SELECT slug FROM $wpdb->terms LEFT JOIN $wpdb->term_taxonomy ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id WHERE $wpdb->term_taxonomy.taxonomy = 'course'" ); That will return an array of strings representing the taxonomy term slugs for terms in the `course` taxonomy.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, theme development, wpdb, sql" }
Use /prefix/postname as a slug in post_name? I have a custom field that I would like to use as the post's slug. I'm able to get the custom field to be used as the slug for the post but I'm having problems attaching a /prefix/ before the postname. This is the code I have so far (If you want to use something else, substitute /episode/ with your choice) wp_update_post(array('ID' => $post->ID,'post_name' => 'episode/'. get_post_meta($post->ID,'incr_number', true))); When it's save, the post's slug is domain/episode1 and I'm trying to get /episode/1.
Well it turns out you can't use a slash ('/') in the slug but I found a solution from How to set permalink structure via functions.php, set the permalink structure in your theme's functions.php file add_action( 'init', function() { global $wp_rewrite; $wp_rewrite->set_permalink_structure( '/episode/%postname%/' ); } ); It will add `/episode/` before the post slug
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, slug, wp update post" }
Facebook og:image issues after https change We bought a SLL certificate recently to change our website to work with https protocol. After this change, we realized that the tag: <meta property="og:image" content=" ... url ...].jpg" /> is working when you load the website and open its source code. The thing is: Facebook sharing debug tool doesn't find this tag anymore. When I click on the link that shows me what is Facebook seeing (HTML), this tag is written like this: <metaproperty content=" ... url ...].jpg"> I already updated the Yoast SEO plugin to the newest version, but didn't solve the problem. Anyone has any clue?
The https change was not the cause. Actually - coincidentally - the W3 Total Cache was updated on the same day, and the **Minify** setting was breaking lines between **meta** and **property** words on the HTML, which were causing the error on Facebook debug tool.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, seo, ssl, https, plugin wp seo yoast" }
Wordpress plugins add parent menu option in admin main right I need to add a menu item but it is available as a parent item, I am trying it as follows but in the menu option it is shown as the child of the parent item Settings> My plugins name: add_action( 'admin_menu', 'my_plugin' ); function my_plugin() { add_options_page( 'My Options', 'My plugins name', 'my_plugin', 'my-plugin.php', 'my_plugin_page' ); } I have reviewed this section: < but there are many options, I am learning to create plugins for Wordpress. _Thank you very much for your help._
That's because it's a helper function for adding pages to the settings section, not the lower level API you expected: > This function is a simple wrapper for a call to `add_submenu_page()`, passing the received arguments and specifying `options-general.php` as the `$parent_slug` argument. This means the new options page will be added as a sub menu to the Settings menu. > > < Instead, you want `add_menu_page` <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin menu" }
Flush rewrite rules when new cpt is registred In my `functions.php` of my theme I'm registering 5 custom post types. Each having a custom taxonomy, which I'm rewriting the url based upon. Meaning the custom post URL becomes ` For example the post "Childrens book no. 1" of the custom post type "books" with the category "Childrens books" would become ` Whenever I register a new post type I need to flush the rewrite rules in order to get the permalink taxonomy rewrite to work. So in order to not use `flush_rewrite_rules()` more often than needed, when do I use it? I understand theres a `registered_post_type()` hook, but it seems to fire every time the admin is reloaded, making it a rather resource consuming operation. Is there a hook that only fires when a **_new_** post type is registered?
Post types are registered on every load. They're not stored in the database or some other sort of persistent storage. The posts are, but not the post types. So the correct place to flush rewrite rules is when the theme is activated. This can be done with the `after_switch_theme` hook: add_action( 'after_switch_theme', 'flush_rewrite_rules' ); For a plugin, you'd do it with the activation and deactivation hooks: register_deactivation_hook( __FILE__, 'flush_rewrite_rules' ); register_activation_hook( __FILE__, 'flush_rewrite_rules' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, url rewriting" }
Page Template Drop down disappears when static front page is selected My theme has a static front page. When I choose a new page for my blog posts to show, the page template drop down disappears from the page options only for the page I have selected to show my blog posts. (Its still there for all other pages) Is this normal behaviour? I want to select a custom template for the blog and not have it use index.php by default.
It's normal because custom page templates are only for pages. Once it becomes the page for posts it's no longer displaying Page content. It's displaying a list of posts. A Page Template wouldn't be designed, built, or optimised for displaying a list of posts. If you want the main blog page to appear different to the index template, then you just need to create a home.php template, as you can see in the Template Hierarchy.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, page template" }
deactivate product-page image slider on mobile I am developing a child theme of Storefront (WooCommerce). In the product page, I display all product images one above the other. But the user can still swype right, as if the image slider is still active. I would like to deactivated this swype motion on mobile (when the user swypes to the left, I want the product images not to move). Can you help me achieve this ? Thanks
Ok I found the solution, with this code in functions.php: add_action( 'after_setup_theme', 'remove_hemen_theme_support', 100 ); function remove_hemen_theme_support() { remove_theme_support( 'wc-product-gallery-zoom' ); remove_theme_support( 'wc-product-gallery-lightbox' ); remove_theme_support( 'wc-product-gallery-slider' ); } The line `remove_theme_support( 'wc-product-gallery-slider' );` deactivate the slider.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, mobile, slideshow" }
Wordpress update leads to 404 error on admin page and signup. CSS mishap with all plugin related functions I have recently updated **WordPress** live website in production. After the update I am facing the following problems. * wp-admin link is not working: it throws a 404 error page. Ref: < * CSS of existing plugins messed up. Ref: <
First of all never update production/live version, download it and try it locally or on dev server. **< seems working for me. Check do you have still page named login-page. For conflict css files you will need to remove them. add_action( 'wp_enqueue_scripts', 'wp_remove_theme_enqueues', 11 ); function wp_remove_theme_enqueues() { if( is_ThatPage()//search for that page ) { wp_dequeue_script('cssFile'); // etc } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "images, css, links, updates" }
Get posts under custom taxonomy and custom post type I've created a page with list of custom terms: ![enter image description here]( Under each Term, i need to show every posts with post_type = 'courses'e taxnonomy = 'courses_category' What will be the query to display those records? Thanks
You will need to use this code: $the_query = new WP_Query( array( 'post_type' => 'courses', 'tax_query' => array( array ( 'taxonomy' => 'courses_category', 'field' => 'slug', 'terms' => 'yourterm' ) ), ) ); while ( $the_query->have_posts() ) : $the_query->the_post(); // Show Posts ... endwhile; You can convert this in shortcode and just append it on your page trough your wordpress content editor or just insert this where you want to show your posts. Check Codex or this link
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, get post" }
Is it safe to add a new field to meta_value field? I'm trying to offload Wordpress images from my web server. I've successfully moved everything over to `Amazon AWS` and have a syncing mechanism in place that uploads new images to AWS. Now I would like to store a flag somewhere that indicates whether the image has been synced so my custom theme can pick the correct path. I was thinking adding that flag to the `wp_postmeta` table, as part of the `meta_value` serialized object. Is that a safe technique? What are the chances this value gets overwritten and lost? Additionally, I assume the `guid` field `wp_posts` shouldn't be updated with the full path to the image on AWS? That could be a solution as well.
`guid` doesn't affect the image URL, it is just used as a unique identifier. It could be random gobbledygook and as long as it is unique it wouldn't make a difference. It should be safe to use postmeta as long as you aren't using any plugins that would potentially completely overwrite all postmeta associated with an attachment - no plugins I am familiar with would do so, just mentioning what you would need to check on. Most plugins use `update_post_meta` which adds or updates if a particular postmeta key is found, so use a unique `meta_key` and you should be safe.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, meta value, guids" }
create front-end users post list by specific category I am trying to create a post list that will show current users posts by specific category and show the post id inside the title. So, I wrote the code below, but it isn't working work. Any suggestions please: <?php if ( is_user_logged_in() ): $user_id = get_current_user_id(); $args=array( 'post_type' => 'post', 'post_category' => array( 2 ), 'posts_per_page' => 10, 'author' => $user_id ); $wp_query = new WP_Query($args); while ( have_posts() ) : the_post(); ?> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php get_the_ID(); ?></a> <?php endwhile; else : echo "not logged in"; endif; ?>
As far as i know there is no arguments array key name `'post_category'` in WP_Query . Insted of `'post_category'` use either `'category__in' => array( 2, 6 )` or `category_name' => 'staff'`. And also for the id case use `echo get_the_ID()` ... to print the post id
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, posts, users, front end, id" }
Sort WooCommerce data with WP-CRON? I am building an e-commerce site with limited edition products. Each Woocommerce product page has a custom attribute when the product will no longer be available to purchase. When the product sale period completes, the 'add to cart button' is removed. If the original seller views their dashboard page, I can display a notification that their campaign has ended. However, an admin needs to visualize the products that have been completed and their sale statistics. I can't rely on a function to send this data if it only runs when the original seller logs in. **Logically, do I run a daily WP-CRON job that queries all products, compares the current time to their completion date, and conditionally manipulate data if the conditions are true?** Is this bad practice, super slow, or is there a better approach? _Slowly learning, thank you in advance for any guidance._
This doesn't sound like a bad approach to me. The thing to keep in mind about `WP_CRON` is that it's not a "real" cron and is only triggered when someone visits the site. To that end, you could also do the check when the product page loads and hide the button as needed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic, wp cron" }
add_filter img_caption_shortcode not implemented In a plugin I am creating, I need to change the output of the `[caption]`. I do this with (as from the Codex and other examples here) add_filter('img_caption_shortcode', 'caption_fix', 10, 3); function caption_fix ($x, $att, $content) { $content = 'new caption' ; // change it return $content; } But the `[caption] ... [/caption]` is still in the output; instead of "new caption" is expected to be in the output. I have verified that the caption code is enabled with this code: if ( shortcode_exists("caption")) { die("found caption shortcode"); } And the generated page dies as expected. Have carefully checked my caption_fix function to ensure that is returning content (if empty return $content, normal caption shortcode function is done). This is with WP 4.8.1 and PHP > 5.3. (Added: WP 4.8.2 does same thing.) Ideas?
(gotta read the docs a bit more carefully) I was using this code in the loop $xcontent =get_the_content(); But `get_the_content()` does not apply filters ... as the documentation states (if I was paying attention). I should use `the_content()`, or change it to this (which is the same as `the_content()`) : $xcontent =get_the_content(); $xcontent = apply_filters('the_content', $xcontent); So the issue was that filters were not being applied, since I used `get_the_content()` instead of `the_content()` . That problem solved. Now on to the next one, with more careful reading of the Codex docs...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, shortcode, captions" }
Some Text of website page on Iphone Safari become invisible I have designed and developed WordPress theme from scratch. Now after completion of website i am having an issue. On iphone safari browser page content become invisible but working perfectly on all the screens, Mobile, tablet and laptop. Iphone View of About Page ![enter image description here]( Android View of About Page ![enter image description here](
The Problem was strange because there was no html or css issue. The Problem is solved now. The problem was due to the font `ttf, eot, woff` files. I changed the font of website and my website started working perfectly.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, html" }
Import users from old WP site to new one I want to import existing users with their passwords from an old WordPress site to a new one. The new WordPress installation has also existing users. Therefore I couldn't simply export/import the database tables from the old site. Is there any other way to import the old users with passwords to the new site?
Changing the user `ID`s could be problematic. Other tables reference those - including `wp_usermeta` but if they are authors, customers, etc. then any tables that hold those items - like `wp_posts` \- reference the author by user `ID`. Changing the `umeta_id`s should be safe, because that value isn't referenced elsewhere that I'm aware of. It wouldn't hurt to check your particular plugins and other tables to see if they are indeed referenced somewhere. It would be safest to use a plugin to migrate the users. It does appear that you'll have to have your old users reset their passwords, but that's a smaller price to pay than getting customers, authors, etc. all confused. A couple of possible options: Importing Users into new WordPress site and importing users where password is provided as md5 + much metadata.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "database, users, import, export" }
How Parent Taxonomy automatically added to the post when using `wp_set_object_terms()`? I uses `wp_set_object_terms()` to add taxonomy to posts. Assume that I have following taxonomy. Topic Taxonomy Parent Tax : Mobile Phones(id=10) Child Tax : Samsung (id =12) When I am using `wp_set_object_terms( $post_id, '12' , 'topic', true );` only "Samsung" is added to that post. I need automatically add "Mobile Phones" to that post because "Mobile Phones" is parent tax for Samsung tax.
You can use `get_ancestors()` to get parents and grandparents etc. of a term, then use that in `wp_set_object_terms()`: $term_id = 12; // Get array of term parents. $terms = get_ancestors( $term_id, 'topic' ); // Include original term in array. $terms[] = $term_id; // Add parents and original term to post. wp_set_object_terms( $post_id, $terms, 'topic', true );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, taxonomy" }
Load media from another URL on a multisite install I have a multisite WordPress install with a large uploads folder. I want to setup multiple staging areas both on the local and remote server. But this way, it will take quite a lot of disk space. So I wonder if I can use the uploads folder from the live site for all these staging areas, e.g., load all images from mysite.com on mysite.dev and test.mysite.com and load images from the corresponding network site for other network sites. I found a plugin called Uploads by Proxy but it does not work with multisite installs. Is there any plugin solution to achieve this? I thought also of replacing image URLs in the database but this is going to be a regex replacement and this is going to take too long each time I update the database.
I found a solution on Stack Overflow. So I added the following to .htaccess Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteRule ^wp-content/uploads/(.*) [R=301,NC,L] This replaces all references to the local uploads folder with a remote uploads folder on the fly and I see images on my local dev area without having to download 30GB+ uploads folder. On the other hand, I cannot remove or replace an image on my staging area.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, media" }
How do I escape a table name or column name in SQL? esc_sql doesn't do this If you want to escape string values in an SQL query, you can use WordPress's `esc_sql` function: <?php $wpdb->get_var( "SELECT * FROM something WHERE foo = '" . esc_sql( $foo ) . "'" ); You can also use the much more convenient `prepare` function like this: <?php $wpdb>-get_var( $wpdb->prepare( "SELECT * FROM something WHERE foo = %s", $foo ) ); However, `esc_sql` is not suitable for escaping table names or column names, (only string values). And there is no way to use `prepare` for escaping table names or column names. How can I escape `$foo` and `$bar` properly in this example SQL query? SELECT * FROM $foo WHERE $bar = "example";
I can't find a function shipped with WordPress that does this, so I created my own: function esc_sql_name( $name ) { return str_replace( "`", "``", $name ); } You can use it like this: $escaped_name = esc_sql_name( $column_name ); $sql = $wpdb->prepare( "SELECT * FROM example WHERE `$escaped_name` = %s", $foobar ); ## Reference: * MySQL documentation on identifiers
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "sql, escaping" }
How to store in the database directly the translation? I would like to store my custom posts with the correct translation when the user activate the plugin. $a_custom_post = array( 'post_type' => "foo-page", 'post_status' => 'publish', 'post_title' => __( 'Foo page name', PLUGIN_DOMAIN ), 'post_content' => "", 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => 1, 'guid' => null ); wp_insert_post( $a_custom_post, true); How can i do it ?
I found the solution ! The problem was I loaded plugin domain only when plugins are loaded, not for the activation plugin. It resolves my problem... **MyPLugin.php** class WPGroupSubs { public function __construct(){ // Install needed components on plugin activation /* need to add this */ register_activation_hook( __FILE__, array( $this, 'load_text_domain' ) ); register_activation_hook( __FILE__, array( $this, 'install' ) ); //Translation when plugins are loaded add_action( 'plugins_loaded', array( $this, 'load_text_domain' ) ); ... } public function load_text_domain(){ load_plugin_textdomain( $this->domain, false, plugin_basename( dirname( __FILE__ ) ) . '/translations' ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, database, translation, activation" }
simple wordpress ajax plugin not working when not logged in anyone encountered this bug that it will work when you are logged in but once you log out it won't work anymore. this is a very simple plugin that will fetch zip code and display the corresponding rate. here's the code. < TIA!
You want to use `wp_ajax_nopriv_`) for handling ajax for non-authenticated users: // logged-out users add_action( 'wp_ajax_nopriv_my_action_search_key_press', 'action_search_key_press_callback' ); // authenticated users add_action( 'wp_ajax_my_action_search_key_press', 'action_search_key_press_callback' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin development, ajax, mysql" }
WordPress User role → Fetch and Print(echo) 1. Subscriber 2. Administrator 3. Editor 4. Author 5. Contributor Above are the 3 types of users roles defined in the WordPress. Just like we pull authors description: <p><?php the_author_meta('description'); ?></p> How can we pull user role?
This was answered here: < **Here is their answer:** You can't get user role directly. First, you have to get the user_meta_data, and it will return an Object that will contain user roles. **Code:** $user_meta=get_userdata($user_id); $user_roles=$user_meta->roles; //array of roles the user is part of.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author" }
Category Redirects to homepage My `.htaccess` file <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> I'm getting redirected to the HomePage but only on one WordPress category. The problematic category is `airlines`. eg. `url/airlines/test/` Had this line previously in `.htaccess`, but deleted. #RewriteRule ^airlines/(.*)/(.*).png$ ./upload-router.php?folder=$1&airline=$2 [L] Also rebuilt permalinks. I can fix this bug by changing `/%category%/%postname%/` to `/%category%xxx/%postname%/`, but of course I need how it was originally. I can also FIX it by renaming category to `airlines2`.
Fixed. There was conflict between slugs, which was hard to see at first, because project is large. :D Thanks.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, htaccess" }
How to rename default category name and slug using WP CLI? Using WP CLI how can I rename default category (Uncategorized) to **Blog** when starting a new project? Following documentation this should be correct? wp term update category 1 --name="Blog" But I get error Term doesn't exist This is how `wp_terms` table looks like ![enter image description here]( **EDIT** If I first create a category Blog with `wp term create category Blog`, how would I set this new category as default? After that I could try deleting the first category Uncategorized with `wp term delete`
Try removing the quotes around the new name. The docs show it as: `wp term update category 1 --name=Blog`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp cli" }
wp_redirect() does not work in custom template file <?php /** * Template Name: Custom Page Template */ get_header(); if(is_user_logged_in()){ // content for login user } else { // // wp_redirect() does not validate that the $location is a reference to the current host // That means this function is vulnerable to open redirects if you pass it a $location supplied by the user. // So use it only when navigating to another website wp_safe_redirect('/wp-login.php'); exit; } ?>
Redirects are performed by outputting HTTP headers, `wp_redirect()` just adds some bits on top of it for flexibility. Headers are only ever meant to be used _before any and all output_ to a page, since that is how HTTP response is structured. Hypothetically it could work in template _if_ you make sure it fires before any output. Practically it is a normal practice to deal with redirects on an appropriate hook, before any template/output is ever reached. The common hook to use is `template_redirect`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "page template, wp redirect" }
Restrict custom fields based on user roles I have search far and wide for this and the only solution i can find it restricting the amount of posts users can make. We have a WP site that we would like to monetize with a simple directory of sorts for a very niche market. We would like to have various levels of advertising partners that have access to certain fields dependent on their level. Example Gold would have 10 images, Bronze might have 1. Or gold has the "website" field. I am using ACF heavily over the site, and i do not need payment plugins or a front-end solution, we can work out the payment side separately and we will be using the Wordpress backend. I just need to be able to modify field availability based on a users role. Is there any way to achieve this? Thanks!
I managed to find a plugin called "ACF User Role Field Setting" that restricts the fields available based on users role. Works perfectly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, advanced custom fields" }
Testing localhost WordPress site over LAN with iPad, iPhone 1 down vote favorite I am developing a Wordpress theme that requires testing with multiple devices over my local network. I use the localhost server XAMPP which runs apache on port 80. When I access my PC's IP (192.168.0.16) port 80 using an iPad, it returns the apache directory of which I have two sites: site1 wordpress The first site is a basic php site, this loads perfectly. The second site is Wordpress, and won't let me access it (see pic). I have tried changing the setting inside Wordpress: changing localhost to 192.168.0.16 inside the site and Wordpress address. Can anyone advise me on what I'm doing wrong? ![enter image description here]( ![enter image description here](
Go to Admin Panel > Settings > General and replace localhost with your ip-address for WordPress Address (URL) and Site Address (URL). Or go to wp-config.php and add define('WP_HOME',' define('WP_SITEURL',' And when you access to from other device you should go 192.168.0.16/directoryOfWordpress
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, localhost, testing, xampp" }
Find and Replace text in the entire table using a MySQL query Website has been hacked and they have injected javascript into every single post, page and product (woocommerce) - Editing every page manually would take for ever, we have over 3000 posts. Is there a simple find and replace we could use to remove this javascript?
Do you have SSH access? WP-CLI via `search-replace`. $ wp search-replace '<script>bad javascript code</script>' '' --precise By default, this only searches for tables registered in `$wpdb`. To overwrite this behaviour, you can use either the `--all-tables` or `--all-tables-with-prefix` flag. (Or pass table names to the command manually.) **Alternative** : Easiest would be to download a dump, search/replace in that file and finally import again. 1. Download complete db backup 2. search & replace with your favourite text editor, replacing `<script>bad javascript code</script>` through an empty string 3. Delete tables 4. Upload your edited backup
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "hacked" }
Overriding post's font-family I have several users posting on my page. Some of them like to prepare post in Word and then copy-paste it into the WordPress Editor. Word uses custom inline CSS anc I'd like to get rid of the part which is changing the font family. Is it possible to replace/remove font-family css from all the posts already posted (I don't want to use some filter when outputting post to the page or using some CSS combined with !important). Solutions like "don't use Word" or "tell them to stop changing the font" won't help. Thanks.
You could run a regex. Since they're continuing this behavior, you will probably want to create a custom plugin and set up a cron job to trigger it periodically so it will continue stripping all inline styles. Your plugin will need to query all posts. From there, in a loop that checks each post's content, use `preg_replace('style="*.*?"', '', $content);` which will replace each inline style with nothing (''), essentially deleting it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, visual editor, fonts" }
How to display to visitor which site they came from? kind of new to this so not sure how to go about this. The task given to me is to that when a visitor arrives at the site through a link, I need to display to them where they came from. So if they used Google and clicked on a link in Google to load my site, the site would say something like "Welcome visitor from www.google.com." First, how to get the information where they came from, I don't really know. I was originally considering using the WP Statistics plugin, but then I was told that the HTTP header would contain this information. I don't really know what the HTTP header is or how it works or if there are exceptions. What would I use to figure out the referreer, and how can I display that to the user? This site is self-hosted so I have access to all the files via my hosting provider's cPanel. I am using the "Basic" WordPress theme. Thanks.
WordPress has a function that can extract referrer information (website where user originated from): `wp_get_referer()`. It will return URL from the originating website. If that is not available it will return `FALSE`. This is the simple example PHP function that will display welcome message when called, if the referrer is set: function wse_280729_show_welcome_message() { $ref = wp_get_referer(); if ($ref) { echo "Welcome visitor from '$ref'."; } } How will you use this is up to you, and depends where you want to display this, and will involve some theme modification and calling this function to show the message (if referrer is set).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php" }
Change WordPress header color using customizer I have theme customize function in my customizer.php file: function mytheme_customize_register( $wp_customize ) { $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage'; } But I can't change header_textcolor using theme customizer. How can I use header text color value in my theme? My header css: .navbar-default .navbar-nav>.active>a { color: #777; background-color: transparent; }
You have to inline the css into your theme. CSS is read-only and can't updated to use the update hex colors for your header. `<?php echo get_theme_mod( 'header_textcolor' );?> 100%);">` So find the `div` in your theme called `navbar-default` and update it to this: `<div style="background:#<?php echo get_theme_mod( 'header_textcolor' );?>"> class="navbar-default">`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, theme customizer, theme options" }
Getting taxonomy category Image from ACF I'm really new to php and I'm trying to get an image set using advanced custom fields on my front end. I've looked at the docs and forums but I can't get the url. All the code works but for the image. I expect the url value to show up but instead I get a blank value. I know I need to get the taxonomy ID, I must be missing something. Here is an image of my ACF settings: < And it's rules: < <?php // get all the categories from the database $cats = get_categories(); // loop through the categories foreach ($cats as $cat) { // setup the category ID $cat_id= $cat->term_id; ?> <div style="background: url( <?php the_field('category-image', 'term_'. $cat_id); ?> );"></div> <?php } ?> Thanks for any advice in advance.
Make sure you are using version 5.5.0 or newer since only that version support the format 'term_' . $id Try passing `$cat` as the second parameter to `the_field()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, advanced custom fields, advanced taxonomy queries" }
Get names and paths from unzip_file() I Need Some help for unzip_file, this code working fine but i want to add extracted files to wp media library, But i don't know how to get unzip files name and path one by one <
If i where you i would read the folder where the zip a $path = '/path/to/extract'; $file = '/path/to/zip.zip'; unzip_file( $file, $path ); $files = scandir($path); $files = array_diff(scandir($path), array('.', '..')); // removes empty spots from the array and then do what you want with the files. File names are in the $files array. foreach ($files as $key => $file) { # code... } Did not test it but i think this should work :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filesystem" }
How To Pass Theme Path In Javascript Ajax to Pass Id On another Page in Wordpress Custom Page Template? <script type="text/javascript"> function test(str) { var a; if(window.XMLHttpRequest) { a=new XMLHttpRequest(); alert("Current Browser is Mozilla"); } else { a=new ActiveXObject("Microsoft.XMLHTTP"); alert("Current Browser is IE"); } a.onreadystatechange=function() { if(a.readyState==4 && a.status==200) { document.getElementById("state").innerHTML=a.responseText; } } a.open("GET","getstate.php?cid="+str,true); a.send(); } How To Get Theme Path in Javascript For last two lines in wordpress custom page template to pass id on getstate.php which is in my theme>currenttheme>getstate.php ?
You have 2 ways to pass the theme name into the javascript 1. You can pass it as a variable into it in case you are using Ajax. 2. If you are using any php file you can use `<?php bloginfo('template_url); ?>` Let me know if you need any more help
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax" }
How to get slug of current category in taxonomy template? How can I retrieve slug of current taxonomy being viewed in taxonomy template? I tried to codex but found nothing on taxonomy template page. To further explain, lets say I am viewing category flowers so how can I retrieve slug of category flowers?
You can get the term object of the category you’re viewing with `get_queried_object()`. That will contain the slug. $term = get_queried_object(); echo $term->slug;
stackexchange-wordpress
{ "answer_score": 26, "question_score": 8, "tags": "templates, taxonomy, slug" }
Why?: hundreds of empty files named wp-cron.php?doing_wp_cron.<digit> In the home directory of the nginx user I have hundreds of empty files named wp-cron.php?doing_wp_cron. So my questions are 1. why...? 2. can I delete them...? . 3. and how do I stop then regenerating? Thanks
Ah... worked it out, though normally I rely on the traffic of the blog to hit wordpress' fake cron I did have a daily crontab with wget to make sure site was fresh just before doing an export for an integration... but to stop it downloading the response of the request (in this case an empty file) you need to add the **\--spider** option `31 0 * * * wget -qT 30 --spider
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp cron, cron" }
How to target children of child pages I would like to apply special styling to the menu items of pages that are children of child pages. Is there a way to do this?
Add this `CSS` rule to your stylesheet: ul.menu ul.sub-menu ul.sub-menu li{ //special styling here } its the default `CSS` classnaming `WordPress` use for the menus, you can see how i add it here. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus, child pages" }
How do I add an options page at the bottom of the list? I'm working on my first plugin, and I'm using something like this to add a submenu under Settings: add_options_page( 'Page Title', 'Menu Title', 'edit_theme_options', 'my-plugin-menu-slug', array($this, 'options_page') ); The trouble is that this adds the entry on the top of the submenu, as pictured below. ![wp-admin menu]( How can I get it to add the entry at the end of the list instead?
When calling `add_options_page` make sure to call it on the `admin_menu` action/event, so it's called at the correct time add_action('admin_menu', function () { add_options_page( .... ); } ); You may be able to gain further control by specifying the priority of the action in the `add_action` call
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, admin menu" }
Unable to make shortcode, what is wrong? /home/<website>/public_html/wp-content/themes/basic/functions.php At the very end of the file, I have included these 8 lines: // Add Shortcode function custom_shortcode() { return "Hello world."; } add_shortcode( 'test', 'custom_shortcode' ); Doesn't work and I can't figure out why. I am self-hosted running the free Basic theme. I have the following plugins: * Cache Enabler, * Disable Emojis, * Remove Google Fonts References, * UpdraftPlus - Backup/Restore, * WP Fastest Cache, * WP Statistics. I've tried various different ways of doing this and have looked up several guides. They all say to do exactly what I'm doing and that it will work, but when I do it it does not work.
I was originally using the Basic theme with a few plugins. Disabled the plugins, issue persisted. Changed from Basic theme to twentyseventeen. Went in to the plugins.php file in the twentyseventeen theme and copy/pasted my exact code. Now it's working fine. I don't know enough to know why the Basic theme did not allow me to make a shortcode, but that is the answer to this dilemma: Basic theme will not allow you to make a shortcode the typical way. Whether it's possible at all is for me to figure out in the future (unless someone else happens to know).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
Can we count the Wordpress Loop Can we count the WordPress loop and store it in a variable? <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $post_id = get_the_ID(); ?> <?php get_template_part('content','home'); ?> some code to be executed <?php endwhile; ?> <?php endif; ?> what I want is that for every 5 posts fetched ceratin code should be executed(example newsletter) → That means within the loop for every 5h, 10th, 15th, ____________ infinite posts(5n, n>=1) the code should be executed.
`$wp_query->current_post` is the build-in loop counter, starting with 0 zero for the first post in the loop. so the line `some code to be executed` could translate to: `<?php if( $wp_query->current_post > 0 && $wp_query->current_post % 5 == 0 ) { ?> some code to be executed <?php } ?>`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, loop" }
Page found with "Plain" permalink but not with "Post name" I'm working locally on Ubuntu 16.04 LTS machine, with apache2 server. I started developing the site on Windows 10 before moving to Ubuntu. I now have this problem: When I set Permalinks to "Post name" all pages, except the front page, are not found by the server. By the way, when moving to Ubuntu I also changed the site url. However, I did similar changes when moving the site to a remote server with no problem at all. My .htaccess is writable looks like this: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /nuritzurgil.co.il/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /nuritzurgil.co.il/index.php [L] </IfModule>
For permalinks to work, you need **mod_rewrite** module enabled on Apache server. Check your Apache configuration and make sure **mod_rewrite** is installed and enabled. Here is the easy to follow tutorial for Ubuntu 16.04 to enable Rewrite module: How To Rewrite URLs with mod_rewrite for Apache on Ubuntu 16.04
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }