INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I make WordPress serve homepage to different URL? I would like to set up a landing page and a homepage for my WordPress website. I am new to WordPress, but I am an experienced web developer. WordPress will only serve the homepage content if the URL is `example.com`; however, I would like to force it to serve the homepage content to `example.com/home`. I was planning on setting the “Front Page” to the Landing Page I have created. And then the landing page will link to `example.com/home`. However, for now the `example.com/home` page is blank, and I would like to have it display the “Home Page” content. Basically, I am trying to find out whether it is possible to make `example.com/home` serve what is supposed to be on the home page.
You could do this by creating a new page called "Home" with the permalink slug of "home" and another page e.g. "Landing" for your landing page. Then go to Settings -> Reading and set the "Front Page" option to your landing page from the dropdown box. You will then be able to link to `mydomain.com/home` from your landing page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "homepage, frontpage, home url" }
remove description in colum title post !remove description post I encountered a problem in the wordpress admin.in Post-> all post.it born a description that I wanted to give it.can i help me?
On same page above post list (in top right), you have this section to change list view. Select the red arrow pointed option to disable excerpt view. Currently you are in excerpt view that's why post description is showing. !enter image description here
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts" }
Plugin Post 2 Posts: How to list most connected posts? I want to list the most connected posts ordered by quantity. ¿Is it possible? ¿Could anyone help me with that? I explain with an example: let's say I have `Movies` custom post type and an `Actors` custom post type, that are connected with `Posts 2 Posts`. In the Actors archive, I want to **order them by the number of Movies that they have worked on**. I think it is maybe possible with `each_connected()`, but I don't know how to order the `$wp_query` array by the number of elements in `connected` subarray for every `$post`. Thanks.
I have done this way: // Find connected pages (for all posts) p2p_type( 'actors_movies' )->each_connected( $wp_query ); Now we have a `$connected` property attached to every post on the `$wp_query`, that is an array of posts connected by `actors_movies`. $actors = array(); while (have_posts()) : the_post(); $movies_acted = count($post->connected); if($movies_acted > 0) { $actors[$post->ID] = $movies_acted; } endwhile; arsort($actors); foreach ($actors as $id => $quantity) { //Show the actor info } Then, I have made an array with the `ID` of the `$post` as the `key`, and the quantity of `$connected` as the `value`, for each. Then I have ordered it by the `value`, and I have done a `foreach` through the array, to get the post from every `ID`, starting from the most prolific =D
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin posts to posts" }
Prevent "/login" to redirect to "/wp-login" A client has asked me to exlude "/login" as they want to have the url to lead elsewhere (to a remote system). When typing this url it automatically redirects to "/wp-login". How can I remove / prevent this?
If you're hosting on Apache you could do this in your .htaccess file by adding the following before any of the Wordpress rewrite rules. RewriteRule ^login$ [NC,L,R] Just replace "< with your clients remote system URL.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, login" }
Wordpress sub taxonomy template Please see my code structure Custom post type name : **product** Custom taxonomy associated with product : **category** Main category inside category taxonomy : **main1, main2 etc** Sub taxonomy inside main1 : **sub1, sub2 etc** I need to create template for all sub category and this templates are same. so I need to create one template only that is suitable for all category taxonomy. Also I need to know **how to get the current taxonomy or sub taxonomy slug inside this template file** , and also **how to know the current page is main taxonomy page or sub taxonomy page**. please explain if you know the answer. I to create `taxonomy-category.php`, but that is not working Why are `taxonomy-category.php` and `taxonomy-category-main1.php` not working? After creating these pages and view products by category it's display Nothing Found.
You cannot use category slug as its the default slug for WordPress category. Try register your taxonomy with some other taxonomy name like product-category and use taxonomy-product-category.php file to render individual taxonomy category layout(main1, main2 etc.) Function Reference/register taxonomy.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, theme development, template hierarchy" }
Include files in functions.php This is a rewritten post since the way I worded my old post totally confused everyone. MikeSchinkel shows how he uses Include files in his theme's functions.php file In this Stackexchange post: Organizing Code in your WordPress Theme's functions.php File? Example: require_once('includes/my-file.php'); How would you write this php line if the file to include is inside a directory, inside the wp-content directory? Location: [wordpress install]/wp-content/new-directory/my-file.php The only way I can think of is like this: require_once( ABSPATH . '/wp-content/new-directory/my-file.php' ); Would this be the correct way?
Including a file inside a subdirectory is the same as any other as long as you know the path to the file. Since it's possible to move the 'wp-content' directory, don't pass that part of the path to the `require` statement; instead, use the `WP_CONTENT_DIR` constant. require_once WP_CONTENT_DIR . '/new-directory/my-file.php'; Also, you can leave out the parentheses since `include` and `require` are statements, not functions.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "php, include" }
Hook that get's triggered when the author of a post is changed Is there any hook that gets trigged when the author of a post is modified from the edit post screen? I can list to the update post hook, but then I will not know whether the author of the post was changed or not.
There is no special hook to author change. But you can achieve it by using `post_updated` hook. Example: add_action('post_updated', 'prefix_on_update_author', 10, 3); function prefix_on_update_author($post_ID, $post_after, $post_before) { if ($post_after->post_author != $post_before->post_author) { // author has been changed // you can add your own hook here or write your code } } Here is the codex reference.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 7, "tags": "posts, hooks, author" }
Targeting specific pages in the loop I am having a custom query that calls in pages in an array like so: <?php $args = array( 'post__in' => array( 2, 7, 9, 11, 13 , 15, 17 ), 'post_type' => 'page', 'orderby' => 'menu_order', 'order' => 'ASC' ); $the_query = new WP_Query( $args ); while ( $the_query->have_posts() ) : $the_query->the_post(); ?> Is it still possible to target single pages of the array to have page specific alterations of the code, i.e. <?php if(is_page(7)) { ?> // do something <?php } else { ?> // do something else <?php } ?> inside this query or do I have to query every page in a a separate query? I am using this query to put together multiple pages into one template (front-page.php) in order to have a onepaged layout, i.e. all content on one page, so I would like to use conditions inside the loop for clarity in my code.
You would rather want to use the post ID inside the loop to target your pages. `is_page()` simply checks whether the current page is actually a page or a specific page if a value is passed ## Example if ( $post->ID === 7 ) { // Do something for page id 7 } else { // Do something for other pages }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp query, pages, conditional tags" }
Why not to include reference to /wp-admin/admin.php in Plugin Contact Form 7 recently pushed out an update which caused a few conflicts in other plugins. WPCF7 Author explains that it's because plugins are including calls to `wp-admin/admin.php` in their scripts which you shouldn't do in a plugin. Takayuki Miyoshi explains it here but I'm not sure I understand exactly _why_ it would cause any kind of issue or how this is different from calling say `wp-load.php`. Could somebody explain why it's advised never to load `wp-admin/admin.php` in your plugin and how it could cause issues?
> Could somebody explain why it's advised never to load wp-admin/admin.php in your plugin and how it could cause issues? Because it is loading WordPress out of context-- well, parts of WordPress. And that can cause unexpected effects such as functions not being loaded or functions being loaded twice (which will cause fatal errors). You will have trouble with hooks firing multiple times, or not firing. You may have trouble with constants. You may not have trouble, but that depends upon how and why the files are loaded. > ...how this is different from calling say `wp-load.php`[?] `wp-load.php` is a bootstrap file that `admin.php` will load about line thirty-something. It is a similar hack and can have similar problems. It should not be done either. There is very little reason to use either technique. WordPress should be loaded for you plugin for most purposes and if not, say you need to make a separate request, use the AJAX API which will boot WordPress properly.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, plugin contact form 7" }
How to disable user registration for the default subscriber user role? I'm dealing with fake user registrations on my site. Since i'm using WooCommerce, i have a custom signup page which will generate users with **"customer"** as the user role. However, all of the fake users are registering through wp-login.php, which will generate a user with the **"subscriber"** role. Is it possible to somehow disable the user generation process(probably inside `wp_insert_user()`) if it tries to signup a user with the role set to subscriber? The closest action i could find is `user_register`, which triggers immediately after the user has been created, so i could delete the user if the role is subscriber, but i would like to do this before the user is even created. Also most of the user data is filtered, but not the user role:(
There might be more elegant way to do it, but from quick look at the code it seems quite easy to simply override the relevant option on login page: add_action( 'login_init', function () { add_action( 'pre_option_users_can_register', '__return_null' ); } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "user registration, signup" }
get_posts - require all categories From the `get_posts` docs I see it takes categories as a parameter. However, is this an `AND` or an `OR`? i.e. if you specify 2 categories do posts have to be in both to be returned? If not, how do you specify an `AND` relation? I only want posts that match ALL categories.
Display posts that have "all" of these categories: $query = new WP_Query( 'category_name=staff+news' ); See this on category parameters.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Shold I manually add 'cap' to admin role ? I've created a role: $role = add_role( 'role', 'role', array('read' => true) ); and so created a cap: $role->add_cap( 'cap' ); after this I'd created a submenu in admin menu with 'cap' as capability argument. So the problem is that the user with 'role' role can see the submenu but the site admin can't see the submenu, so the question is: I have to add 'cap' to admin role ? isn't it automatically ?
A new capability has to be explicitly added to either a role or a user. In your case if you want all administrators to have 'cap' capability you will add it to 'administrator' role: $role = get_role( 'administrator' ); $role->add_cap( 'cap' ); If you want a specific administrator only to have 'cap' capability then you add it to this particular user: $user = new WP_User( $user_id ); // $user_id = id of your administrator user $user->add_cap( 'cap' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "user roles, capabilities" }
How to search map address in custom post type? I built a custom post type "shop" with Custom Post Type UI plugin and added a field "address" (Google Map type) with Advanced Custom Fields plugin. From the response of `WP_Query('post_type=shop');`, I got the following: $shop = WP_Query('post_type=shop'); while($shop->have_post()) { $shop->the_post(); $location = get_field('map-location'); if($location != null) { echo $location['address']; } } Here I got a list of addresses. How do I search with this "address"? Let's say user wants to search shop that is in "London", how can I achieve this? Thanks. * * * **UPDATE** Sample result of searching "15": * 15B * 103 * A
You need a `meta_query` something like this: $args = array( 'post_type' => 'shop', 'meta_query' => array( array( 'key' => 'map-location', 'value' => 'London', 'compare' => 'LIKE' // the = operator might work depending on how your data is stored ), ) ); Note: I am making some assumptions about how ACF stores data.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, search" }
Contact form db plugin customization I am using contact form db plugin. Now I want to just hide the short code menu link from admin panel. Is it possible?
Use the remove_submenu_page function to remove the shortcode menu. Pass the parent menu's slug and the submenu's slug as arguments to this function. Paste the following in your theme's `functions.php` file. add_action( 'admin_menu', 'remove_short_code_menu' ); function remove_short_code_menu() { remove_submenu_page( 'CF7DBPluginSubmissions', // $parent_menu_slug 'CF7DBPluginShortCodeBuilder' // $submenu_slug ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin contact form 7" }
Quotes in table name Since WP3.5, `prepare()` accepts placeholders as a security measure, instead of just appending the argument to the query. Therefore, `$wpdb->prefix` needs to become a second parameter, called by `%s`: $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(id) FROM %s WHERE answer !=' '", $wpdb->prefix . "faq_questions" ) ); However, doing that returns the table name in quotes: `SELECT COUNT(id) FROM 'wp_faq_questions' WHERE answer !=' '` How can I fix this?
> How can I fix this? You can't, but it isn't broken. You are telling `prepare` to use a string. A string will be quoted. It isn't meant to generate MySQL syntax, which is what you are asking it to do. Your tablename is more a MySQL command or keyword than a string value. That isn't what `prepare` is for. `prepare` is meant to operate on user supplied data. Your tablename is not-- well, shouldn't be-- user supplied data so you don't need to "prepare" it. It is unnecessary. Just construct the tablename in the SQL itself: "SELECT COUNT(id) FROM ".$wpdb->prefix."faq_questions WHERE answer !=' '" See: <
stackexchange-wordpress
{ "answer_score": 9, "question_score": 1, "tags": "wpdb" }
How to split a loop into two columns I am running a dwfocus news website, I would like to split my li loop catagory in two section, can some let me know how can i proceed forward, thanks. <div class="headlines" data-interval="<?php echo ($interval>0)?$interval*1000:'false'; ?>"> <ul> <?php $i = 0; while ( $r->have_posts() ) { $r->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li> <?php } ?> </ul> </div>
You will need to create `css` classes for a left and right column (you can use bootstrap if you like) after creating the classes try this <div class="headlines" data-interval="<?php echo ($interval>0)?$interval*1000:'false'; ?>"> <ul> <?php $i = 0; while ( $r->have_posts() ) { $r->the_post(); if($i % 2 == 0){ //even line ?> <li class="left-col"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li> <?php } else { ?> <li class="right-col"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="time_diff"><?php echo ' - ' . dw_human_time_diff( get_the_time('U'), current_time('timestamp') ); ?></span></li> <?php }; $i++; } ?> </ul> </div>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "loop" }
CPT and metabox: create multi checkbox by using array? I have a custom post type to display informations of book. Then I created a metabox for it. And: I need to add a warning system _(like: for kid, violent, mature, adult, etc...)_ chosen by multi checkbox, then display them to the CPT by warning icons (png or svg) How can I use array to create this options, save and display? Here's my metabox addding: global $st_series_cpt; $prefix = 'st_series_'; $wpar_meta_box = array( 'id' => 'series-post-meta-box', 'title' => 'Information', 'page' => 'stfic', 'context' => 'normal', 'priority' => 'high', 'fields' => array(???) );
There is no "fields" argument to `add_meta_box()`, which I assume is what you are using and not some code-bloat-ie helper function/class nonsense. And you've not identified a callback, which is the key. Create a callback and put your "warning" array in that, along with code to create your checkboxe/radio-boxes, or whatever you need. $wpar_meta_box = array( 'id' => 'series-post-meta-box', 'title' => 'Information', 'callback' => 'st_meta_box', 'page' => 'stfic', 'context' => 'normal', 'priority' => 'high', ); function st_meta_box($post) { $warn = array( 'kid', 'violent', 'mature', 'adult' ); // Code to create form markup }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, metabox, array" }
Can't connect to WP-Admin, blank error message I have to work on a website, but I cannot connect to the WordPress Administration... I did a forget password and resetted the password multiple times so I know that I have the right username/password combination, but I still cannot connect. Anytime I try to connect, it comes back to the wp-login page with a blank error message. Tried to update my WP installation, didn't fix the problem (site is now running WP 4.2.2) The blank message appears with both a correct and incorrect login. I have no idea what might cause this problem, can somebody help? !enter image description here
Check to see if your `functions.php` file includes a filter for `login_errors`. For example, this would disable any login errors from being displayed: add_filter('login_errors', function($error){ return null; }); This is sometimes done as a security measure so the reason a login attempt failed isn't available to any would-be hacker or bot. More info on this filter: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, login" }
Query only current post type using taxonomy I have several post types "Courses", "Institutes" having same taxonomy "country". I am using this to get term on single-courses.php <?php $terms = get_the_terms( $post->ID , 'country' ); foreach ( $terms as $term ) { $term_link = get_term_link( $term, 'country' ); if( is_wp_error( $term_link ) ) continue; echo '<a href="' . $term_link . '">' . $term->name . '</a>'; } ?> When I click term, it get all post types having "country" taxonomy. How can I use it to get ONLY CURRENT POST TYPE.
If you look at WordPress' available query variables, you will notice `post_type`. You will need to add that to your URL: $terms = get_the_terms( $post->ID , 'category' ); foreach ( $terms as $term ) { $term_link = get_term_link( $term, 'category' ); if( is_wp_error( $term_link ) ) continue; $term_link = add_query_arg( array( 'post_type' => $post->post_type ), $term_link ); echo '<a href="' . $term_link . '">' . $term->name . '</a>'; } Reference: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy" }
WordPress Custom Menu Admin helper plugin I'm creating learning system in WordPress and I have a lot of pages instead of post. Those pages needs to be in a custom menu with two sub items. It gets really confusing to add pages to the menus because the add to menu section is so tiny. Also some of the sub-pages doesn't show up indented. Is there a way to make that bigger thru a plugin? To make it more uncluttered. Here's the view of my menu right now. !enter image description here and sample of my menu structure !enter image description here
Add this to functions.php, or put the CSS into a css file which is loaded in the admin screen. This will let the box become resizable, so you can make it taller and see more pages/checkboxes at once. function wp191833_resize_menu_list() { ?> <style type="text/css"> #wpwrap .categorydiv div.tabs-panel, #wpwrap .customlinkdiv div.tabs-panel, #wpwrap .posttypediv div.tabs-panel, #wpwrap .taxonomydiv div.tabs-panel, #wpwrap .wp-tab-panel { resize: vertical; max-height: none; } </style> <?php } add_action( 'admin_print_styles', 'wp191833_resize_menu_list' ); Preview: !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, menus, sub menu" }
Show different page for first time user As per my requirement I need to show a page say `firstpage.php` for user who visit my site for `first time` else should show home page say `homepage.php` I created both this pages as `page-templates` For this so far I have managed to set using cookies using below code if (!isset($_COOKIE['visited'])) { // no cookie, so probably the first time here setcookie ('visited', 'yes', time() + 3600); // set visited cookie header("Location: index.php"); exit(); // always use exit after redirect to prevent further loading of the page } else{ header("Location: index.php/first-page/"); } When I use above code it is not being redirected to required URL and resulting an error. > The page isn't redirecting properly
I found a plugin to get my requirement,it is managed using `cookies` we need to provide `Welcome URL` A.K.A `firstpage` in my case and them we need to select which page should be redirected for second time.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "redirect, page template, wp redirect" }
Woo-Commerce Send mail by code. I am doing custom order is working fine but mail is not working so i am trying to use the default woo-commerce mailing functionality. i found the class from where woo-commerce send mail but when i am using the class it give me error. Class and Function which i am calling `WC_Email_Customer_Processing_Order::trigger( $order_id );` It give me bellow error. Class 'WC_Email_Customer_Processing_Order' not found in function.php. I am call function in functions.php
After doing some research on google and woocommerce code i found the ans of the what i what. i have use following function for to send the mail to the user once order have been generated using the custom code in wordpress woo-commerce. `WC()->mailer()->emails['WC_Email_Customer_Processing_Order']->trigger($orderId);`
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "email, woocommerce offtopic" }
Select random post every day I am looking for a script to select 1 random post per day in Wordpress. I found the code below, but this keeps gathering a new post every time I refresh the page: <?php function force_random_day_seed($orderby) { $seed = floor( time() / DAY_IN_SECONDS ); $orderby=str_replace('RAND()', "RAND({$seed})", $orderby); return $orderby; } add_filter('posts_orderby', 'force_random_day_seed'); $args = array('numberposts' => 1, 'orderby' => 'rand', 'post_type' => 'listing'); $totd = get_posts($args); remove_filter('posts_orderby', 'force_random_day_seed'); foreach( $totd as $post ) : ?> <?php the_title(); ?> <?php the_content(); ?> <?php endforeach; ?> Any ideas?
Note that the `posts_orderby` filter is not available for `get_posts()` where `suppress_filters` is `true` by default. You can use `WP_Query` instead: $args = [ 'posts_per_page' => 1, 'orderby' => 'rand', 'post_type' => 'listing', 'ignore_sticky_posts' => true, ]; add_filter( 'posts_orderby', 'force_random_day_seed' ); $q = new WP_Query( $args ); remove_filter( 'posts_orderby', 'force_random_day_seed' ); if( $q->have_posts() ) { while( $q->have_posts() ) { $q->the_post(); the_title(); } wp_reset_postdata(); } else { _e( 'Sorry no posts found!' ); } It's also possible to skip your `posts_orderby` filter callback and just use transients to store the results for 24 hours.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query" }
Rewriting URLs with a query string I am running into a headache trying to get some url rewriting working on a wordpress website, running Centos 6 for operating system. This is what I am trying to achieve. **Current URL =< I would like this to be re-written to **< I must of tried every tuturial online with absolutely no success. Please help me!!
I have cracked it. :) Here is my solution. add_rewrite_rule('^(property-details)/([^/]*)/?', 'index.php?pagename=$matches[1]&propertyidtag=$matches[2]','top'); add_filter('query_vars', 'foo_my_query_vars'); function foo_my_query_vars($vars){ $vars[] = 'propertyidtag'; return $vars; } Thank you for your help
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, url rewriting" }
How can I get all user options? The codex has a function called `get_user_option()` but it requires me to pass the name of the option. Is there a wp function to retrieve all user options? I just need to see a list of all options set for a specific user. The only other similar function I found is `get_alloptions()` but that has been deprecated.
You will get all the meta for the user by using get_user_meta function $all_meta_for_user = get_user_meta( [user ID] ); echo "<pre>"; print_r( $all_meta_for_user );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "options" }
What is the meta-box-order_post_hash used for? `meta-box-order_post_hash` is stored as an user option. I am sure it's related to `meta-box-order_post` but I could not find anything in the codex about it. So what is it for? And how can or should be used?
I could only find the following core code references for the `meta-box-order_` string: /wp-admin/includes/ajax-actions.php: update_user_option($user->ID, "meta-box-order_$page", $order, true); and /wp-admin/includes/template.php: ... get_user_option( "meta-box-order_$page" ) ... that's related to the ordering of meta-boxes. I doubt your `$page` value is `post_hash`, so my first guess is that this comes from a plugin/theme? If not then the user option might be dynamically constructed. Searching the wide world web gave be only this plugin on GitHub, that uses the `meta-box-order_post_hash` user meta key. _Thanks to @toscho for the information about the handy` y` key on GitHub, to retrieve permanent links to GitHub files that I didn't use in previous answers ;-)_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "user meta" }
Custom page pagination based on Kriesi pagination I am stuck on this problem: We have 2 custom post types on our website, both created the same way, only the name of the post type differs. In addition we have 2 custom page templates which show an archive of these custom post types. Both use the same logic / look and feel only the custom post type posts shown differ. Our problem is that we use custom pagination based on kriesi.at code. However for 1 custom page it works perfectly for the other one it isn't. We did a diff of all code and cannot find the difference. And biggest problem is that we have absolutely no clue how to debug this since the only difference is the custom post type value... Anyone suggestions on how to start debugging this?
when writing this question we suddenly thought that we did not try to change the permalink. After changing the permalink to another unique value it worked like a charm. So still not sure what was causing this issue but the above solved the issue. If anyone has a clue why the permalink was causing the problem please let us know, might help us by understanding the exact cause of the problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination" }
Page and Posts loading as index page? Not loading the content I've been developing a website on wordpress for some time now and came across some issues but until now I could figure it out, not today... Yesterday I've worked some more on the website and today when I came back to do some more work the pages on my site that are part of my navigation menu didn't load properly (minus the home page that is static and a news page that is the index page), they were loading the index.php page. Also with my posts in the news(index) page the load the index page instead of the post content. The URLs appear correct, but the loaded page is the index one. This doesn´t happen with the other pages I have that are not in the navigation menu and also with some custom post types, everything works fine there. The strange thing is that it happened from nothing, maybe is a quick fix... or not, I'm not an expert. Thank you in advance and if you could help me I would aprecciate it!
I figured it out, after trying a million things I tried one more, super stupid but it worked, I just went to permalink settings, clicked save changes and my posts and pages are working again... I don't understand why but finally it's working again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, menus, pages, navigation" }
add post content in meta description in yoast How can I add post content in meta description via `Title & Metas`? I have seen excerpt variable `%%excerpt%%` but it will give only excerpt but I want whole content in meta description. Can any one help me for this because I can not found variable for content? Thankns
Here is a safe and Yoast preferred method add_action('wp_head','add_custom_meta_description_box'); function retrieve_var1_replacement( $var1 ) { global $post; return strip_tags($post->post_content); } function register_my_plugin_extra_replacements() { wpseo_register_var_replacement( '%%mycustomdesc%%', 'retrieve_var1_replacement', 'advanced', 'this is a help text for myvar1' ); } add_action( 'wpseo_register_extra_replacements', 'register_my_plugin_extra_replacements' ); You can now replace your %%excerpt%% with %%mycustomdesc%%
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "seo, plugin wp seo yoast" }
Mass registrations on my blog. Disable specific domain? Since few days, every several minutes I get on my mailbox information about new user. I don't know what is the main purpose for that but I assume someone is checking something on my site and it not anything good. Is it anyhow possible to disable specific domain while user is filling email field? Should I be worried? !enter image description here
BTW you can try this one. I just put together something. It should block gmail.com domain. This function will check for email domain when someone tries to register on your website and throws an error if email domain is matched. function wpse_disable_email_domain( $errors, $sanitized_user_login, $user_email ) { list( $email_user, $email_domain ) = explode( '@', $user_email ); if ( $email_domain == 'gmail.com' ) { $errors->add( 'email_error', __( '<strong>ERROR</strong>: Domain not allowed.', 'my_textdomain' ) ); } return $errors; } add_filter( 'registration_errors', 'wpse_disable_email_domain', 10, 3 ); **OK I just tested it and it's working.**
stackexchange-wordpress
{ "answer_score": 9, "question_score": 7, "tags": "email verification" }
Target WooCommerce submit button I am trying to hook into the WooCommerce submit button and applying some custom jQuery scripts before submitting the order. However,I can't seem to target the submit button on the checkout page. I have tried the following: jQuery('form[name="checkout"]').submit(function(event) { alert( "Checkout submit!" ); console.log('test'); event.preventDefault(); }); And jQuery('#place_order').on("click",function() { alert( "Checkout submit!" ); console.log('test'); event.preventDefault(); }); None of which seems to work. Any ideas? The name of the form is checkout, and the id of the submit button is place_order. Thanks!
Please copy the woo-commerce checkout.js and paste in your theme folder and add following code in your function.php and after then you can change the checkout.js from your them. function so_27023433_disable_checkout_script(){ wp_dequeue_script( 'wc-checkout' ); wp_enqueue_script('checkout', get_template_directory_uri() . '/js/checkout.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'so_27023433_disable_checkout_script' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
How to make my third multisite blog start with id 1000? I'm making a new multisite install and would like my 'registration' blog id to be '1' (done), my 'template' blog id to be '2' (done), and then all subsequent subsites to start with a different blog id, like, 10,000. And, in case I add future template blogs, I would also like them to have a low id, like '3' and '4', not a high id like '10,003'. Any suggestions? Motivation: This is to mainly help organize my blogs and to separate my user blogs from my admin blogs.
In MySQL ALTER TABLE wp_blogs AUTO_INCREMENT = 10000; Than create the new site and switch back the auto_increment ALTER TABLE wp_blogs AUTO_INCREMENT = 3;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite" }
Overriding default template if page slug and post type are same I have created a post type named 'faq', and a page 'faq' for displaying the posts under faq. Also I have created a page template name faq and selected the faq page's template to this. Now the problem is the faq page always render default template, which is `archive.php` or `index.php`. I tried to change the template name to `page-faq.php` and `page-{page_id}.php` but failed to achieve desired result. Is there any way to override default template in this case if I would not willing to change the page slug or post type.
Easy way to achieve this. register_post_type( 'mypost', array( ... 'has_archive' => false, ... ) ); After updating this reset the permalinks 'Settings -> Permalink'
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "template hierarchy" }
Theme does not respect spaces between paragraphs in pages I am working with a theme that focuses on special types of posts. It seems that the author has neglected pages and as a result, paragraph spacing in pages is not respected. The next paragraph simply appears on the next line instead of leaving a line of space between paragraphs. This does not affect special posts, but it does affect pages. What is the best way to fix that?
The theme's style sheet uses the reset method to set all margins on the `<p>` tag (and many others) to 0 (this is common practice). So you would need to add a style declaration into your style sheet to add the top and bottom margin back in for the `<p>` tag. For example: you could add this to your style sheet after the reset. p { margin: 10px 0; } This will add a top and bottom margin of 10px. You can change this to whatever value you like. You could also set the margins individually. p { margin-top: 10px; margin-right: 0; margin-bottom: 10px; margin-left: 0; } .added p { margin: 0; } **Edit:** Included extra css to fix "Added by"
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, pages, formatting" }
Generating a certain sized thumbnail on the fly? I'm displaying a picture under each post on my homepage using the following PHP code: <div class="preview"> <a href="<?php the_permalink(); ?>" rel="bookmark" style="background-image: url('<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID), array( 300,300 ), false, '' ); ?>');"></a> </div> And the following CSS to make it appear at a certain size: .preview a { background-position: 0 50%; background-size: cover; display: block; height: 250px; } Is there any way to feed in the image dimensions when I get the image URL, so that I can link to something that's a specific size? So instead of having to load huge images, it just loads one that is something like 1200px by 250px, and grabs the middle part of the image rather than the top. Thank you :)
You can use Adaptive images WordPress plugin. It generates images on the fly and cache them. It gives to settings in admin section in which you can specify your breakpoint ( on which it will generate images ). You can also use Picturefill.WP WordPress plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, post thumbnails" }
custom fields not showing before get_header I am trying to use this code in my WordPress site <?php if(get_post_format() == 'video'){ function insert_game(){ get_template_part( 'content', 'video-top' ); } add_action( 'colormag_after_header', 'insert_game' ); } ?> <?php get_header(); ?> **and in content-video-top.php is this code** echo get_post_meta( $post->ID, 'video', true ); The problem is that it doesn't show the custom fields, **but after`get_header()` it works**.
It seems that at that point, `$post` is not yet defined, you can make sure by turning debugging on. Then add this before your `get_post_meta( $post...`: global $post; Or you can replace `$post->ID` with `get_the_ID()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, page template" }
Remove All Widgets from Sidebar Does someone know a solution for this? I want to remove ( **not unregister** ) all widgets from a sidebar with a function.
You could add this function to your functions.php file. add_filter( 'sidebars_widgets', 'disable_all_widgets' ); function disable_all_widgets( $sidebars_widgets ) { $sidebars_widgets = array( false ); return $sidebars_widgets; } You could also use the Wordpress conditional tags to disable widgets only on certain pages. For example; this would only disable widgets on the home page. add_filter( 'sidebars_widgets', 'disable_all_widgets' ); function disable_all_widgets( $sidebars_widgets ) { if ( is_home() ) $sidebars_widgets = array( false ); return $sidebars_widgets; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "widgets, sidebar" }
Add text to Title dynamically using tags I am trying to add custom text to title according to the tag selected. For example: If I've added a tag named 'Private', The title should look like "Page Title From title field + custom text assigned to the tag 'Private'". i.e. "Iron Man - Review - Awesome" here awesome will be the custom text assigned to the tag private. Please help. Thank you in advance.
The code below assumes that only one tag ( 'private' ) has a text associated with it: function add_tag_text_to_title( $title, $id = null ) { if ( has_tag( 'private' ) ) { return $title . ' - Awesome'; } else { return $title; } } add_filter( 'the_title', 'add_tag_text_to_title', 10, 2 ); If you have more than one tag with text associated with it: function add_tag_texts_to_title( $title, $id = null ) { $tag_texts = array ( 'tag1' => 'text1', 'tag2' => 'text2', 'tag3' => 'text3' ); $new_title = $title; foreach ( $tag_texts as $key => $value ) { if ( has_tag( $key ) ) $new_title .= ' - ' . $value; } return $new_title; } add_filter( 'the_title', 'add_tag_texts_to_title', 10, 2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "tags" }
Force authors to use Manual Excerpt in Wordpress and multiple Manual Excerpts I'm stuck with this thing. I have a multiple author website and I would like to force them to use the Manual Excerpt before they publish. Also, I want to display different custom fields for multiple Manual Excerpts so I can use them in some areas in my web, such as the slider or posts. Thank you.
I'd suggest this plugin: < It is very well maintained and documented. It will allow you to add one or more custom excerpt fields, manage the layout in the admin area and make them required so a post cannot be submitted without completing them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "excerpt" }
Widget logic conditional widget Is there any experience using widget logic, I want to display a widget on single custom post type with specific taxonomy. Tried using is_tax(taxonomy_name) || is_single() && in_term(term_name).
Before I start, I must say that your terminology is quite confusing and plain wrong. You should take your time and read through my answer to this question: Is There a Difference Between Taxonomies and Categories? As I stated before, there is no `in_term()` function to check if a post has a specific term. There is however a `has_term()` function which accepts the term as first parameter and the taxonomy name as second parameter. So your condition should look like this: ( _if this is for a specific post type outside the loop_ ) global $post; if ( $post->post_type == 'my_post_type' // checks the post type of the post && is_single() // Checks if this is a single post && has_term( 'term-name or id or slug', 'my_taxonomy', $post->ID ) // Check if post has specific term ) { // Do something if our condition is true }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional content" }
Orderby doesn't work like expected on custom query I have this custom query: query_posts( array ( 'orderby' => 'rr_recommends_count', 'meta_key' => 'rr_recommends_count', 'order' => 'DESC', ) ); Which orders the posts like this: 9, 8, 7, 6, 5, 4, 3, 2, **11, 10,** 1 etc. I see that the problem is that the meta_value field has a type of **longtext**. How can I fix the sort without changing the meta_value field type?
First of all, never ever use `query_posts`. It breaks the main function and all plugins and functions relying on the main query object. For custom queries, use `WP_Query` or `get_posts` if aren't looking to paginate the query As for the following line 'orderby' => 'rr_recommends_count', I can tell you that `rr_recommends_count` is an invalid value to the `orderby` parameter. Suspect that this is actually the key name, and the values are all numerical in that key, so you would use the `meta_value_num` value to the `orderby` parameter which is a valid value 'orderby' => 'meta_value_num', Please see Order and Orderby Parameters in `WP_Query`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "meta query, order" }
multisite detect subsite blog number We have a multisite installation of Wordpress where we show events from subsites on the main blog. for the detailed event pages which are shown on the main blog we would like to detect from which blog they coming from. We need to execute a switch_blog($numberblog) where $numberblog is the ID of the blog who owns the event. Could not find a function which does this, anyone able to help out?
the plugin we used for the events (Events Manager Pro) had an extra metadata field for each event which contained the blog id so this problem is solved
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
Multisite custom taxonomy archive issues We are using a WP multisite install. 3 subsites use the same theme, using a custom taxonomy which is defined inside the theme code. The issue we have is that the archive page for this custom taxonomy does work on 1 subsite but not on 2 others. Our question: * Is it possible that the permalink structure causes this although all 3 sites use different domain names? * In case the above can't be the problem does anyone have suggestions on possible causes of this issue? Or suggestions on where and how to start debugging?
SOLVED: This is issue was solved by correctly flushing rewrite rules: global $wp_rewrite; $wp_rewrite->init(); //important... $wp_rewrite->flush_rules();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, multisite" }
Get all registered wp theme customizer sections? Is there a way to retrieve all the registered customizer sections? I'm building out a custom customizer and don't want other plugin or themes who register custom sections to appear on this page. I can remove all the default sections, but I can't predict which plugins or themes will register sections. `$wp_customize->remove_section( 'title_tagline' );` removes the default title_tagline section. I can see all of the registered sections by doing `print_r( $wp_customize );`. I would just loop over that section and build an array to un-register, but I can't seem to access the array of registered sections due to it being protected. Is there any other way to retreive registered sections?
After digging around inside of some core files, I was actually able to get this resolved. The following function will retrieve all registered sections in the customizer and loop over each to un-register them altogether. This should run before registering any of your own custom sections, as to not remove your custom registered sections. function eherman_remove_registered_customizer_sections() { // retrieve the sections array $registered_sections = $wp_customize->sections(); // loop over and remove each section foreach( $registered_sections as $section ) { $wp_customize->remove_section( $section->id ); } } Not bad at all. Hopefully that helps others out as we move closer to a more powerful customizer! **Resources:** * WP Customizer Class
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "theme customizer" }
Wordpress login issue . Permission Problem I can't access wordpress admin panel after installation few plugins . it's show **You do not have sufficient permissions to access this page.** I follow many instruction but did't help my problem . 1. I am checking database prefix and usermeta table all is good. 2. Rename Plugins and themes folder . But this is not help me then define wp-config user and usermeta table also truncate user and usermeta table and import from new working db( changeing prefix when import ) But nothing help me . !enter image description here This is my user data what i get from when print current user information . Please help me out. ![enter image description here][2]
Assuming you have access to the database, try this: Set `db_version` in the `wp_options` table to `8204`. Log out and then back into wp-admin. Click the upgrade database button, this should restore all admin privileges.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login" }
WP-API : post_meta not updated... but have another entry When creating a post, I put some post_meta here is the code for the creation edition and deletion of a post < and here is the result of the post_meta when it's created Array( [time_client_email] => Array ( [0] => [email protected] ) [time_client_website] => Array ( [0] => clientwebsite.com ) ) When I update it here is the result Array( [time_client_email] => Array ( [0] => [email protected] [1] => [email protected] ) [time_client_website] => Array ( [0] => clientwebsite.com [1] => clientwebsite.com ) ) My question is : is it because of the revision.... or something is wrong.... because I think the desirable result would be ... if exist and the same value "do nothing" .... if exist and not the same value "replace" here's a link to the issue on github. <
I've answered my question... when your not giving the id of the post meta ... it's creating another one ... you give the id and it's updating... –
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "post meta, wp api" }
Add JavaScript in footer if shortcode used in page I want to add javascript to page footer if the shortcode is used into the page content. add_shortcode('show-popup', 'show_aip_popup'); function show_aip_popup($args){ // HTML Comes here for popup }
Please try this one function show_aip_popup($args){ wp_enqueue_script( 'parent-stylesheet', 'javascript file', false ); //your code for show shortcode data }
stackexchange-wordpress
{ "answer_score": -2, "question_score": 0, "tags": "shortcode, footer" }
Disable Facebook Comments Automatically On CPT I am working with the Facebook comments plugin. I have a custom post type that never uses Facebook comments. I am trying to create a function to automatically turn these off when the custom post type is published. In the database there is a meta key called **_disable_fbc** and it accepts two values. Having the meta_value as **on** turns the Facebook comments off. !enter image description here The custom post type is **music**. function on_music_publish( $post_ID ) { update_post_meta($post_ID, '_disable_fbc', 'on' ); } add_action( 'publish_music', 'on_music_publish', 10, 2 ); How can I make the following function work?
I ended up going with this type of solution. It seems to be working fine for me. I am open on ways to improve this code as it seems there is a better hook that could be used. function on_music_publish( $post_ID, $post ) { if ( $post->post_type != 'music' ) { return; } update_post_meta($post_ID, '_disable_fbc', 'on' ); } add_action( 'save_post', 'on_music_publish', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, post meta, publish" }
How to crop image from center using wp_image_editor I am working on WordPress plugin. In plugin the user upload images from meta field and in back end i use wp_image_editor for cropping and re sizing the images. The images re sized very well but on cropping the images not cropped very well. I give x-dimension 100 and y-dimension 0. $resize_img = wp_get_image_editor( $wpc_prod_img['wpc_resize_img'] ); if ( ! is_wp_error( $resize_img ) ) { $resize_img->crop( 100, 0, $wpc_image_width, $wpc_image_height, NULL, NULL, false ); } I want to cropped image from center of x-dimension and center of y-dimension. I tried this but its not work $resize_img->crop( 'center', 'center', $wpc_image_width, $wpc_image_height, NULL, NULL, false ); How can i do this. Is there any solution
Try this code $crop = array( 'center', 'center' ); $resize_img->resize( $wpc_image_width, $wpc_image_height, $crop);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, images, cropping" }
Make certain pages uneditable by editors? My Wordpress page has a few editors. They need this permission because they need to be allowed to change the posts/pages of others. However there two pages I want only me, the administrator to be able to edit. How can I accomplish that?
You can try the `map_meta_cap` filter: /** * Uneditable posts/pages for editors */ add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) { // Edit to your needs: $post_ids = [123, 234, 345, 456]; // Uneditable posts $role = 'editor'; // Uneditable by this user role // Make given posts uneditable for the above user role: if ( 'edit_post' === $cap && isset( $args[0] ) && in_array( $args[0], $post_ids ) && current_user_can( $role ) ) $caps[] = 'do_not_allow'; return $caps; }, 10, 4 ); to make certain pages/posts uneditable by editors.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "admin, users, user roles" }
Get a link to paged(<!--nextpage-->) part? I want to get a link (like `get_permalink($id)` ) to it's specific page of a post (created by `<!--nexpage-->` tag).. how to achieve this?
You're looking for: _wp_link_page( $page_number ); Must be used inside loop, and it return the opening tag: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, pages, paged, nextpage" }
wp_enqueue_script adds only the first script function banana_scripts() { wp_enqueue_script('grid', get_stylesheet_directory_uri() . '/js/jquery.min.js', null, null); wp_enqueue_script('grid', get_stylesheet_directory_uri() . '/js/main.js', null, null); } add_action('wp_enqueue_scripts', 'banana_scripts'); I have the above hook in my functions.php. The first js file gets included, the second not. Is it incorrect to call this function twice or more?
You gave each each script the same handle/id of 'grid' Try something like this. function banana_scripts() { wp_enqueue_script('grid', get_stylesheet_directory_uri() . '/js/jquery.min.js', null, null); wp_enqueue_script('grid2', get_stylesheet_directory_uri() . '/js/main.js', null, null); } add_action('wp_enqueue_scripts', 'banana_scripts');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "javascript, wp enqueue script, scripts" }
How can I add Javascript in the header of all post pages and only post pages I am using add_action('wp_head', 'function_that_returns_js_string') in `functions.php` but it is adding the string in the header across the site. How can this be narrowed down to be only included in post pages?
Check the type of the queried object on the page and the post type: function function_that_returns_js_string() { $obj = get_queried_object(); $type = is_a($obj,'WP_Post'); if (true === $type && 'post' == $obj->post_type) { echo 'your string'; } } add_action('wp_head', 'function_that_returns_js_string'); However, I am concerned that you are inserting a script directly into the head of the page rather than enqueueing it, which is more standard practice. The same trick will work to conditionally enqueue: function function_that_returns_js_string() { $obj = get_queried_object(); $type = is_a($obj,'WP_Post'); if (true === $type && 'post' == $obj->post_type) { wp_enqueue_script('jcrop'); } } add_action('wp_enqueue_scripts', 'function_that_returns_js_string');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "javascript, wp head" }
Display News Posts by Day with Post Counter I am building a site client who makes anywhere from 20-50 news posts per day. I'd like to have a news feed where it shows the date / post count as an H3 and then list all the posts for that day underneath. Example... **TODAY (4 posts)** \- News Article Link \- News Article Link \- News Article Link \- News Article Link **YESTERDAY (6 posts)** \- News Article Link \- News Article Link \- News Article Link \- News Article Link \- News Article Link \- News Article Link **MONDAY, JUNE 22, 2015 (3 posts)** \- News Article Link \- News Article Link \- News Article Link ...I can't find info anywhere on Google. Hoping this is possible. Thanks to anyone who can help. Justin.
Clever manipulation of your Loop code should prevent having to make numerous additional requests to the database. Proof of concept: $args = array( 'post_type' => 'post' ); $qry = new WP_Query($args); if ($qry->have_posts()) { $date = $count = 0; $content = ''; while ($qry->have_posts()) { $qry->the_post(); $tdate = mysql2date('Y-m-d',$post->post_date); if ($date != $tdate) { if ($date != 0) { echo $date.' ('.$count.' Posts)'; echo '<br>'; echo $content; echo '<br>'.str_repeat('-',50).'<br>'; } $content = ''; $count = 0; $date = $tdate; } $content .= '<br>'.get_the_title(); $count++; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts" }
How to add multiple custom URL variables? I am building a Wordpress plugin that looks for different custom variables in the URL. The way I am able to achieve that right now is with this code: function add_custom_query_var( $vars){ $vars[] = "variable1"; return $vars; } function add_custom_query_var1( $vars1){ $vars1[] = "variable2"; return $vars1; } add_filter( 'query_vars', 'add_custom_query_var' ); add_filter( 'query_vars1', 'add_custom_query_var1' ); I feel like this code is redundant and was wondering if there is a better way to do this. Thanks
I pretty sure this filter lets you add an array of variables. I've not tested this: function add_custom_query_vars( $vars ){ $vars[] = "variable1"; $vars[] = "variable2"; $vars[] = "variable3"; //... etc return $vars; } add_filter( 'query_vars', 'add_custom_query_vars' ); Or another way of doing it would be to do this: function add_custom_query_vars( $vars ){ array_push($vars, "variable1", "variable2", "variable3"); return $vars; } add_filter( 'query_vars', 'add_custom_query_vars' );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "plugin development, wp query, urls, variables" }
extract url from a hyperlinked string in PHP I need a function to extract the link (url) from a hyperlinked text in PHP. For example i get it a string and it returns me the link or url. Thanks before for your answers...
$arr_str = new SimpleXMLElement('<a href="www.example.com">Click here</a>'); echo $arr_str['href']; // will echo www.example.com Note that, SimpleXMLElement required PHP version above 5.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, urls" }
wp-login.php just refreshes the form fields I've recently moved a customers blog from one server to another. On the surface everything seems to be working fine - the blog is running and you can view the entries with no issues. The problem we're having is with the admin login page. When you enter your username and password it simply refreshes the page. No error messages or prompts are shown at all. I've followed the tips on this page: < Cookies are enabled, tried via several browsers Plugins folder has been renamed to plugins.old - aside from anything the only plugin within that folder was the default akismet one Uploaded wp-login.php from a fresh download of 2.7.1 Reset password via command line mysql URI is unchanged Not using secure HTTPS No errors about headers not being sent I've checked error logs debug and there's nothing appearing related to WordPress. ...what am I supposed to do?
This may be a file ownership or permissions issue. Try setting the permissions correctly as outlined here: Wordpress Permissions
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, reset" }
Deny dashboard access breaks ajax requests I need to restrict the access to the dashboard fon non-admin. Therefore i'm using this function in the functions.php: function ggp_restrict_dashboard_access_function() { if (!current_user_can('administrator')){ wp_redirect(home_url()); } } add_action('admin_init', 'ggp_restrict_dashboard_access_function', 1); Problem is that because of this, Ajax calls are returning a 301 for non logged in users as well as for logged in non-admin users. How can i workaround this?
You need to also check it's not an AJAX request inside your hook: if ( ! current_user_can( 'administrator' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) { wp_redirect( home_url() ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax, dashboard" }
Redirect users after first login I want to redirect my users to a page after they logged in for the first time. I also noticed some solutions like a redirect after the user was registered (redirect after first 48 hours) but the problem is that all users are registered already. Does anyone knows how to do this? Thanks!
Use following code to achieve your requirement. //hook when user registers add_action( 'user_register', 'myplugin_registration_save', 10, 1 ); function myplugin_registration_save( $user_id ) { // insert meta that user not logged in first time update_user_meta($user_id, 'prefix_first_login', '1'); } // hook when user logs in add_action('wp_login', 'your_function', 10, 2); function your_function($user_login, $user) { $user_id = $user->ID; // getting prev. saved meta $first_login = get_user_meta($user_id, 'prefix_first_login', true); // if first time login if( $first_login == '1' ) { // update meta after first login update_user_meta($user_id, 'prefix_first_login', '0'); // redirect to given URL wp_redirect( ' ); exit; } }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "redirect, login, front end" }
Which Wordpress version to use for improved plugin compatibility? I am currently using WordPress 4.2.2 and Woocommerce 2.3.11 - I find that many plugins associated with Woocommerce have not yet been updated for whatever reason. In some cases a whole year has gone by with no updates to the plugins. * Would it be advisable to regress to an older version of Wordpress? * Is there a recommendable version to go back to? Say WordPress 4.0/4.1/4.2? I understand that it may depend on my current situation. Most of the plugins i need to use are compatible to v4.1.5 only. * Is it advisable(a good/safe idea) to use WordPress 4.0/4.1? I am concerned about the security problems(if any) if i use and older version.
It is not advisable to run anything but the latest wordpress, especially with regards to security fixes. For a minior wordpress release, you can read the release notes and see if any of the changes are security related. If they aren't, then you can probably safely wait until the next security fix. In my experience, wordpress updates only sometimes break a plugin. The problem, though, is that if there is a security fix in an update, it is quite irresponsible to not apply the update, especially if you have sensitive data in your system. This is just the burden of modern software, updates are mostly required, but the ofter cause incompatibilities. A good solution is to set up a staging environment for yourself to see if the update breaks any plugins. If it doesn't, apply the update, if it does, start working on a contingency plan. Good luck,
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
Show all child categories associated to post ID within loop I'm looping through all posts and I'm trying to output the category nicename related to each post. So if there are categories A,B and C with post X only associated with categories A and C then I only want to output category A and C's nicename. Here's the loop: <?php $subs = new WP_Query( array( 'post_type' => 'case-study' )); if( $subs->have_posts() ) : while( $subs->have_posts() ) : $subs->the_post(); ?> <?php the_title(); ?> <p>Associated Child Categories</p> //Show nicenames of each child category associated to each post <?php $category = get_categories($post->ID); foreach(($category) as $cats) { echo $category->category_nicename; }?> <?php endwhile; endif; ?>
You should use `get_the_categories()` > Returns an array of objects, one object for each category assigned to the post. This tag may be used outside The Loop by passing a post id as the parameter. $categories = get_the_categories(); var_dump( $categories );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, categories, children" }
Override get_template_directory() in child theme? Is it possible to replace a `get_template_directory()` in my child's functions.php file? I want to make changes to the file: /** * Load Custom Post types file. */ require get_template_directory() . '/inc/post-types.php'; I'd obviously prefer my work not be overwritten when I update my theme, so can I un-register the parent file and then re-register my child's file in my child's functions file?
Late answer, but in Wordpress 4.7 two new functions were introduced to address this question. `get_theme_file_path()` (for absolute file paths) and `get_theme_file_uri()` (for URLs) work just like `get_template_part()` in that they will automatically look in the child theme for that file first, then fallback to the parent theme. In your example, you could rewrite it using 4.7 to look like this: /** * Load Custom Post types file. */ require get_theme_file_path( 'inc/post-types.php' ); More information here: <
stackexchange-wordpress
{ "answer_score": 29, "question_score": 12, "tags": "php, child theme" }
wpdb->get_var always returning 0 I am trying to run this statement: global $wpdb; $amt = $wpdb->get_var($wpdb->prepare("SELECT SUM(amount) as amt FROM wp_pay_table WHERE postid = %i", $pid)); ...but $amt always comes out as 0. I have checked that $pid is the correct value. I have also run the sql statement in my db and it returns the correct value (should be 75). I also tried get_row but had the same issue. Any help greatly appreciated.
`prepare` accepts three placeholder arguments\-- " %s (string), %d (integer) and %f (float)". You have used `%i`. That isn't going to get through the sanitization process. That is why you are getting `0`. You need `%d` instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, sql" }
Link to Homepage in Menu I am using the mh-newsdesk-lite wordpress theme in one of my client's websites and I'd like to have a link to the homepage in the menu. It ideally would be accomplished without php, or without any code, but I've been looking and I do **not** want to make my homepage static, as I have latest posts there. Thank you in advance!
You can take the following steps 1. Go to You Dashboard 2. Click Appearance > Menus 3. Under Pages, Click View All 4. There will be a 'Home' option 5. Check that Home Option 6. Click 'Add to Menu' 7. The new Menu item will appear in the right block 8. Drag the home menu to the top 9. Save the menu !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "menus, pages, links, homepage" }
Where is the stylesheet code? I want to change some values in this code on the header of my site: <link rel='stylesheet' id='style-css' href='localhost/wp-content/themes/xxxx/style.css' type='text/css' media='all' /> I can't find this line in any of the source code, or the database. Where is this code?
The most common would be /wp-content/themes/your-theme-name/style.css but this may not be the case depending upon the theme you are using. The easiest way to find out is to use Chrome Developer Tools. In Chrome open your website and right click on the element you would like to alter the CSS for, then click 'Inspect Element'. The CSS files and classes which apply to that element will be listed in the right hand pane.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, custom header" }
Replace existing pages with new pages, keep menu links I basically want a plugin or method that would give the same functionality as 'Enable Media Replace' but for replacing pages and posts, instead of redirecting, or manually editing. I've searched high and low and while I've found similar, or workarounds, or manual editing of DB, these weren't ideal, or beyond my abilities. I'm redesigning an existing WP site, have changed template and have added many new pages, with multiple template level customisations (on >20 pgs), but want to keep the existing (google indexed) links throughout intact - and not have to change menu. I'd like to ideally: Change urls, slugs, etc of my NEW pages to match these existing links sitewide (leaving existing redundant &/or deleted). Is there a plugin or method that would be faster than me deleting and manually renaming all the new pages?
I was shocked to see that such a simple thing is not readily supported. I was even more shocked to see that no one had a good answer here on StackExchange! Happily, I found this post: < ...and am grateful for the answer provided by Joy (@joyously on WordPress.org and Slack) "If you need to build a new version over a long period of time, start a new page and only save Draft. [You can also save and publish as another page name so others can review it while under construction.] When it is ready, go into the Text mode of the editor and copy all. Then go to the old page Text mode and select all, and paste. Then save the old page (with new content)." So: 1. Use the text-mode editor to copy the content of the new page. 2. Open the old page, go to text-mode editor and paste the copied content from the new page. Enjoy!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "plugins, posts, pages, mysql, customization" }
Show all posts shows a blank white page in WP 4.2.2 In show all posts I have changed the number of items pe page from 20 to 500 and after that I got a timeout as it could not display all the posts. And now every time I go to show all posts I get a white blank page and no posts and I am not able to change the number of items to be displayed on the page.
Install and activate _User Meta Manager_ plugin. Go to `Users -> User Meta Manager`. Under your user click on `Edit Meta`. From pull down list of meta keys select `edit_post_per_page` and click `Submit`. Change the value to 10 and click on `Update`. All done.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, bug" }
passing variables inside a widget add_action Here's my code inside a widget class: function widget($args, $instance) { add_action('wp_footer', function () { echo $instance['title'] }); } It doesn't output `$instance['title']`. I tried passing the `$instance` parameter in the function, and even tried `global $instance;`, but neither worked.
Use the `use` keyword: $title = $instance['title']; add_action( 'wp_footer', function() use ( $title ) { echo $title; });
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "widgets, actions" }
How to get WP editors tinyMCE instances My main goal is to get editor content when it changes and update a live preview. For this I need to add an event listener to the editor. BTW, I have two editor in the same page and the page is loaded via ajax. Now back to my problem. I can't get to the instance of the tinyMCE editors. I can `console.log()` them but get empty result when I try to stringify them. Below is the result of `console.log(tinymce.editors)`. !console.log\(tinymce.editors\) So, whenever I try to access editors using `tinymce.editors.contentleft`, `tinymce.editors['contentleft']`, `tinymce.get('contentleft')` or `tinymce.EditorManager.get('contentleft')` in all these cases I get `undefined` or `null` Working more then couple days on this. Would appreciate a proper direction soon.
If you wait for the `SetupEditor` event then you can access the editors: add_action( 'admin_print_footer_scripts', function () { ?> <script type="text/javascript"> jQuery(function ($) { if (typeof tinymce !== 'undefined') { tinymce.on('SetupEditor', function (editor) { if (editor.id === 'contentLeft') { // Could use new 'input' event instead. editor.on('change keyup paste', function (event) { console.log('content=%s', this.getContent()); }); } }); } }); </script> <?php } );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "tinymce, wp editor" }
Get all products with a custom attribute I want do a custom query to get all products with an especific attribute ("demo" in my case) The query what i want returns from this: a:5:{s:4:"demo"; a:6:{s:4:"name"; s:4:"DEMO"; s:5:"value"; s:366:"LINK TO DEMO"; s:8:"position"; s:1:"0"; s:10:"is_visible"; i:0; s:12:"is_variation"; i:0; s:11:"is_taxonomy"; i:0; } } I don't know how do an $args to get products. I want $args be something like this: $args = array ( 'meta_query' => array( array( 'key' => 'meta_value', 'value' => 'demo', 'compare' => 'LIKE', ), ), ); Thanks!
OK I HAVE ALREADY!! yuhuuu! Thanks a lot guys!! I have this: $args = array ( 'post_type' => 'product', 'posts_per_page' => -1, 'meta_query' => array( array( 'value' => 'demo', 'compare' => 'like' ), ), ); Well this works at least for me Thanks thanks!! Best regards!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "customization, woocommerce offtopic" }
Make inline edit in wp_list_table I'm very new to JavaScript and jQuery. However, I've jumped into trying to make inline edit for my `wp_list_table` but find it difficult to catch the class for some reason. The classes for the column I'm trying to catch is named <td class="director column-director"> I've tried the 2 following statements below to check that I actually catch the class correctly: $( ".director").click(function() { alert( "Handler for .click() called." ); }); $( ".director", '.column-director' ).click(function() { alert( "Handler for .click() called." ); }); The console shows no errors and nothing is happening when I click the `<td>`. Is there anyone that can tell me what I'm doing wrong?
Replace `$( ".director", '.column-director' )` by `$( ".director, .column-director")` and also replace `$` by `jQuery`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "jquery, wp list table" }
Getting Category Children i have a problem understanding the get_terms function All i want is getting all the children of specific category so that it can be listed. But i don't really know how the $args works. So with this `get_terms(category, $args);` I tried to use the child_of $args = array( 'child_of' => 0, 'childless' => false, ); But it gives all the category while i only need the child of a category. Changing the value to "1" gives empty result. Then i tried the 'slug' $args = array( 'slug' => 'on-going', 'child_of' => 0, 'childless' => false, ); ` This gives nothing but "On-going" only. This is the category tree in my wordpress !category The only thing i want is listing all child category of "On-going", that's it.... Thanks
The `child_of` parameter excepts an integer value of the specific term you need to get descendants from. This means that you need to get the ID from the `On-going` category term and then passing that ID to the `child_of` parameter. To note, the `child_of` parameter returns **all** descendants of the term passed, this includes direct children and all children of those children etc. If you only need first level children of a specific term, then you need to pass the term id to the parameter `parent`. If you do not have the exact id, you can use `get_term_by` to get the id and then pass that to `child_of` in `get_terms` ## EXAMPLE This example shows how to get the term ID if you only have the term name, like in your case `On-going` $get_term_id = get_term_by( 'name', 'On-going', 'category' ); $terms = get_terms( 'category', array( 'child_of' => $get_term_id->term_id ) ); var_dump( $terms );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, array, terms" }
JQuery UI not loading without explicit loading of jQuery I know there are a lot of questions regarding this issue, but I can't figure out mine here. I'm trying to load the whole jQuery UI ( Actually I need only the Slider ) and I successed. This is my enqueing which is working: wp_enqueue_script('jquery-google-lib', ' array('jquery'), '2.1.4'); wp_enqueue_script('jquery-ui', ' array('jquery'), '1.11.4'); wp_enqueue_style('jquery-ui-css-google-lib', ' And this is the working various. When I check my head section, I can see I load jquery twice. I read the codex and says that WP loads jquery and jquery UI by default. Why I cannot use them and load them twice? When I remove the jquery enqueueing, jquery UI is not loading. Is it a good practice to load jquery from external sources? Why the wordpress jquery is in version 1.4.1 and google's 2.1.4? When there are these libraries loaded, why can't I use them in the front end? I got quite confused about this.
jQuery and the jQuery UI Slider are both registered by default by WordPress. In order to use them, all you should need to do is something like this: add_action( 'wp_enqueue_scripts', 'wpse192997_load_slider' ); function wpse192997_load_slider() { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-ui-slider' ); } Note, though, that WordPress uses jQuery in `noConflict` mode, which means that the `$` variable used in most jQuery code samples on the Internet won't be available. You can get around that by using the techniques listed in the _jQuery`noConflict` Wrappers_ section of the Codex article on `wp_enqueue_script()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, jquery ui" }
Load custom PHP on a custom URL via a plugin I am looking into having a plugin developed that loads a PHP script (`myscript.php`) on a custom URL. It's very important to achieve this functionality with a plugin. Example: * `example.com/myscript` \- loads myscript.php * `example.com/myscript/example` \- prints out "example"
Use `is_page()`. The `is_page()` function accepts page title, slug or id. Documentation <?php if(is_page('myscript')) { include '/path/to/myscript.php'; } ?> **UPDATE** To add it to the content, you have two options **1\. Find the content function in your template** Find either `the_content()` or `get_the_content()` in your template. Place it immediately after that function (or before if you want it before). **2\. Add A Filter** Move the above code into your theme's `functions.php` file and wrap it in a function. Then add a filter to `the_content()` to make it include your new function. Your code should look something like this: function my_the_content_filter(){ if(is_page('myscript')) { include '/path/to/myscript.php'; } } add_filter( 'the_content', 'my_the_content_filter' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, permalinks" }
Activate Child Theme with Codex I know there is an option to have the following code in the wp-config.php file: define('WP_DEFAULT_THEME', 'x-child-integrity-light'); define( 'TEMPLATEPATH', 'wp-content/themes/x'); I currently have this commented out and I'm trying to use the WP Replicator to replicate sites in a multisite install. I'd like to have the code automatically activate the child theme when it's installing the new site. By default, it's making the Twenty Fifteen theme active. How can I go about doing this?
Use `switch_theme` as already indicated in another answer, but hook it to `wpmu_new_blog` > This function runs when a user self-registers a new site as well as when a super admin creates a new site. hook to 'wpmu_new_blog' for events that should affect all new sites. > > < If not the code will run constantly, which will be inefficient and make switching themes impossible ( or unpredictable ). In other words: function default_theme_wpse_193024() { switch_theme('twentythirteen'); } add_action('wpmu_new_blog','default_theme_wpse_193024'); For `switch_theme()`, despite the parameter being named somewhat inexplicably "stylesheet", use the name of the theme folder. Per the Codex: > Accepts one argument: $stylesheet of the theme. ($stylesheet is the name of your folder slug. It's the same value that you'd use for a child theme, something like `twentythirteen`.)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, child theme" }
Stylesheet not loaded on register page Using WordPress 4.2.2. Im trying to add some custom fields to the registration page. I have gotten the fields to show up there now, but for some reason i cannot get the stylesheet to load there too. The stylesheet loads fine on all other pages it seems but not the register page. Im using this to load the scripts add_action('wp_enqueue_scripts', array(&$this, "enqueueScripsAndStyles")); public function enqueueScripsAndStyles() { //Styles wp_enqueue_style('sh_billing_styling', plugins_url('/css/sh_billing.css', __FILE__)); wp_enqueue_style('sh_billing_fontawesome', plugins_url('/css/font-awesome.min.css', __FILE__)); //Scripts wp_enqueue_script('sh_billing_radiobuttons', plugins_url('/js/custom-form-elements.js', __FILE__)); } Am i missing something? Thanks!
You need `login_enqueue_scripts` for the login page. See: < Swap that out in your `add_action`, or add a new one, and it should work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp enqueue style" }
How to change user password with wp-cli? wp-cli is great. But it's not clear how I can quickly change a user password with it. How to change a user's password programatically can probably help to figure this out. Although `wp user update username --field=password` is not gonna cut it, apparently `md5` is deprecated so it should go through `wp_set_password`.
This does the trick: wp user update USERNAME --user_pass="PASSWORD" (Found it here.)
stackexchange-wordpress
{ "answer_score": 51, "question_score": 42, "tags": "password, wp cli" }
How to run a php file that uses wordpress functions from command line? I am using wordpress functions in a custom php file including `wp-load.php`, run from browser it is fine, but run from command line with `php /path/.php` `wp-load.php` causes problems: Warning: Cannot modify header information - headers already sent in /../wp-includes/ms-settings.php on line 162 code example to reproduce: echo 'something'; require "/../wp-load.php";
WordPress has a command line library called WP-CLI. You can extend it to create your own commands. I would recommend this for any work on the command line.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, command line" }
How can I bulk import into galleries? I have a large number of photo galleries in a database-driven site that I want to migrate into WordPress. I can get the metadata and associations out of the database. Is there a way to bulk import the photos into WordPress and generate photo galleries?
So I don't think it was an elegant solution, but this is what I did. I wrote a plugin that: * Looped through the galleries in the old database * Created a post for each gallery (I chose to use the envira gallery plugin) in the format used by a sample envira gallery post * Looped through all the images in each old gallery and attached them to the new gallery post with appropriate metadata
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "gallery, plugin nextgen gallery, bulk import" }
Reloading page with a query string upon login for admins After users with specific roles log in, I would like to reload the current page with a query string added (to trigger a message via JavaScript). How can this be improved? function show_hi_admin_message() { global $current_user; get_currentuserinfo(); if ( user_can( $current_user, 'administrator' ) ) { ?> <script> $(function() { window.location.replace(window.location.href.split('#')[0] + '?message=hiadmin'); }); </script> <?php } } add_action( 'wp_login', 'show_hi_admin_message' );
Try using the filter hook: function user1462_login_redirect( $redirect_to, $request, $user ) { global $user; if ( isset( $user->roles ) && is_array( $user->roles ) ) { if ( in_array( 'administrator', $user->roles ) ) { return $redirect_to . '?message=hiadmin'; } else { return home_url(); } } else { return $redirect_to; } } add_filter( 'login_redirect', 'user1462_login_redirect', 10, 3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login, actions, authentication" }
Wordpress get_posts by category I have the following bit of code: $args = array( 'posts_per_page' => -1, 'category' => 7, 'orderby' => 'name', 'order' => 'ASC', 'post_type' => 'product' ); $posts = get_posts($args);var_dump($posts); This should return one post I know that is in the category, but it isn't. If I leave out the 'category'-argument, I get all the products, so I know this should normally work. If I change the category to 1 and take out my custom post type (product), I get my default posts. I can't see what's wrong with this. Can anyone spot what the problem is?
In all probability you are using a custom taxonomy, and not the build-in `category` taxonomy. If this is the case, then the category parameters won't work. You will need a `tax_query` to query posts from a specific term. ( _Remember,`get_posts` uses `WP_Query`, so you can pass any parameter from `WP_Query` to `get_posts`_) $args = [ 'post_type' => 'product', 'tax_query' => [ [ 'taxonomy' => 'my_custom_taxonomy', 'terms' => 7, 'include_children' => false // Remove if you need posts from term 7 child terms ], ], // Rest of your arguments ]; ## ADDITIONAL RESOURCES * What is the difference between custom taxonomies and categories
stackexchange-wordpress
{ "answer_score": 23, "question_score": 11, "tags": "get posts" }
Register Page Template from Plugin I'm trying to figure out how to properly register a page template (and all of the associated assets, like CSS and Images) from a plugin. Basically, I've created a landing page that I want to live outside of the Theme, so I can use it on multiple websites. My code was as follows: add_filter( 'page_template', 'custom_page_template' ); function custom_page_template( $page_template ) { $page_template = dirname( __FILE__ ) . '/custom-page-template.php'; return $page_template; } But I'm not seeing the page template within WordPress.
You misunderstand what `page_template` does. It does not create a new template that you will "show up" somewhere and that you can use. It replaces the `page.php` template provided by the theme. I think that what you want is `template_redirect`: function custom_page_template( $page_template ) { if (is_home()) { get_header(); echo 'do stuff'; get_footer(); } } add_filter( 'template_redirect', 'custom_page_template' ); Or `template_include`: function custom_page_template( $page_template ) { if (is_home()) { $page_template = plugin_dir_path( __FILE__ ) . 'custom-page-template.php'; return $page_template; } } add_filter( 'template_include', 'custom_page_template' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, templates, page template" }
How to add a class to figure tag for featured images? I'd like to add a class to tag so that the caption for my featured image will show on hover. Currently, this is the code when I use FireBug: <div class="td-post-content"> <div class="td-post-featured-image"> <figure> <a class="td-modal-image" data-caption="test caption lorem ipsum" href=" <figcaption class="wp-caption-text">test caption lorem ipsum</figcaption> </figure> </div> </div> I'd like to add: `<figure class="wp-caption">` , but I don't have any idea which file should I edit. I am unable to find it on any of the PHP files in the theme. When I upload an image to the blog post, the caption will show on-hover because the figure tag has the "wp-caption" class, except for the featured image. Any one have an idea?
jQuery( document ).ready(function() { jQuery("figure").addClass("wp-caption"); }); You could use jQuery to add a class.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails" }
NextGEN Gallery - set lightbox image size I use NextGEN gallery with lightbox effect. Is there any way how to set the lightboxed image to f. ex. to max width: 600px? Without resizing the source image? I have tried all of possible Lightbox Effect setting, but nothing has helped. We use big pictures (+3000px width) because our users can download them through NextGEN Download Gallery so we don't want to resize them. But if you click on image as a lightbox is loaded the big image which is really useless and pretty big so it takes time and data traffic. I have read throught this topic but it didn't worked for me: * auto-resize-gallery-based-on-browser-size-or-scrn-resolution * nextgen-problem-resize-images-automatically-in-screen-resolution-function Thanks a lot for your help!
I've finally founded the solution, so if you have same troubles as me: 1) let the NextGenGallery automaticaly resize uploaded images 2) for downloading hi-res image you have two options how to use NextGEN Download Gallery 1. upload images whenever you want on your site and just change the path by the `addfilter ngg_dlgallery_image_path` \- see here on WP forum for detailed answer 2. or use backup files created by NextGenGALLERY by changing the source code of plugin - see here or you combine them into addfilter and use _backup image (which is the best I think)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin nextgen gallery, lightbox" }
Question on using custom structures for categories Im trying to create a topics "section" similar to what Justin Tadlock has on his site but i'm not sure **how** he is doing this. Categories? Tags? or what? I tried changing the Category base to topics as the instructions state: > If you like, you may enter custom structures for your category and tag URLs here. For example, using topics as your category base would make your category links like < Now assuming my category is "foo", when I visit ` I see the proper listing of articles categorized as "foo". But when I back out to ` i get ...nothing. Whereas I assumed I would get a list of all categories. Again looking at Justin Tadlock's site, it appears each item in his "Topics Archive" is actually a tag? How is this done? Is he using a Custom taxonomy or what? How do I approach this? Please advise. \--pkd
The simple and quickest solution is showing categories list by using sitemap plugin with short-code. For example this plugin WP Sitemap Page. Install it and place shortcode on page. Second option is create page template for category list. Using wp_list_categories() Thanks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, custom taxonomy, theme development, taxonomy" }
Modify files without losing customization after updates I would like to know what is the best way to modify a file in Wordpress, such as header.php or single.php so when you update the theme, the changes remain there. I am not sure if this can be done with a child theme or if a plugin is needed.
If you want to make changes to the template files (e.g. header.php, single.php, etc) you should create a child theme. Here's the Codex link to help you create your Child Theme
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization" }
Why does wp_enqueue_style() in plugin not load stylesheet? I'm trying to load a custom stylesheet (for the front-end, not admin area) via plugin. As near as I can tell, I'm doing things the way the Codex says is correct, but my CSS doesn't get loaded. This is what I have: /* * Load stylesheets, etc. */ function cl_chanimal_scripts() { //Register CSS wp_register_style('cl-chanimal-styles', plugins_url('css/cl-chanimal-styles.css', __FILE__)); //Use it! wp_enqueue_style ( 'cl-chanimal-styles' ); } add_action( 'wp_enqueue_scripts', 'cl_chanimal_scripts' ); Am I using the wrong action hook? It is possible to load front-end styles via plugin, is it not?
First thing to mention is that you don't need to use `wp_register_style` if enqueuing within the same function. You can replace it with `wp_enqueue_style` and remove the duplicate. As for why your stylesheet isn't loading, start by checking the file path. Try this instead: `wp_enqueue_style('cl-chanimal-styles', plugin_dir_url( __FILE__ ) . 'css/cl-chanimal-styles.css' );` <
stackexchange-wordpress
{ "answer_score": 9, "question_score": 6, "tags": "plugins, css, hooks" }
Include Class File in Wordpress I'm including a Class file in `functions.php` file require_once get_template_directory() . "/core/classes/General.php"; require_once get_template_directory() . "/core/classes/User.php"; When I do `$user->getCredits($user_id);` in some page, it works fine. But when I tried doing that same line of code in `header.php` it prompts an error of `Call to a member function getCredits() on null`. So what I did is I required the same file in `header.php`, it still gives the same error, when I removed the included file in `functions.php` the error was removed and the code in header.php works (`$user->getCredits($user_id)`) but then in normal pages it does not detect the required file. Any solution for this stuff?
Please clarify where you initiate the object $user in both ways (function.php and header.php). This is another thread on stack with similar kind of issue, have a look: Organizing Code in your WordPress Theme's functions.php File? Thanks, Vee
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, include" }
captiva Theme Error I have Install Captiva in my system local.its showing error like this Warning: POST Content-Length of 36013235 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 Are you sure you want to do this?
8388608 bytes is 8M, which is the default post size limit in PHP. Update your `post_max_size` in php.ini to a larger value, may be 50M. `post_max_size` sets the maximum amount of data that can be sent via a POST in a form.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Problem after updating plugins So today i updated my plugins, everything went smoothly, but later i found out that my website is messed up. All the custom taxonomies are gone, then one of my plugin disappear somehow. I tried to reinstall the plugin, but i got this error Installing Plugin: WordPress SEO by Yoast 2.2.1 Downloading install package from Unpacking the package… Installing the plugin… Destination folder already exists. /customers/b/1/f/yahya98.com/httpd.www/wp-content/plugins/wordpress-seo/ Plugin install failed. Well, i haven't tried deleting the folder manually from FTP, but i don't want to make a wrong step, there's more than 40 post in my blog, it's a big problem if i have to re-write meta description and the other things for every post... so i post it here in case there's an alternate way.
There is problem with the "wordpress-seo" permission so please following steps. There are two way 1) Upload from the wp-admin Step 1 -> Change the "wordpress-seo" permission or rename the "wordpress-seo" plugin to another Step 2 -> If you have change the permission then just upgrade the plugin and if you have rename the plugin dir then you need to follow the install new plugin steps. 2) Change the file using FTP: Step 1 -> Take backup of your old plugin Step 2 -> change the plugin name or delete from the server Step 3 -> Upload the plugin via FTP It will not remove the data.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, admin, errors, updates" }
Ignore/Skip default value on orderby menu_order? Is there a way to query all pages and order them by `menu_order` **but** ignore those pages that the default value of `0`? I was trying to do something like this: $the_query = array( 'post_type' => self::POST_TYPE, 'posts_per_page' => $total, 'product_cat' => $product_category_name, 'orderby' => $orderby, 'suppress_filters' => '0' ); Or do I need to create a filter to alter the `WP_Query`? any ideas? cheers
You can try the following ~~(untested)~~ mini plugin: <?php /** * Plugin Name: Support for ignoring the default menu order in WP_Query * Description: Uses the _ignore_default_menu_order argument * Plugin URI: */ add_filter( 'posts_where', function( $where, $q ) { global $wpdb; if( (bool) $q->get( '_ignore_default_menu_order' ) ) { $where .= "AND {$wpdb->posts}.menu_order <> 0"; } return $where; }, 10, 2 ); Then you should be able to use the new custom query argument like: $query = new WP_Query( [ '_ignore_default_menu_order' => true, ] ); to ignore posts with the default menu order (`0`). You could also extend this to support any menu order as user input.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query" }
Set post tags using tag ID I want to set post tags to a new value. Is there a way to use the **tag ID** to do it? The `wp_set_post_tags` only accepts the **tag name** or an **array of tag names**. <?php wp_set_post_tags( $post_ID, $tags, $append ) ?> The reason why I want to set the tag using the `ID` is I don't want to make an additional call for getting the full tag object.
For non-hierarchical terms (such as tags), you can pass either the term name or id. If you pass the id there is only one caveat: You must pass it as an integer, and it must be in an array. This is necessary because any non-array value passed will be converted to a string, which will be interpreted as a term name. $tag = '5'; // Wrong. This will add the tag with the *name* '5'. $tag = 5; // Wrong. This will also add the tag with the name '5'. $tag = array( '5' ); // Wrong. Again, this will be interpreted as a term name rather than an id. $tag = array( 5 ); // Correct. This will add the tag with the id 5. wp_set_post_terms( $post_id, $tag, $taxonomy ); This function will only work on the native post type.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, tags, id" }
How to add a user profile page to frontend? I am looking in using wordpress for ecommerce by using woocommerce, as a newbie i don't know how to set up a user profile page outside wordpress installation (so the clients don't see the back end profile in wordpress). Also, if some one know a complete shop theme in wordpress that has already this feature, that will make my life easier. Thank you in advance for your answers. Cheers.
If you're using WooCommerce, they have a shortcode that displays the logged in user's account details on a front end page: `[woocommerce_my_account]`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "users, woocommerce offtopic, front end, profiles" }
Should non-WordPress data get its own DB? I couldn't find anything on Google or on here about best practice for data that is not really Wordpress related. Say we have a database of clients that we'll be accessing through PHP/SQL. Should I just create new tables within the wordpress database or is it good practice to keep these in completely separate databases? Currently its very basic and was actually being done as an external CSV. Moving forward though we want it to be a database and eventually clients will have a login area as well.
WordPress uses a prefix by default just in case the database is being used by more than WordPress. Since creating a new DB is pretty simple I would go that route. You would get the potential benefit of it being something separate that you can easily export, import or blow away if needed and also the potential security benefit if your WP site gets hacked this DB is separate (and vice-versa). If you do decide to use the same DB then you should prefix your tables to make them easier to know what they are used for.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "database, customization" }
Rewritten URL not loading WordPress environment I have a page that I am sending users directly to so I can serve them a PDF dynamically created using the FPDF library. Since I'm sending them directly to the file which generates the PDF, I'm rewriting the URL. In the original file I use `require_once('wp-load.php')` with the correct path in order to load the WordPress environment. It loads perfectly fine and spits out the PDF when I go to `website/path/to/file.php?p=foo&q=bar` but when I go to `website/rewritten?p=foo&q=bar` the `require_once()` function is breaking. I can tell that my rewrite rule is working properly because when I add debug messages to the file, they are printed when I go to `website/rewritten?p=foo&q=bar` and using `dirname(__FILE__)` returns the path of the actual file not the template. Do I need to change the require path or something to load WordPress properly? I can't seem to figure it out no matter what I try.
If anyone is wondering I figured it out. Since I was hosting my WordPress site on a Chassis server, the path I needed to use in my `require` statement was different than the actual path on my machine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rewrite rules, paths, wp load.php" }
WP_Query with meta_value LIKE 'something%' I have read several questions like this (for example, this), but no equal. I WP_Query need to perform a LIKE on a meta_value. My problem is that I want the like is as follows: meta_value LIKE 'value%' and I can not solve. My code is as follows: $today = '0702'; /*(month and day)*/ $args = array ( 'post_type' => 'post', 'posts_per_page' => $number, 'orderby' => $sort_by, 'cat' => '2' 'post_status' => 'publish' 'ignore_sticky_posts' => true, 'meta_key' => 'date' 'meta_value' => $today, 'meta_compare' => 'LIKE' ); Thanks!!! :)
For a left-sided match you can get around the automatic adding of `'%'`'s by WP by using regular expression `RLIKE`: 'meta_value' => '^' . preg_quote( $today ), 'meta_compare' => 'RLIKE' Similarly for right-sided match: 'meta_value' => preg_quote( $today ) . '$', 'meta_compare' => 'RLIKE'
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "wp query, meta value" }
I have index.php and other files, how do I display other pages? I'm converting an HTML theme into WP. I have index.php, header.php, footer.php, which are from HTML. Then I created pages from within admin area like about-us etc. Created a menu and linked those pages to the menu. The menu is showing fine, but instead of pages I created WP is displaying index.php. So I guess I need a template to display about-us and other pages. If it's a duplicate please post a link in a comment, I mean an exact duplicate not something that I have to sit and guess the answer. Thanks I tried to read an article in Codex but its not well written, sounds like gibberish. Should be straighforward, I just need to display pages I created from within the admin area.
The template for the page is called `page.php` and should be in the same theme folder as index.php (alternatively you can use the `is_page()` function to do a template inside index.php but it's more difficult and there's little point to that). Best way forward is to study an existing theme and figure how things work. A look at the template hierarchy should help as well.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "pages, templates" }
Expandable WordPress content (text) inside a post I've created a CPT in my WordPress site. In this CPT I have the content element (which is the default WP content) and want to make it expandable, I mean, while viewing the CPT I want it to only display a few lines of text until you press the view full content or something similar, all this inside the post view. Like in the image below: !Expandable WordPress content inside a post
I solved it using the following WordPress Plugin, which has plenty of options to customize: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, content, the content" }
How to order by post_status? I'm using `get_posts()` like this: $posts = get_posts(array('orderby' => 'post_status')) which is not possible cause it's not in the allowed keys in the `parse_orderby()` method How to get around this limitation?
You can use `'posts_orderby'` filter to change the SQL performed. Note that: * using `get_posts()` you need to set `'suppress_filters'` argument of `false` for the filter to be performed * if you don't explicitly set `'post_status'` you'll get only published posts (so no much to order) Code sample: $filter = function() { return 'post_status ASC'; }; add_filter('posts_orderby', $filter); $posts = get_posts('post_status' => 'any', 'suppress_filters' => false); remove_filter('posts_orderby', $filter);
stackexchange-wordpress
{ "answer_score": 10, "question_score": 6, "tags": "wp query, get posts" }
Add data to post edit page, when post is published I need to customize the "post edit page", for a custom post_type, but to keep things simple let's say it's on the post_type post for now. When the post status is published, I need to run a PHP script that fetches some data from my database, based on the post_id of the current post. **Question:** Where do I add this script?? Thanks.. !enter image description here
Search for `add_meta_box()`. This function is the key to add custom areas to the edit screen and inside this can you handle your custom requirements.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp admin, dashboard, post editor" }