INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What are the security reasons to disallow Microsoft Word uploads? When I try uploading a .doc or .docx file I get this message: > Sorry, this file type is not permitted for security reasons What are the security risks involved in a multisite installation (3.9.1)? I know how to enable the feature. Thank you.
`.doc` files can contain executable scripts, and there is no way to make sure they are safe. The same applies to SVG and some other file types. If WordPress would accept `.doc` files from any user with the capability `upload_files`, these files could be used to send malicious code to visitors.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "uploads, security" }
Display an authors post on a single page only when they are logged in I am having trouble finding a solution or the correct tutorial on how to get this done, I have been looking for weeks and still no outcome. What I am trying to accomplish is display all post on the front end (single.php) of an author (Author A) who is logged on. When Author A logs off all the posts on single.php will be removed leaving a message (you must be logged in to view this page). Then when Author B logs on all of Authors B post will be displayed on single.php. Each post is being generate by a custom post type called projects, which have the ability to assign an author. I am trying to accomplish this without a plugin. Any help would be appreciated.
Check if a user is logged in using `is_logged_in`. If a user is logged in modify the query using `pre_get_posts` filtering posts by the current author ID. if ( is_user_logged_in() ) : function filter_posts_by_author( $query ) { global $current_user; get_currentuserinfo(); $query->set( 'author', $current_user->ID ); } add_action( 'pre_get_posts', 'filter_posts_by_author' ); // ... loop else : echo 'you must be logged in to view this page'; endif;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, posts, pages, author" }
Remove header text option from the backend I want to remove the _header text_ option from WordPress backend, under the _Appearance->Header page_ at the bottom. !Screen Dump Is there any hook or filter to remove this option from the backend? Thanks!
This is controlled by theme as part of custom header feature declaration. Something like this should disable that part of the feature (you might need to adjust, depending on specific theme used): add_action( 'after_setup_theme', function () { add_theme_support( 'custom-header', array( 'header-text' => false ) ); } );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp admin" }
Allow Permalinks to Work with and without Hyphens Is there a way that I can change my .htaccess file to allow the user to go to a permalink with or without the hyphen? For example: I have a page: ` To get to that page, I'd like to be able to type in any of the following: example.com/parent/two-words example.com/parent/twowords example.com/two-words example.com/twowords Is that possible? Thanks!
I ended up using the plugin "Safe Redirects Manager" to redirect any /twowords/ to /two-words/ as necessary.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "permalinks, htaccess" }
Different page template for paginated content? Sorry for the basic question, but I can't track down a solution (or maybe it's just hard to search for). I'm creating my own infinite scroll system for a wordpress site I'm working on. For ease of development it would be beneficial for the 'paginated' content to be on a separate template (so that I can just output the content, and ignore the rest of the template). Can this be done in wordpress? i.e. `domain.tld/content-page` should use `content-page.php` `domain.tld/content-page/page/1` should use `content-page-paginated.php` I suppose the obvious alternative is having logic in content-page.php that checks to see if it's paged content and outputs differently if that's the case.
> I suppose the obvious alternative is having logic in content-page.php that checks to see if it's paged content and outputs differently if that's the case. Basically. In `content-page.php`: get_header(); //WordPress has a global variable for whether a post/page is paginated or not global $paged; // If post/page isn't paginated if ($paged === 0) { //Do stuff that you want for non-paginated posts/pages } //If post/page is paginated else { include 'content-page-paginated.php'; } get_footer(); (Edit: changed `$multipage` to `$paged` as per Nathan's comment)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pagination, infinite scroll" }
Theme specific plugin, how? Can someone tell me whether it is possible to create a plugin that is only available to a specific theme and how do I override certain settings in that theme? **The problem** This is basically the story. We've had a third party design and create a wordpress theme for us. Now it's up to us to expand the functionality of the theme by creating a plugin that will only be valid when someone has our theme installed. Are there specific functions available to achieve this? Thanks in advance.
You can ask for the activation of the theme. You can get the value of the options values `template`and `stylesheet`. The `stylesheet` get the active style, a benefit if the user use an child theme. As example `if ( 'my_theme' === get_option( 'stylesheet' ) ) ...`. Also you can use the hooks for template and stylesheet, also s small exmaple. add_filter( 'option_template', 'fb_theme' ); add_filter( 'option_stylesheet', 'fb_theme' ); function fb_theme( $template = '' ) { if ( 'my_theme' === $template ) { echo 'TRUE'; } return $template; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, themes" }
Why use the Settings API over a new administration menu? I'm writing a 'quote-me' plugin which provides the end-user with a quote based on data they submit through a front-end form. The quote is calculated according to a price list. The price list varies depending on the time of year so I need a way of letting the admin-user update the prices via the back-end dashboard. My first thought was to use the Settings API but have since seen administration menus can be created. Considering my objective above, should I create a new admin menu or should I use the Settings API? Which is more appropriate for my use case and why? Hoping someone can explain. Thanks in advance. **UPDATE:** My confusion came from my assumption that the Settings API is to be used for just the _Settings_ administration menu. But now I know the Settings API can be used across the whole set of administration menus, including new ones I create. Thanks for your answers and comments!
The two are not the same thing at all, and likely you'll use both. The Administration Menu stuff shows you how to create the menu item and page for your settings to live on. In other words, the menu item in the left hand bar, and the existence of the page itself. The Settings API is what you use to actually build the contents of that page (the table of settings, form fields, and submit button), and to then process the data coming back from it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, admin menu, settings api" }
Why does enabling Permalinks make pages not found? I'm new to Wordpress and am creating a site using v3.9.1 of WordPress. When I create a new page, I can see it in edit mode, but the URL it is supposedly creating is not found when permalinks is used, but visible when permalinks is disabled. For example, if I try to create a page called `photos` right below the top level, the editor states the page will be visible at ` when permalinks is `Post name`, but navigating to such page gives the error: > Not Found > > The requested URL /photos/ was not found on this server. But if I put Permalinks back to `Default` then it becomes visible at `
This is a Site I maintain hosted on GoDaddy. All HTML seen by the outside world is stored in the `/public_html` directory. Therefore `/public_html` is considered the root directory of my server. !FileZilla Photo This site runs on WordPress 3.9.1. All that was done, was that GoDady's custom installer package unzipped the WordPress download zip to the `/public_html` directory. Doing this Manually is easily accomplished by unzipping the WordPress download to a Folder and then uploading the **contents of that Folder(but not the folder)** to your web root. I suspect you unzipped and then uploaded the containing folder, which would lead to `www.example.com/wordpress` if wordpress was the folder you uploaded. To fix this, work backwards...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, pages, 404 error, wp redirect" }
Making a Custom Menu Sidebar Icon show as Current in css In the custom WP Menu I have assigned classes which are different for each menu item. For example .power-icon a { padding-left: 35px !important; background-image: url(/images/icon-grey.png); background-position: 5% 50% ; background-repeat: no-repeat; } .power-icon a:hover { padding-left: 35px !important; background-image: url(/images/icon-blue.png); background-position: 5% 50% ; background-repeat: no-repeat; } This works fine, however, I would like to make the blue icon also display when the page is active/current. I discovered that this .widget_nav_menu .menu .current-menu-item { background-color: #f3f3f3; } will highlight the current item background. But my attempts to unify it with the icon class have failed. Appreciate any help on this. Thanks.
This isn't really WordPress specific, but here goes. Really, all you're missing is applying the blue background image on `.current-menu-item a`. /* Default state base */ .widget_nav_menu .menu li a{ padding-left: 35px !important; background-position: 5% 50%; background-repeat: no-repeat; } /* Active state base */ .widget_nav_menu .menu .current-menu-item a, .widget_nav_menu .menu .current-menu-item a, .widget_nav_menu .menu .current-menu-parent a, .widget_nav_menu .menu .current-menu-ancestor a { background-color: #f3f3f3; } /* Power */ .power-icon a { background-image: url( /images/icon-grey.png ); } /* Power active + hover */ .power-icon a:hover, .power-icon.current-menu-item a, .power-icon.current-menu-parent a, .power-icon.current-menu-ancestor a { background-image: url( /images/icon-blue.png ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css" }
Add character count to custom metabox I know of a way to add a character counter to the excerpt metabox in WP, but I would like to add a character counter to a custom metabox. The following script is getting the counter in the metabox, which has tabs, but it isn't counting. Any help would be great. Thanks, it's my first question in StackExchange. jQuery(document).ready(function(){ jQuery("#bgnp-metabox-tabs").after("<p style=\"text-align:left;\"><small>Excerpt length: </small><input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"bgnp-metabox-tabs\" readonly=\"\"> <small>character(s).</small></p>"); jQuery("#feed").val(jQuery("#excerpt").val().length); jQuery("#bgnp-metabox-tabs").keyup( function() { jQuery("#bgnp_metabox_tabs").val(jQuery("#excerpt").val().length); }); }); The counter appears in all of the tabs, but I only want it in the tab "#feed"
I assume the `#feed` element is the one in which you want the count value to appear? If so, change the `#bgnp_metabox_tabs` entry in your keyup function to `#feed`. **EDIT:** For some reason, I wasn't seeing all the code when I first read the problem. The id of your placeholder for the character count is the same as the id on which you are calling the `after` function. I would change the placeholder id to something like `char-count`. You can then target that placeholder with `jQuery(#feed #char-count)` to get it to be shown only on the feed tab (assuming the feed tab has an id of `#feed`)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox, count" }
Get markup for post without loading into the template I am writing a shortcode plugin that displays posts according to some parameters passed into the shortcode. I have the `wp_query` to get the posts and now I am trying to get the markup for the posts according to the theme's template files. In essence, get_template_part is exactly what I want... except that it directly loads the markup into the template. I want to get the markup for the content, perform a little post-processing and then return the markup for the shortcode. Essentially, $listings = new WP_Query(...); while ( have_posts() ) { $markup .= get_template_part('content', $post->post_type); } return $markup Except this obviously isn't the way that `get_template_part` works. How do I get the markup for a post without rendering the markup into the page?
I couldn't figure out a WordPress way to do this and looking at the WP source, it looks like this probably will never really be possible. However, I was able to get a solution using vanilla PHP by redirecting standard output into a buffer and loading the buffer into a variable. $listings = new WP_Query(...); ob_start(); while ( have_posts() ) { get_template_part('content', $post->post_type); } $markup = ob_get_contents(); ob_end_clean(); return $markup
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, themes, templates" }
How do I prevent term from being created on create_term hook? I have a function working on 'create_term' hook, I'm trying to prevent the term from being created on certain situations, I've tried return false; But that didn't do much, how do I prevent the term from being created?
`create_term` as you can see in inline docs in code > Fires immediately after a new term is created, before the term cache is cleaned So you can't prevent an event after that event already happen. To prevent a term is inserted you can use **`'pre_insert_term'`** filter hook and return a `WP_Error` a `0` or an empty string. Example: add_filter( 'pre_insert_term', 'prevent_add_term', 20, 2 ); function prevent_add_term( $term, $taxonomy ) { if ( $term === 'i-am-a-bad-term' ) { $term = new WP_Error( 'invalid_term', 'Term you tried to add sucks' ); } return $term; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "hooks, actions, terms" }
Is there an action hook that fires just before a template is loaded? I'm looking for an action hook that occurs just before a template is parsed but AFTER the query has run and the variables are present. So if it's going to run index.php, just before it starts reading code from line 1 of index.php, some hook would be super useful. Anyone know one?
Looking at the Action Reference in the Codex, the first action listed after the `wp` action that sets up the WP object is `template_redirect`, which is indeed fired after all queried data is available, and before a template is selected. You can use the WordPress conditionals to determine if your intended template file will be loaded. There is also the `template_include` filter which is executed after a template has been selected but before it is loaded, and gets passed the selected template file as an argument. But you should note that as this is a filter hook, it's intended purpose is to replace a selected template rather than adding or removing functionality. Alternately, if you are using your own theme, you could call `do_action( 'my_custom_action' );` at the top of your template file and simply add hooks to the action to execute custom functionality.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "templates, hooks, actions" }
Admin Taxonomy Terms - Orderby Term Field I have a custom value which is being stored as `term_group` but in the admin panel I would like to order them by that term group. I'm able to sorta do this through this function, but there's a problem: function change_term_order( $args, $taxonomies ) { if ( is_admin() && 'tax_products' !== $taxonomies[0] ) return $args; $args['orderby'] = 'term_group'; $args['order'] = 'ASC'; return $args; } add_filter( 'get_terms_args', 'change_term_order', 10, 2 ); This only works if the user sorts on one of the columns, not on initial page load. I tried to modify the filter to be `get_terms` but it just errored out half way down the page. Does anybody know the correct filter to change ordering categories and taxonomy?
I was able to find the answer after some trial and error / tons of searching, this looks like the correct filter, just need to make sure we're in the admin section and we're in the correct taxonomy. /** * Modify the admin listed order of terms * * @param String $orderby * @param Array $args * @param Array $taxonomies * * @return String $orderby */ function change_term_order( $orderby, $args, $taxonomies ) { if ( is_admin() && 'tax_products' !== $taxonomies[0] ) { return $orderby; } $orderby = 'term_group'; $args['order'] = 'ASC'; return $orderby; } add_filter( 'get_terms_orderby', 'change_term_order', 10, 3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "admin, wp admin, taxonomy, sort" }
Make a user administrator to a sub directory site and a contributor to main site in multisite network I have a multisite network. The main site displays news. The sub directory sites have administrators and I call them subsite admin. If the subsite admin wants to post to the main site, I want them to log in only as a contributor for the main admin to review their news before publishing. Is it possible to customize the role of subsite admin where he/she may use it to login as contributor to the main site? For example, subsite-admin-A will have 2 roles: 1. admin to its subsite 2. contributor to the main site.
Read User Access paragraph on the Codex here: Multisite Network Administration
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, users, user roles, directory" }
Auto Log In Users after registration and send confirmation email I'm using this function in functions.php to auto log in users after the sign up in the front-end function auto_login_new_user( $user_id ) { wp_set_current_user($user_id); wp_set_auth_cookie($user_id); wp_redirect(' exit; } add_action( 'user_register', 'auto_login_new_user' ); This works great for auto login in users but for some reason this also causes the automatic confirmation email not being sent to users anymore. I have no idea why though, any suggestions would be really helpful. Thanks
You're short-circuiting the registration process when you redirect and exit script execution, the `user_register` action isn't the last step of the process. You can try to call `wp_new_user_notification` manually, but I'm not sure what other side-effects that may have.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "email, user registration" }
Hiding Metabox from Screen Options Pull Down 1. I've created a Custom Post Type (CPT) which has 2 metaboxes. 2. On the Edit Page for the CPT, the screen options pull down (at top) displays the metaboxes and gives the user the **option** to "Show on screen" ... or **not** "Show on screen". 3. As these fields are mandatory for the CPT, I would like to hide my metaboxes from the "Screen Options" dropdown completely. How do I do this?
There is no way, at least to my knowledge to unset an option from the screen options panel without unsetting the actual metabox itself. My suggestion would be to target these screen options item via your CSS and hide it from view. Add this to your plugin or functions file. Don't forget to update 'METABOXIDNAME' with the ID name of your metabox. add_action( 'admin_head', 'remove_wordpress_cfields' ); function remove_wordpress_cfields() { echo '<style>label[for=METABOXIDNAME-hide] { display: none; }</style>'; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, metabox, screen options" }
How to call a plugin function from front end form I have a page template having a form which further have 3 input fields and and a submit button. I have a written a function in a plugin which inserts the retrieved values in database. I am trying to figure out what to write in action attribute of the form, so that when user clicks the submit button, the function gets executed?
## Output The Form Can be done via Shortcode API. ## What Should Be Set on Form Action Leave it blank `<form action="">`. Make sure you avoid using reserved name as form field name like `name` or `p`. Otherwise your form submission will hit `404`. ## How Can We Validate or Process The Form? Hook into `template_redirect`. add_action( 'template_redirect', 'wpse149613_form_process' ); function wpse149613_form_process(){ if(!isset($_POST['submit'])) // assuming you're using POST and submit button name is 'submit' return; // Validate the form, verify nonce // process form } Hope it makes sense. This is how I usually handle form submission.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "plugins" }
importing table data to custom post type i'm trying to import data from table to custom post types below is the code i'm using but this $row['Title'] return nothing ... if i hard code it works $rows = $wpdb->get_results( "SELECT * FROM Products"); foreach ($rows as $row) { $new_post = wp_insert_post(array( 'post_type' => 'products', 'post_status' => 'publish', 'post_author' => $authorID, 'post_title' => $row['Title'] )); if( !is_wp_error($new_post) ) { update_post_meta($new_post, "shakamaka", $row['DocFileID']); } };
`$row` doesn't look like you think it does. `$wpdb->get_results` will by default return an array of _objects_. Your code-- `'post_title' => $row['Title']`\-- treats an object like an array and should generate a Fatal Error, which you'd see if you had debugging enabled. > Fatal error: Cannot use object of type stdClass as array in ... You need object syntax. Try (using a Core table): $rows = $wpdb->get_results( "SELECT * FROM wp_posts"); foreach ($rows as $row) { // echo $row['post_author']; // doesn't work echo $row->post_author; // works echo '<br>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp insert post" }
How can I show a different theme for admin users? WP 3.8+ I've been searching around for a long while now. There seem to be plugins available for this, but hardly anything that is current. Many of the plugins I have already tried do not work correctly with WordPress 3.8+ My needs are basic. All I want to do is load another theme if I am logged in as an admin, so that I see a different front-end. Thanks, Michael.
You can use the filter `stylesheet`: <?php add_filter( 'stylesheet', 'wpse149620_stylesheet' ); function wpse149620_stylesheet( $stylesheet ) { if ( ! is_admin() && current_user_can( 'administrator' ) ) { $stylesheet = 'admin-theme'; } return $stylesheet; } ?> However, this must be loaded before the first time the "current theme" is requested, which can only be done (without editing core) by putting this in a Must Use Plugin. Create a directory called 'mu-plugins' in 'wp-content' and insert this code into a PHP file. WordPress will pick this up automatically. Make sure there are no spaces, line breaks or output before the PHP code to avoid a fatal error.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, theme development" }
Remove number in URL I'm trying to use WordPress to make a web page. I made a "Contact" page, but for some reason it didn't show up. WordPress kept saying it couldn't find it. So I deleted it and made a new one called the same thing, "Contact". Now the Contact page works, but it has a `-2` in the URL. I want to make it say ` instead of ` How do I do this?
When you delete a post, it merely gets put into the "trash" and retains its slug. When you created the "new" contact page, the slug "contact" was already in use by the original contact post that is in the trash. Go into your posts on the dashboard and click on the "Trash" link near the top of the post listing. Once in the Trash area, permanently delete the original contact post. You can now go back into the "new" contact post, edit the slug near the top of the post, and remove the extra -2 that was added to it. Click OK and save the post. It should now have the slug contact instead of contact-2
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "pages, urls" }
Call Shortcode on wp_footer Is it possible to call shortcode outside of post/ page content area? I am trying to add it to wp_footer with the following codes but it's returning string: add_shortcode('eps_pop', 'init'); function indtable_display_front_end($atts ) { global $post; extract( shortcode_atts( array( 'id' => '' ), $atts ) ); echo get_post_meta($id, '_my_meta_value_key', true); } echo do_shortcode('[eps_pop id="234"]');
Try this: add_shortcode('eps_pop', 'indtable_display_front_end'); function indtable_display_front_end($atts ) { global $post; extract( shortcode_atts( array( 'id' => '' ), $atts ) ); echo get_post_meta($id, '_my_meta_value_key', true); } echo do_shortcode('[eps_pop id="234"]');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, footer" }
How to edit the '<-- older' link on archive page in Blankslate theme? I am using the 'Blankslate' theme for Wordpress and I edited about everything except for the older and newer links on my blog page. How can I change this links in the Blankslate theme? It isn't located in the function.php and index.php files.
If i am not wrong then i think you are talking about this Blankslate theme. If this is the case then you can edit the older and newer links displayed on archive page by editing the following code by overwriting the theme file nav-below.php in the child theme. <div class="nav-previous"><?php next_posts_link(sprintf( __( '%s older', 'blankslate' ), '<span class="meta-nav">&larr;</span>' ) ) ?></div> <div class="nav-next"><?php previous_posts_link(sprintf( __( 'newer %s', 'blankslate' ), '<span class="meta-nav">&rarr;</span>' ) ) ?></div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, archives, previous post link" }
How do we exclude multiple pages (like opposite of is_page) ## Scenario I have a following customized format for the website with Woocommerce. 1. **`<?php if(is_shop()) {?>`** There are certain css styles, JS options used for this particular page 2. **`<?php } if(is_front_page()) { ?>`** Same as above with different css animations used or certain classes when on home page of the site ## Question Now, I want to use some specific jQuery options such as .Delay(), Hide(), & Show() on `pages other than Shop & Home page` However, If I simply add the jQuery outside the options `1` & `2` mentioned above .. this gets applied to entire website -- overriding options specified for `is_shop` I think if we can exclude pages then I can exclude these 2 pages above. Writing `is_page (array)` would be too tedious for hundreds of pages. How can we exclude certain WP pages (in my case only 2)? Or should I re-format the page using `if else` & will it work? Thanks in advance.
The opposite of `is_page()` will be `! is_page()`. In php the `!` is used as negative, so `! is_page( 42 )` will means something like > if we are not on page ID 42, do something, in other words exclude page ID 42
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, woocommerce offtopic" }
Migrating Roles from one environment to another I have 2 identical environments . Now, on one I have created many roles and have assigned users to them . How do I migrate this to the other server which has the same set of users already. Any suggestions to the problem would be great.
So I Migrated the contents of `meta_Key` `'wp_user_roles'` from the `wp_options` table from one server to another after a backup and it worked , the Roles migration was successful.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles" }
redirect users to the login page I create a template page as seen below to check if user is logged in or not. If user is not logged in, I want to redirect user to first login page and after login I want him to redirect previous page. With the code below, Login redirection function redirects to login page again after user login. How can I fix that code? In my template page : <?php if(!is_user_logged_in()) { wp_redirect( ' 302 ); } else { wp_redirect('----------otherpage---',302 ); exit; } ?> in functions.php : function directtorequest( $redirect_to, $request, $user ) { // instead of using $redirect_to we're redirecting back to $request return $request; } add_filter('login_redirect', 'directtorequest', 10, 3);
Add `redirect_to` as a query variable in your link whenever you redirect user `wp-login.php`. Like wp_redirect(' 302); In `redirect_to` write the link of any page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, login" }
Delete post media except featured image I'm working on site where post except 'featured image' has also other images. Under certain circumstances I need to delete all images except 'featured image'. Which one the most convenient way to do it? Is it possible to do via `delete_post_media()` function or I should write custom query? Thanks.
If someone has clashed with such problem, I solved it in this way: $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => $post_id ) ); $thumbId = get_post_thumbnail_id($post_id); foreach ( $attachments as $attachment ) { if($thumbId != $attachment->ID) wp_delete_attachment( $attachment->ID, true ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails" }
Nginx with Wordpress not showing template 404 for certain file types I am using Nginx on Ubuntu to host a Wordpress site and everything is working great except certain file types return the Nginx 404 rather than the Wordpress template 404. For example: < shows the Nginx 404 page. While < shows the template 404 page. What am I missing in my configuration of Nginx?
I received a response with code that fixed the issue from rtcamp.com Add this code to the nginx site configuration for the domain has the issue with not all 404 requests being handled by Wordpress: if (!-e $request_filename) { rewrite ^/(.+)$ /index.php?q=$1 last; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "404 error, server, nginx" }
Count post that have specific meta value How do I count only the post that have a specific custom meta field value? $productCount = wp_count_posts('product'); echo $productCount->publish; That gives me all the total of all the post. How do I find out how many of those post have say a custom meta value of `cat`?
There is no default/native function in wordpress to count posts from a specific meta value. `wp_count_posts` only counts the amount of posts according to post type It might be useful here to use `WP_Query` to create a custom query to get all posts with that specific meta value and then use `$wp_query->found_posts` to get the post count. This should do it $query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) ); echo $query->found_posts;
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "custom post types, count" }
What does Wordpress media uploader do to image files on upload? This question is specifically for images and what optimisation happens to these files when they are uploaded via Wordpress Media Library? Images .jpg .jpeg .png .gif And how is it possible to change these settings? I also know you can change the image sizes in `Settings > Media`
I think that Wordpress only apply jpeg compression and the quality can be only change by code. For example, add this code to the functions.php file of your theme or in a plugin: add_filter('jpeg_quality', function($arg){ //Set compression quality from 0 to 100 return 100; });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, uploads, media library" }
Order of stylesheets in child theme Parent theme has following code for including styles. function blue_planet_scripts() { wp_enqueue_style( 'blue-planet-style', get_stylesheet_uri() ); wp_enqueue_style( 'blue-planet-style-bootstrap', get_template_directory_uri().'/css/bootstrap.min.css', false ,'3.0.0' ); wp_enqueue_style( 'blue-planet-style-responsive', get_template_directory_uri().'/css/responsive.css', false ,'' ); } add_action( 'wp_enqueue_scripts', 'blue_planet_scripts' ); In child theme I just imported parent theme's styles using `@import url("../blue-planet/style.css");` But order of stylesheets are: * style.css (child theme) * bootstrap.min.css * responsive.css What modification is needed in parent function to include child theme's style.css in last in the order? I need: * bootstrap.min.css * responsive.css * style.css (child theme)
The function `wp_enqueue_style` has the param `$deps` for depends. > $deps (array) (optional) Array of handles of any stylesheet that this stylesheet depends on; stylesheets that must be loaded before this stylesheet. false if there are no dependencies. Default: array() Use this param to define the dependencies and you have an order. function blue_planet_scripts() { wp_enqueue_style( 'blue-planet-style', get_stylesheet_uri() ); wp_enqueue_style( 'blue-planet-style-bootstrap', get_template_directory_uri().'/css/bootstrap.min.css', 'blue-planet-style' ,'3.0.0' ); wp_enqueue_style( 'blue-planet-style-responsive', get_template_directory_uri().'/css/responsive.css', 'blue-planet-style-bootstrap','' ); } add_action( 'wp_enqueue_scripts', 'blue_planet_scripts' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "child theme, css, parent theme" }
How pass a 0 in $atts? I need to pass an attribute (tabindex="0") into my navigation link. I use this filter: /** * Add tabindex attribute to menu links * * Brings keyboard accessibility for opera browser. */ add_filter( 'nav_menu_link_attributes', 'atts_menu_tabindex' ); function atts_menu_tabindex( $atts, $item, $args ) { $atts['tabindex'] = 0; return $atts; } This filter works fine with all values unless with **_0_** (zero). What can i do, to pass the "0"?
This happens, because WP checks the value with `empty()`: if ( ! empty( $value ) ) … and `empty()` is `TRUE` for values like `0` or `"0"`. You have two options now: 1. Filter `walker_nav_menu_start_el` and replace `<a` with `<a tabindex=0`. 2. Pass `$atts['tabindex'] = "0 ";` in your original function. Note the extra space. It circumvents the `empty` check. Test it with different browsers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "array" }
WP_NAV_MENU filter targets all menus Im trying to replace my template's primary menu through a plugin so that I don't have to make changes to the header.php. I found this code in another question answered here in 2011 (Replacing WordPress menu functionality with a plugin) add_filter('wp_nav_menu', 'my_menu_func'); function my_menu_func(){ print "Testing 123"; } It worked but it replaced both my top primary menu and the widget side menu. How can I specify which menu to target when using the filter?
You could try the following code snippet to override the _primary_ menu: /** * Override the primary menu. * * @param string $nav_menu The HTML content for the navigation menu. * @param array $args Array of wp_nav_menu() arguments. * @return string $nav_menu */ function wpse_150003( $nav_menu, $args ) { //Override the primary menu: if( 'primary' === $args->theme_location ) $nav_menu = 'My new menu'; return $nav_menu; } add_filter( 'wp_nav_menu', 'wpse_150003', PHP_INT_MAX, 2 ); where we find the input arguments info from the source. Notice that we **return** the `$nav_menu` value, instead of **echoing** it. You could also filter my other attributes, for example `menu_id`. You might also consider these filters: * `wp_nav_menu_items` * `wp_nav_menu_{$menu->slug}_items` I hope this helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, menus, filters" }
Hide sub domain created for local CDN Not sure if my question would make sense or not. I have created a sub-domain to store some of my static files (like images). So, some images now load from **< Now, the problem is, all the files stored under this sub domain < are publicly visible which I want to hide or redirect or show 404. Any idea how to achieve this? Currently files in the subdomain shows -- **Index of /** * cgi-bin/ * onevideofile.mp4 * oneimagefile.png _Apache Server at imgs.iconicwebteam.com Port 80_
You could go around and not allow indexes? Add this to a .htaccess file, in the same directory as the .png and .mp4 files. Options -Indexes
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "subdomains" }
Redirect to a file in a WordPress theme directory I have a site where < creates a pdf of some content based on what's in a cookie. That URL is pretty ugly. I'd love the url to simply be < I've tried to use mod_rewrite with no success. E.g. In my .htaccess file I have: `RewriteRule ^/pdf$ This just returns a 404. Any ideas what I might be doing wrong? Thanks.
This is what ended up working for me: RewriteRule ^pdf$ wp-content/themes/my-theme/pdf.php It looks like removing ` was the difference.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rewrite rules" }
Retrieve Product category 'NAME' by product category ID - WooCommerce? Can I retrieve woocommerce product category name by ID? Not thumbnail, not the URL, not the Sub-categories, just raw Category name.
Use `get_term_by`: $id = 42; if( $term = get_term_by( 'id', $id, 'product_cat' ) ){ echo $term->name; }
stackexchange-wordpress
{ "answer_score": 15, "question_score": 8, "tags": "categories, woocommerce offtopic" }
How do I add a featured image to a single post page? I'm using the Pinboard theme on WordPress 3.9.1. I'd like to edit Pinboard (or, more accurately, make a child theme) so that on single post pages, if the post has a defined featured image, it displays at the top of the post. I've gathered that doing so requires editing single.php in the theme, but my knowledge of PHP is minimal at best, so when I open single.php, I can't figure out where to make the changes--or, in fact, what changes to make. Would anyone be willing to walk me through what it would take to include the featured image at the top of a post page such as this one? Once I understand how to properly get the image on the page, I should be able to style it the way I want. This is probably asking for a little more hand-holding than is normal around here, so big thanks in advance.
In `single.php`, find `<?php the_content(); ?>` around line ~17. Just before that. paste following code. <?php if ( has_post_thumbnail() ):?> <div class="featured-image-wrap"><?php the_post_thumbnail(); ?></div> <?php endif; ?> This will show featured image if assigned to the post. To change the size of image you can pass parameter to the function `the_post_thumbnail()`. See official documentation of the_post_thumbnail(). I believe you would use child theme for modification.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "images, post thumbnails" }
Display sidebar only if it has content I have registered a new sidebar. Here is my code in functions.php: register_sidebar(array( 'name'=>'1', 'before_widget' => '<div class="div1">', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', )); How do I get to display this sidebar. I want to do something like this: > if sidebar(1) doesn't have widgets, it should not be displayed > > if sidebar(1) have widgets to display, it must display <div class="alllist"> <div class="div1"></div> <div class="div1"></div> </div>
You can use `is_active_sidebar` to check if sidebar has any widgets or not. Display sidebar only if `is_active_sidebar` returns true. <?php if ( is_active_sidebar( 'sidebar-name' ) ) : ?> <?php dynamic_sidebar( 'sidebar-name' ); ?> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets" }
Read text defined under __() I am new to WP Plugin development. I have a theme where texts are included inside __() function for translations, like: __('This is text to be translated'); I want to create a plugin which would get the value from __() functions and run through my own defined functions. Suppose the text inside __() contains __("This is JavaScript alert <script>alert('Hello');</script>"); I want my plugin to do sanity check before printing it in the browser, something like: function my_sanitizer($text) { $text = trim(strip_tags($text)); // The $text is value from __() of above return $text; } and the sanitized text should print in the browser. How shall I be approaching this, any hints, ideas, solutions would be appreciated.
You should look at `gettext` filter hook which is applied to the translated text by the internationalization functions (__(), _e(), etc.). eg: add_filter( 'gettext', 'my_sanitizer', 20, 3 ); /** * my_sanitizer * @param string $translated_text the translation * @param string $text the origial text from __() * @param string $domain text domain * @return string */ function my_sanitizer( $translated_text, $text, $domain ) { $translated_text = trim(strip_tags($translated_text)); return $translated_text; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development, translation" }
User description only displayed for logged user In my "About" page I list all WP users of the site. Then in author.php I display the description of the selected user with this code: `<?php the_author_meta( 'description' );?>`. Problem: this code only display user description if this user is logged, otherwise it displays nothing. Why? Code of the "About" page: <ul> <?php $blogusers = get_users('orderby=nicename&who=authors'); foreach ($blogusers as $user) { $user_info = get_userdata( $user->ID ); ?> <li> <a href="<?php echo get_author_posts_url($user_info->ID); ?>"> <?php echo $user_info->nickname; ?> </a> </li> <?php } ?> </ul>
I have tested your code on my side, and it works perfectly. The relevant info displays, whether I'm logged in or not. This is definitely not a problem with your code, but more an external problem. You will need to look for any type of code that might restrict this code from showing if a user is logged out, something like `if ( is_user_logged_in() )`. If you have any type of admin/role type plugin, have a look at those as well. They might be restricting a user from viewing certain pages or info when they are logged out I would suggest the following, get yourself a code editor like Notepad++ and search your wordpress install for statements like `if ( is_user_logged_in() )`. Also look at your user roles and what they can and cannot view if you have customized your roles. You should also try to deactivate your plugins one by one and check if the problem goes away or not. Lastly, try one of the bundled themes. This should at least give you some idea on how to solve your problem
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "users, user meta" }
Exclude parent category when getting category posts by slug I have the following category layout: Resources -- Documents I want to list the posts in the documents category, and have the following code: $args = array( 'posts_per_page' => '-1', 'orderby' => 'ID', 'order' => 'DESC', 'category-name' => 'documents' ); $surveys = get_posts($args); This returns the posts in both documents AND resources categories. I only want those in 'documents'. I know there is ways to exclude categories by ID but I need to use the category slug as my dev and live databases do not match.
I wonder if a single typo is messing things up for you? Please try this: $args = array( 'posts_per_page' => '-1', 'orderby' => 'ID', 'order' => 'DESC', 'category_name' => 'documents' ); $surveys = get_posts($args); where I replaced `category-name` with `category_name`. > I know there is ways to exclude categories by ID but I need to use the category slug as my dev and live databases do not match. There exists for example the function `get_category_by_slug()` that you can use if you need to get the `term_id` from the `slug`: if( FALSE !== ( $obj = get_category_by_slug('some-category-slug') ) ) { $id = $obj->term_id; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, get posts" }
Wrapping code in an if block Breadcrumb trail shows on all pages, except I need to remove it from the homepage. Here's my code so fare. <?php if( !is_front_page ):?> <div class="breadcrumbs" style="position:absolute; bottom:0;"> <?php if(function_exists('bcn_display')) { bcn_display(); }?> </div> <?php endif;?> at this point the code is not working, even on the homepage. how should i have the if statement written so that the breadcrumb trails show up on all other pages except the homepage.
You should change it to: <?php if (!is_front_page()): code code code See this page in the Codex for more information: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins, customization" }
Change the date and time in wordpress Is there a way to change the date and time in WordPress, not the timezone, but the date and time all together, like make it 03-21-85 11:11 PM. I want all dates and times to be changed, not just to one post or page, but to the whole WordPress site it's self.
Maybe you'ld like to go to settings > general and then add a custom date format. Like `d.m.1985` instead of `d.m.Y` Or you write a function that subtracts the time you want from the current date. Or you set the server time back to 1985. But that's no good idea since it will affect other apps, mysql etc. as well. Last but not least you could try to set up a second development environment maybe in Virtualbox and then set the OS time manually.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "date, date time" }
Allow different <span> tags in widget titles How can I make widget titles allow HTML? I want to add icons from an iconfont to the titles like <span class="icon-someicon">Widget Title Here</span> I tried the following but it does not work at all... function html_widget_title( $title ) { $title = str_replace( '[', '<', $title ); $title = str_replace( '[/', '</', $title ); $title = str_replace( 's]', 'span>', $title ); return $title; } add_filter( 'widget_title', 'html_widget_title' );
Whoopsie, I found out how to do it - could not be any simpler. For additional information: I used fontello to create my own iconfont and added it to my WordPress Theme. That's why `font-family` is fontello in my snippet below. I looked up the CSS Path to my widget titles (i.e. `.widget-3 > h3.widget-title`), added `:before` in CSS, looked up the icons (in this case \e805) in my fontello.css file and added the following CSS rules: .widget-3 > h3.widget-title:before { content: '\e805'; margin-right: 0.5em; font-family: "fontello"; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, widgets, sidebar" }
rewrite rules social share links Within the Ultimatum's theme childtheme.php I've added rewrite rules to the rewrite rules and it works perfectly fine. However, it does not work if the URL is shared in Facebook or Twitter. The Facebook debugger returns "Could Not Follow Redirect Path" for any of the pages using the rewrite rule. URL to try: < debugger: < ### rewrite rules function function AddRewriteRules ($ar_rules) { $ar_new_rules = array('listing-details/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?pagename=listing-details&mls=$matches[1]&ret=$matches[2]'); $ar_rules = $ar_new_rules + $ar_rules; return $ar_rules; } // hook add_rewrite_rules function into rewrite_rules_array add_filter('rewrite_rules_array', 'AddRewriteRules');
The rel canonical link points to ` which returns a 500 internal server error response code. You can try to remove the canonical action before `wp_head()` is called on those pages: remove_action( 'wp_head', 'rel_canonical' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, facebook, rewrite rules, twitter" }
Echo only gives me the first part of string So I was pulling some meta_value and trying to use it in a mass email and tested it first by echoing what I obtain in the array. In var_dump I see the array and that it gets my correct data, but when I echo the values in the loop, they only return the first letter in the string. $meta_key = 'agency_email'; $agency_emails = $wpdb->get_col($wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key)); var_dump($agency_emails); //I can see the array and the full string here foreach ($agency_emails as $ae) { $aemail = $ae['meta_value']; echo $aemail; //Only gives me the first part of string? } if one of my emails is '[email protected]' it will only give me 't' in the echo. What is the reason for this and how do I get the full string? Thanks.
Edit your code thusly: $meta_key = 'agency_email'; $agency_emails = $wpdb->get_col( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key ) ); var_dump( $agency_emails ); foreach ( $agency_emails as $ae ) { echo $ae; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb, array, meta value" }
How to redirect multiple subfolders back to root domain? Due to search engine crawling errors, I need to redirect websites of non existing subfolders to a reachable website. This is what is currently leading to 404-errors: * www.domain.tld/subfolder1/tag1/ * www.domain.tld/subfolder1/tag2/ * www.domain.tld/subfolder1/tag3/ Therefore I simply want to redirect the above URLs to the root domain. The following code is heading to www.domain.tld/tag3/ (which is not what I need) RewriteRule ^subfolder1/(.*)$ /$1 [R=301,NC,L] Can anybody help me out what to modify in the .htaccess-file, that all URLs with subfolder1 are redirected to www.domain.tld?
This is the solution I finally found after many hours investigation: RewriteRule ^subfolder1/(.*)$ [R=301,NC,L] With the above code in the .htaccess-file, which is located in your websites root directory, all URLs which contain www.domain.tld/subfolder1/* are redirected to the root domain. Hope this will help anybody else than me :-)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, htaccess" }
widget exclude post by custom field I have a widget that gets posts from different post_type's. I want to exclude some posts that have a custom field value e.g. I save a form where a checkbox adds a value of 0 or 1 depending if ticked. If the value is 0 the post should be visable and if the value is 1 then it should not be visable. Here is what I have to extract the posts: $wpcust = new WP_Query( array( 'post_type' => array( 'posts_type_1', 'posts_type_2' ), 'showposts' => '4' ) ); This is a basic WP_Query that selects posts based on two post_types. What I want to add is: 'meta_key' => 'key', 'meta_value' => 'value' Where value is 0 or 1. If I do this it only shows posts based on the meta_value. I need it the other way around where this excludes those posts. Any help? Thnx M.
The `meta_query` parameter in `WP_Query` allows you to query posts that don't have a certain custom field. Furthermore, you can check for multiple custom fields. With two queries in `meta_query`, you can fetch all posts that either don't have a custom field, or have it set to 0: 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'my-key', 'value' => '0' ), array( 'key' => 'my-key', 'compare' => 'NOT EXISTS', 'value' => 'Use any value here' // If you're using WordPress 3.9+, you can omit "value" for NOT EXISTS ) )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, exclude, meta value" }
Language of errors in WordPress admin How can I change the Wordpress error message language? The language of my WordPress installation is set to Russian. The entire site and the admin panels are in Russian, but the error messages (bad login, etc.) are in English. How can I make sure the error messages are translated as well?
Disable "Polylang" plugin solves the problem
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "errors, language" }
post_categories array using variable When using wp_insert_post can I do something like: `$categories = '1,2,3,4,5'` ...and then... `'post_category' => array($categories)`
This is the solution: < `$categories = '1,2,3,4,5'` ...and then... `'post_category' => explode(',', $categories)`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, wp insert post" }
Retrieve posts by term id custom query i want to retrieve custom posts using using custom query . my taxonomy is recipe_tx and terms (Beef) , (Chicken) etc in it . i have tried using SELECT p.* FROM wp_posts p, wp_term_taxonomy tt, wp_term_relationships tr WHERE p.ID=tr.`object_id` AND tt.`term_id`=tr.`term_taxonomy_id` AND (p.post_type = 'recipe_cpt') AND p.post_status = 'publish' AND tt.`term_taxonomy_id` = 37 but no luck . can someone help me how to get wp posts by their term_id . if beefs id is 37 then i want to retrieve all the posts with `term_id = 37` Thank's
Have you tried using the WP_Query class? You might find it's easier to use the built-in tools for this instead of a custom query from scratch. Something similar to the following should work for you: <?php $args = array( 'post_type' => 'recipe_cpt', 'tax_query' => array( array( 'taxonomy' => 'recipe_tx', 'field' => 'term_id', 'terms' => 37 ) ) ); $query = new WP_Query( $args ); ?> EDIT: note the `tax_query` is an array of arrays by design. Many tax query problems are a result of missing this detail. EDIT: corrected `field` value typo above, replacing 'id' with 'term_id'.
stackexchange-wordpress
{ "answer_score": 46, "question_score": 21, "tags": "custom taxonomy, query, terms" }
Find out who deleted a page or post? Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense. The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure. Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked.
By default, no, WordPress doesn't keep track of who changes post statuses (at least that I can see). you can hook into `transition_post_status` and log the user id. add_action( 'transition_post_status', 'wwm_transition_post_status', 10, 3 ); function wwm_transition_post_status( $new_status, $old_status, $post ) { if ( 'trash' == $new_status ) { $uid = get_current_user_id(); //somehow or another log the $uid with the $post->ID } }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 8, "tags": "posts, users, customization" }
Query unique author ids with published post of type job I'm trying to come up with a simple query to return an array of unique author IDs that have a post_status of 'publish' and a post_type of 'job'. I know I can query using: $args = array( 'post_type' => 'job', 'post_status' => 'publish' ); $published_jobs = new WP_Query( $args ); But this seems horribly inefficient to iterate through the results when all I want is an array of unique author IDs. At most we will have 30 or so authors, but could have thousands of job posts. Any suggestions? Thanks!
The most efficient means would be to query directly via `wpdb`: $author_ids = $wpdb->get_col( " SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_type = 'job' AND post_status = 'publish' " );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query, author" }
Check to see if more than one post I am new to php. I want to use a certain div "case" in the below code if there is one post here . If there is more than one I want to use another div "case2" <php> $connected = new WP_Query( array( 'connected_type' => 'posts_to_pages', 'connected_items' => get_queried_object(), 'nopaging' => true, ) ); if ( $connected->have_posts() ) : ?> <?php while ( $connected->have_posts () ) : $connected->the_post(); ?> <div class="case"><h5><?php the_title(); ?></h5><?php the_excerpt(); ?></div> <?php endwhile; ?> <?php // Prevent weirdness wp_reset_postdata(); endif; </php>
Try this to get the count of posts: <?php $connected = new WP_Query( array( 'connected_type' => 'posts_to_pages', 'connected_items' => get_queried_object(), 'nopaging' => true, ) ); echo "<h2>Found: $connected->found_posts</h2>"; ?> You could write a variable like: $the_count = $connected->found_posts; Then test with an `if` if ( ( $connected->have_posts() ) && ( $the_count > 1 ) ) :
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "loop" }
CSV to WordPress posts: do I have to populate each possible field? I'm planning to import Products in a CSV to WooCommerce. We are still working on an Excel, and we are using the main fields that a product has, following the WooCommerce wordings for the Products (post_title, post_excerpt, post_content, sku, regular_price, images). However, we have no columns for ID for example, or comments_status or post_author. My thinking goes that those fields would be auto-populated by WordPress with a kind of "default", but, hence my question, I'm not sure. Do I have to include ALL the fields that a Product (or Post or Page) has, so the import is successful? If so, is it enough to give an ascening ID to the products? (if the last created ID on the site is 35, assign IDs like so: 36, 37, 38, etc). Thanks for your inputs,
Nope, the WP is pretty flexible about this and will perfectly handling omitted fields. Including assigning IDs (which is actually best left to it, outside of edge cases when exact IDs must be imported). The only situation that natively won't let you create post is if neither of title/content/excerpt is provided and post type supports any of them. Even then there is `wp_insert_post_empty_content` filter available to adjust the behavior.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "import, woocommerce offtopic, csv" }
How to remove the category from post slug I want to remove the category from post slug, for example a post slug like "< would become "< My search only gives results about how to remove the word "category" from slugs, which is a different problem.
As @E pointed out, this is handled in Permalink Settings. To access these settings, look in the Admin menu on the left side of your screen. Under 'Settings' click on 'Permalinks' In 'Permalinks' you can see all of your various options for how to format the permalinks. It sounds like you want to use the 'Post name' option. Choose that and 'Save Changes' That ought to set you right.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, slug" }
Dynamic meta description I am trying to make the `<meta name="description" content="">` pull the content from single posts, but I am running into a snag. Currently I am using this: `<meta name="description" content="<?php $post_id = the_ID(); $post = get_post($post_id); echo strip_tags(substr($post->post_content,0 , 150)); ?>">` It works well but adds the post id in front of the content. Is there anyway to remove that? Thanks.
The the_ID() function that you are using in your code echos the current post id, to get current post id instead of displaying it use the function get_the_ID() as shown in the following code. Alternatively you can just use get_post() function without passing any post id as a parameter because the post id parameter is optional and if you don't pass any post id then by default the current post is used. Try using the following code instead of what you are using. <meta name="description" content="<?php $post = get_post(get_the_ID()); echo strip_tags(substr($post->post_content,0 , 150)); ?>">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, headers" }
term_link filter gives less atributes I have made a filter for term_link but when I work with it, I get message about not getting the second and third attr. Its a pitty, i need them add_filter('term_link','authorsongsurl',10); function authorsongsurl($url,$term='',$taxonomy=''){ } Whats up?
You need to add the the fourth parameter, $accepted_args, to add_filter() to access the second and third parameters in your callback function. Only the first parameter ($url) is passed by default. add_filter( 'term_link', 'authorsongsurl', 10, 3 ); The 3 in the end tells the filter to provide all the three parameters to your function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters" }
Cannot access subdirectory subpages I am working on a wordpress site for a client, who has a 2nd install in a subdirectory. When I try to view a subpage on the 2nd install (domain.com/folder/subpage) I get the root directory install's 404 page. It is not a htaccess issue because I have a similar set up on my own server where my website is in the root and I host other client websites in subdirectories, have never had a problem viewing any page in any sub-install. Could it be that the hosting has got directory browsing disabled or another issue? Thanks
Finally fixed this errow after browsing for a couple of hours and trying many options. In this block in your Apache httpd.conf file, (located in my CentOS instance at $ sudo vi /etc/httpd/conf/httpd.conf) # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None change `AllowOverride None` to `AllowOverride All`. Src: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "htaccess, directory" }
link header to homepage (for wp multisite) I am using the genesis framework and have added this code to change the way genesis uploads a header image: remove_action( 'wp_head', 'genesis_custom_header_style' ); add_action( 'genesis_header', 'andym_header' ); function andym_header() { echo '<img src="'.get_header_image().'">'; } This code just puts the header image in the html instead as a css background. I would also like to link the header to user homepages like the h1 site title links to homepages. I tried changing the header function in the code above to: function andym_main_header() { echo '<a href="<?php bloginfo('url'); ?>"> <img src="'.get_header_image().'"></a>'; } but got a syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ I don't know php very well, any help appreciated
A few issues- php tags are for interpolating between php/html, they can't go within php statements. Also, the single quotes in `bloginfo` are closing your string, which is generating the error. Lastly, `bloginfo` will `echo` its value, which can't go within an `echo` statement, you need to use `get_bloginfo` instead, or simpler, just use `home_url()`: echo '<a href="' . home_url() . '"><img src="' . get_header_image() . '"></a>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links, headers" }
Get new (not old) post inside transition_post_status hook Following up the ticket 'transition_post_status' is executed before 'save_post', I'm still struggling how to access the **new** `$post` (after it has been saved) inside a `transition_post_status` hook. Right now, I'm getting the old $post data (before it has been saved). Example: add_action('transition_post_status','myfunc',10,3); function myfunc($new_status,$old_status,$post){ if ( $new_status == 'publish' && $old_status != 'publish') { // a post is getting published if(!check_my_post($post->ID)){ //how can I get the saved/new post here? ... // do something } } } Changing priorities does not make any difference. Any ideas how to achieve this?
According to the Codex, if you use `wp_transition_post_status()` you will get both the old version and the new version. wp_transition_post_status( $new_status, $old_status, $post ) The ticket also says that the post type needs to support revisions for the save to work. > Check the post type of the post objects before doing anything. > > If your post type supported revisions, you'd see both actions fire twice -- transition then save for the revision, transition then save for the post. Would it be possible for you to use `wp_transition_post_status()`? And have you ensured that your post type supports revisions?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, post status" }
See which user installed a plugin? Are there any DB entries made when a plugin is installed, and if so does this indicate which user did so?
No, natively WordPress doesn't audit and store any records of admin activity. Retroactively the best you can do is try to get relevant information from web server access logs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, admin" }
Wordpress does not output "post" class when calling post_class() function I am writing an ajax call to a server which requests a next set of posts. However when I try to generate a list of posts I am having an issue with post_class() function. It does not add a "post" class to post. $osetin_query = new WP_Query( $args ); while ($osetin_query->have_posts()) : $osetin_query->the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>></article> <?php endwhile; ?> Result: <article id="post-154" class="post-154 type-post"> Expected result: <article id="post-154" class="post-154 post type-post">
`get_post_class()` generates and returns the list of classes echoed by `post_class()`. The only reason for the function itself not producing the result you want can be found in the source `post-template.php`: if ( ! is_admin() ) $classes[] = $post->post_type; Which means that the class `post` actually only gets generated if `is_admin()` _doesn't_ apply. Another possibility actually could be that the filter post_class is used to prevent the class. But given the available information this can just be a non-grounded assumption.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts" }
How to change image url? How can I change the image url from this > < Into this: > < Or into this: > < Any suggestions to to solve this problem?
Go into your WordPress **Dashboard > Settings > Media** and then untick the option that says > Organize my folders into Month and Year based folders This will make it look like: > < Then to take it further you need to update you **config.php** file and add in either this line: define( 'UPLOADS', 'image/'.'files' ); This will give you: > < Or this: define( 'UPLOADS', ''.'files' ); ...to get: > <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "images, urls, attachments" }
How to apply action the_post to the post that is only being mainly displayed I'm trying to write an action that will modify some WooCommerce product on its display. This is my simple code function do_some_modifications($post) { if (is_singular('product')) { // do some action } return $post; } add_action('the_post', 'do_some_modifications'); But the page contains two related products and "the_post" is called for them as well. How can I avoid running that code for additional products displayed on the main product page? Thank you!
Okay. Here we go! I needed this to be implemented within only one plugin, not inside the template. So I found out how to get the ID of current post outside the loop. The great function get_queried_object() and get_queried_object_id() will seal the deal! It might not seem the quickiest way (it queries the database) but in my case it is a perfect solution since I'm running this code not for every page and not every time it's loaded. And the final code is function do_some_modifications($post) { if (is_singular('product') and get_queried_object_id() == $post->ID) { // do some action } return $post; } add_action('the_post', 'do_some_modifications');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "actions" }
Setting a default thumbnail url if no thumbnail I have created a code to get an existing post's thumbnail and echo the url, but I would like to be able to have it get a default url is the post doesn't have a set thumbnail. Any help would be appreciated! Here's my code so far <?php $thumb_id = get_post_thumbnail_id(); $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail', false); ?> <div class="content" style="background-image:url(<?php echo $thumb_url[0]; ?>);"> Default Thumbnail url :
Just set up a condition to check that thumb_id isn't empty. If it is, use your alternative image. Pretty simple stuff. <?php $thumb_id = get_post_thumbnail_id(); if ( $thumb_id ) { $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail', false); $thumb_url = $thumb_url[0]; } else { $thumb_url = ' } ?> <div class="content" style="background-image:url(<?php echo $thumb_url; ?>);">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, thumbnails" }
add_menu_page does not seem to work in a class Here is some of my code: class proposal { function __construct() { add_menu_page('Topic Proposal', 'Topic Proposal', 'read', 'topic_proposal', array(&$this, 'writer_page'), 'dashicons-welcome-add-page'); } public function load_menu() { echo 'EHY'; } public function writer_page() { ?> <h1>Topic Proposal</h1> <?php } public function editor_page() { ?> <h1>Topic Proposal</h1> <?php } } add_action( 'admin_init', function(){return new proposal();}); The "Topic Proposal" shows of on the menu but when I click on it I get this: You do not have sufficient permissions to access this page. What am I doing wrong?
From `add_menu_page` in Codex: > Note: If you're running into the "You do not have sufficient permissions to access this page" error, then you've hooked too early. The hook you should use is admin_menu. `admin_init` is too early to hook `add_menu_page`, use `admin_menu`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, add menu page" }
Using a custom field value as current users name I'd like to use conditional logic to show a part of the single post page to a specific user. However the problem is Im pulling that username in from a custom field. Below is what I have so far. <?php if ( $current_user->user_login =='the_field("my_field")') { ?> <h1>Welcome <?php echo $current_user->user_firstname ?></h1> <?php the_content(); ?> <?php } else { ?> <?php the_excerpt(); ?> <div class="apply">APPLY FOR THIS</div> <?php } ?> And this is not working. However if i use the username as normal for example: <?php if ( $current_user->user_login =='jacksonsmith') { ?> Then this works fine. So, I'm wondering how can I use the value of a custom field within an if statement as user login name value? I am a newbie forgive my ignorance!! Thanks
First of all, you're testing for a string, as you're wrapping `the_field("my_field")` in single quotes. So, you want to remove these quotes. Next, `the_field("my_field")` outputs a field, it doesn't return it. You should try `get_field` instead of `the_field`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, content" }
Using Masonry - How to make every Xth post thumbnail image span multiple columns? To be specific: * I'm using Masonry to show all posts within a certain category * Thumbnail images for each post are shown on the category page in a 3-column format using CSS fluid width columns * I need to show the 7th thumbnail image spanning the width of all 3 columns In the past I've added a counter to posts to target the Xth post to apply a class and style accordingly. But is that possibly with Masonry, which is absolutely positioning elements? **EDIT** I'm using this code to query posts on the masonry page: if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); } elseif ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); } else { $paged = 1; } $args = array( 'posts_per_page' => 12, 'paged' => $paged ); // Override the primary post loop query_posts( $args );
So I couldn't figure out how to add a number sequence class to each post/article div, but I just changed the template for the 7th post in the masonry template. I did it like this: <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while (have_posts()) : the_post(); ?> <?php $count++; ?> <?php if ($count == 7) : ?> <article class="masonry-entry masonry-3col masonry-post-no-7"> </article> <?php else: ?> <article class="masonry-entry masonry-3col"> </article> <?php endif; ?> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "masonry" }
more tag in the $post->content when get_pages were used I used get_pages() to get the content of the child pages of a page. Although the excerpt can also be an answer but is there any other way to display the contents of the page before the more tag when I use the get_pages()?
You can use the WordPress function `get_extended` to fetch the different parts of a string (the part before and the part after the `<!--more-->` tag). `get_extended` returns an array with three keys, of which the keys `main` and `extended` are important: `$arr['main']` contains the part before the more tag, and `$arr['extended']` the part after the more tag. This would yield something like: // Fetch post content $content = get_post_field( 'post_content', get_the_ID() ); // Get content parts $content_parts = get_extended( $content ); // Output part before <!--more--> tag echo $content_parts['main'];
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, templates" }
Change RSS format for specific categories Is there way to have, **in a single RSS feed** , different formats for different categories? For example, if a post is a very long and technical one I would like to have only an excerpt (or a custom text with a link) and if it is short I would like to put the whole thing on the feed.
It certainly is! WordPress has filters called `the_excerpt_rss` and `the_content_feed` which filter the posts' content and excerpts for the RSS feed. The filter is called in the loop, so you can use `get_the_ID()` and `get_the_content()` (and other loop functions) to fetch information about the post. add_filter( 'the_excerpt_rss', 'wpse151603_rss_post_excerpt' ); function wpse151603_rss_post_excerpt( $excerpt ) { $content = get_the_content(); if ( strlen( $content ) < 200 ) { $excerpt = get_the_content(); // Get full content for use in feed } return $excerpt; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, rss" }
Adding custom fields to images I want to show sources under my every images. So basicly I want to add a simple custom field. I added this code to my function.php add_filter('attachment_fields_to_edit', 'edit_media_custom_field', 11, 2 ); add_filter('attachment_fields_to_save', 'save_media_custom_field', 11, 2 ); function edit_media_custom_field( $form_fields, $post ) { $form_fields['custom_field'] = array( 'label' => 'Custom Field', 'input' => 'text', 'value' => get_post_meta( $post->ID, '_custom_field', true ) ); return $form_fields; } function save_media_custom_field( $post, $attachment ) { update_post_meta( $post['ID'], '_custom_field', $attachment['custom_field'] ); return $post; } It is ok so far.But then things getting messy. Now my problem is where I can add this second calling code, I meant which .php get_post_meta( get_the_ID(), '_custom_field', true ) );
Where you put it depends, you likely want to put the `get_post_meta()` call: echo get_post_meta( get_the_ID(), '_custom_field', true ) ); into the according template file. But of course you can also hook into a filter or action from your `functions.php` or a plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, customization, post meta" }
Why is the server response time slowing my site down? My site is www.phoenixwave.com When I use Pingdom speed test and Google's speed test both give me the conclusion that my server response time is ridiculously slow...I'm using a Rackspace server. I'm just trying to get a general direction where I need to start troubleshooting. Should I look into different hosting? Am I having a server problem or a DNS problem? Thanks for any and all help provided from the community. See the result picture from Pingdom below: !Pingdom Test of Phoenixwave.com
This clearly isn't a DNS problem since "wait time" is counted after domain was resolved and connection to server has been established. What you can start with on WordPress level is getting a plugin which will show you is this time is actually spent inside WP page load. Laps (disclosure — developed by me) or Query Monitor are what I look at first for issues like this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "performance, server, shared hosting, dns" }
How to Emulate Default Navigation Menu Behaviour in a Custom Theme? I'm trying my hand at developing a custom theme, and I've got navigation menus working (with the help of this walker, but only if they're explicitly defined in the menu settings. The default themes (twentyfourteen, twentythirteen) seem to be able to create a default menu solely from the existing pages hierarchy, without needing to create a separate menu structure. I've had a look around the source for the twentyfourteen theme, but as far as I can tell, the menu is generated with a standard `wp_nav_menu` call. I don't see anything that accounts for how it loads a menu when none are defined. Does anyone know how I can automatically populate my menus as the default themes do?
The default `wp_nav_menu` arguments set the `fallback_cb` argument to `wp_page_menu`, which outputs a list of pages if your menu doesn't exist. If your menu doesn't behave this way, that argument has been overridden in some way, either from being explicitly set in the `wp_nav_menu` call, or perhaps via the `wp_nav_menu_args` filter.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, menus, theme twenty fourteen" }
How to get comment id in callback function? I am trying to get the comment ID in the custom callback function that I can use in wp-list_comments. Any help on how to do this? Thanks in advance I am using wp_list_comments as: ` wp_list_comments('avatar_size=60&type=comment&callback=get_the_rating');` Note: I was trying to use arguments earlier but I am not sure if I can use arguments in callback functions.
The callback is already passed arguments but crazily the codex doesn't document them. However it does give you an example and the first two lines are: function mytheme_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; which matches the equivalent functions in the bundled styles. Once you've set the comment object passed as the global as in that example then you're then free to use `get_comment_ID()` as usual. If you didn't want to set the global then $my_comment_ID = apply_filters( 'get_comment_ID', $comment->comment_ID ); is equivalent, but it's probably safer to go through `get_comment_ID()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "comments" }
How to separate the tags? Ok I have searched and can't find. Here is what I'm trying to accomplish. I want to separate the tags in my post. For example, I want to show the first tag in my post but have all other tags show when you hover over the more button. Now the css and the menu I can handle, but how do I get the tags to separate, like placing the first tag in one div and the rest in another div that is hidden except on hover. !enter image description here In the photo above, I want the other tags to appear once they hover over the "+" button. `<?php the_tags( __( '<span class="tag-links">Tags: ', 'wpbx' ), ", ", "</span>\n" ) ?>`
You need to use another function to get the tags, something that returns an object or an array, like that you can manipulate it as you need. < <?php $my_tags = get_the_tags();?> Then where you need the first tag: <?php echo $my_tags[0]->name?> For looping the rest except the first tag: <?php $count=1; foreach ($my_tags as $my_tag) { if ($count != 1) {?> <li> <a href="<?php echo get_tag_link($my_tag->term_id);?>"> <?php echo $my_tag->name?> </a> </li> <?php } $count++; }?> Hope it helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags" }
How to hook watchdog script for existence of a WP page? I would like to have a watchdog script which checks the (un)availability of a certain DB entry, namely a certain WP page. The script itself is absolutely independent from WP and not difficult, but I don't know how where I hook this script into WP. It should be called with every website visit.
An easy way to do this would be to create a simple Must Use Plugin and check for your page in a function hooked to an action, like `wp_loaded` function wpd_check_page_exists(){ $page = get_page_by_title( 'The Page' ); if( !$page ){ wp_mail( '[email protected]', 'a message from your site', 'the page is gone!' ); } } add_action( 'wp_loaded', 'wpd_check_page_exists' ); You may want to use a different function to query the page, depending on how you identify whether it exists or not, like `get_post` if you want to pass an ID, or `get_page_by_path`, or `WP_Query`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
Adding more onto an esc_url I have an esc_url that creates a link to buddypress profiles depending on the author of the post which returns like this < I want to make it so it returns "posts" at the end of the url too like so, < The code I have. esc_url( bp_core_get_userlink( get_the_author_meta( 'ID' ), $no_anchor = false, $just_link = true )), I tried placing the following && 'posts' || 'posts' after the bp_core_get_userlink( get_the_author_meta( 'ID' ) and other parts of the code line but my PHP isn't great so I'm not sure exactly how && and || works. Worth a try though. Thanks for the help in advance :)
To concatenate strings, PHP uses the concatenation operator `.`. Thus, to append a string to the current user link, you can use bp_core_get_userlink( get_the_author_meta( 'ID' ), false, true ) . '/posts/' Note that I've removed the first part of the assignment from the `$no_anchor` and `$just_link` parameters, as the values should be passed, and not the assignments themselves. In general, I suggest you start by reading a few basic PHP tutorials.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, buddypress" }
Using a private method as an action callback from within a class I have created a class from within which I would like to call a private method (from within the same class) from the `__construct` method as an action callback. When I would like to use a public method I can access it by: add_action( 'init', array( $this, 'action_callback' ) ); However, this causes an error when the method is private. I have also tried unsuccessfully: add_action('init', $this->action_callback() ); How do I access a private method? The class looks something like: class My_class { public function __construct() { add_action( 'init', array( $this, 'action_callback' ) ); } private function action_callback() { // do something } }
It's not possible to call a private method through an action or filter. When calling `add_action` or `add_filter`, WordPress adds the callback to a list of callbacks for that specific action or filter. Then, when `do_action` or `apply_filters` is called, WordPress uses `call_user_func_array` to call the linked functions and methods. As `call_user_func_array` is not called from within the class, it can't call private methods of that class. Furthermore, there's no proper way to really keep the method private, even though you could add a separate (public) method to your class, add that as a callback to the action, and have that call the private method. In doing that, however, you lose the real concept of the method being private.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 4, "tags": "functions, actions, private, callbacks" }
How To Add Perfect Apostrophe And Quotation Mark In WordPress Posts? I have a blog at www.exeideas.com where I am sharing codes snippet too. I am new to WordPress and migrated from Blogger. So now my all codes shared in posts stop working. When I check my codes then found that all was fin but just Apostrophe, Quotation and, Dash are changes that is causing to stop my codes. I am sharing below what I am getting and what I want. 1. I am getting `’` and want `'`. 2. I am getting `”` and want `"`. 3. I am getting `‘` and want `'`. 4. I am getting `–` and want `-`. Now tell me what to do to fix this out. My code box CSS is given below. `#execodediv0 {width:99%;max-height:300px;border:3px solid black;overflow:auto;font: 12px Arial!important;word-wrap:break-word;}`
The filter responsible for adding these characters is wptexturize, you can remove it using remove_filter. remove_filter( 'the_content', 'wptexturize' ); remove_filter( 'the_excerpt', 'wptexturize' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, shortcode, code, css" }
Bootsrtap.css overlap style.css in custom wordpress theme On creating a custom theme i faced one problem < lookwise its not look so good because it not supported style.css By default it shows all its css properties from bootstrap.min.css. I want theme look good like this html < what should i do so that theme take all its css properties from style.css. Thanks in advance
You can load first `bootstrap.min.css` and then after your main `style.css` and Set `About Us` as `About`, then your issue is solved.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, responsive" }
Retrieve a specific field from taxonomy term through advanced custom fields I've set up a custom field which appears in a taxonomy terms page. I am trying pull an image associated with the custom taxonomy term directly However the page in which it is being displayed is a template page. I think I need to pass the post ID before pulling the specific image, but how do you do that for a custom taxonomy? The custom taxonomy is 'manufacture', and the term id is e.g 1, the image field id is 'image_toc' and I have set ACF to image url. I've read the page on "how-to/how-to-get-values-from-a-taxonomy-term/" but I don't really understand what I'm supposed to replace with what. I am using things along the lines of: <img src="<?php the_field('image_toc', 'I am giving term id here'); ?>" /> But nothing is happening. No image and no path in the source code.
To retrieve a field from ACF for a term (instead of, for example, a post), you should use the taxonomy name, followed by an underscore, followed by the term ID instead of the post ID when calling `the_field` or `get_field`. Assuming you want to retrieve the field `image_toc` for the taxonomy `mytax` and term ID `$termid` that would be: <img src="<?php the_field( 'image_toc', 'mytax_' . $termid ); ?>" /> In your case, this would amount to <img src="<?php the_field( 'image_toc', 'manufacture_1' ); ?>" />
stackexchange-wordpress
{ "answer_score": 9, "question_score": 2, "tags": "custom post types, custom taxonomy, terms, advanced custom fields" }
Annoying notification when trying to create a new page Whenever I try tomake a new page, I get an annoying block asking me so upgrade some plugin of some sort. Is there a way to get rid of this extremely annoying notification? !enter image description here
This notification is added by your theme. You can remove the upsell notices for this theme by hooking into the `ttfmake_is_plus` filter: add_filter( 'ttfmake_is_plus', '__return_true' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, notifications" }
Query child's child categories I'm building a query to get the child's child categories. For example : I have a parent category named 'animal' and others like 'food' and 'sport'. I want to get animal's sub categories. I do : $parent_cat = get_cat_ID( $cat_name ); $args = array( 'type' => 'post', 'parent' => $parent_cat, 'order' => 'DESC' ); $categories = (array) get_categories( $args ); And no problem, with a foreach I get my animal's sub categories. In my sub categories, I also have categories (this is a 3 levels hierarchy). I do the same : $child_cat = get_cat_ID( $sub_cat_name ); $args = array( 'type' => 'post', 'parent' => $child_cat, 'order' => 'DESC' ); $sub_categories = (array) get_categories( $args ); And... it returns the others parents categories 'food' an 'sport'. Why that ? Where am I wrong ?
Ok then, I actually was getting the subcats with the wrong method. in `$parent_cat = get_cat_ID( $cat_name );` `$cat_name` wasn't a name but un slug. First mistake. So I corrected with `$parent_cat = get_category_by_slug( $cat_slug );` The final code is : // Get the parent cat thanks to the page's cat slug $parent_cat = get_category_by_slug( $cat[1] ); $args = array( 'type' => 'post', 'parent' => $parent_cat->term_id, 'order' => 'DESC' ); // child cats $categories = get_categories( $args ); // loop on the child cats to get the sub cats object foreach ($categories as $key => $value) { return $value; } That's it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Proper Way to Enqueue CSS for Front Page - template_redirect in functions.php? I want to load some specific css to change color of body element of front/home page of WP. Within my themes function file, the following code seems to work, but can someone please tell me if it is "proper"? //Adding and Encuing styles for Front Page add_action( 'template_redirect', 'front_page_design' ); function front_page_design(){ if ( is_front_page() || is_home()) { add_action('wp_enqueue_scripts', 'enqueue_index_styles'); function enqueue_index_styles() { wp_register_style( 'home_page_style', get_stylesheet_directory_uri() . '/index-style.css' ); wp_enqueue_style( 'home_page_style' ); } } } I had come across a blog by Mark Jaquith saying that template_include is for including, which is what I'm doing, right?
Nope. Use the `wp_enqueue_scripts` hook directly for enqueing all styles and scripts. There's no need to hook into `template_include` for that. `template_include` is specifically for modifying templates. //Adding and Encuing styles for Front Page add_action( 'wp_enqueue_scripts', 'front_page_design' ); function front_page_design(){ if ( is_front_page() || is_home()) { wp_enqueue_style( 'home_page_style', get_stylesheet_directory_uri() . '/index-style.css', array('handle_of_main_style') ); } } Where 'name_of_main_style' must be changed to match the handle of the stylesheet you want to load 'home_page_style` after.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "template redirect" }
Foreach displays from last to first I created the foreach loop to display post images, but It displays them from last to first, how can I make It to displays from first to last ;) ? <?php $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ); $attachments = get_posts( $args ); if ( $attachments ) { foreach ( $attachments as $attachment ) : ?> <p> <?php echo wp_get_attachment_image( $attachment->ID, 'full' ); ?> </p> <?php endforeach; } ?>
Why wouldn't you just pull them in the order you need instead of reversing the array? $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, // correct key is posts_per_page, not numberposts 'orderby' => 'date' 'order' => 'ASC', 'post_parent' => $post->ID ); $attachments = get_posts( $args );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop, php" }
Site Title in my Search URL First off, I am still learning Wordpress by building my own theme. Go easy on me. My search URL displays my sites title. Example: `/My%20Site?s=horror` Is there an issue with my searchform.php that is causing this? If its the `bloginfo();` then what can I use as a replacement? <form action="<?php bloginfo('search'); ?>" id="searchform" method="get"> <input name="s" class="nav-search" type="text" placeholder="Search Videos"> </form>
Use `<?php echo home_url( '/' ); ?>` as the action. 'search' by the way is not a valid `bloginfo` parameter.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search, urls" }
Show excerpt for only first post in query I'd like to only show the excerpt for the first post in my main query. I was wondering the best way to approach this. What I have tried so far is: 1. Making a custom homepage and using two queries, one that returns 1 post with an excerpt and another queries that returns posts without. 2. Just using the default queries but using css to hide the excerpts for all posts but the first, using `nth-child`. Both of these work well enough, but I was wondering if there was a better way to do this, through a function or filter. Thanks!
You can use `$wp_query->current_post` in your loop to check the current post. You don't need two loops, one will do the trick If you need excerpt for first post only, you can do something like this. Just remember, the first post in the loop is `0`, and not `1` if ( !$wp_query->current_post > 0 ) : the_excerpt(); else : <--- DO SOMETHING ELSE FOR OTHER POSTS endif; For all the **`WP_Post`** member variables, go and check the link provided from the codex
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "functions, theme development, filters" }
Why use while over if in single wordpress posts? Why is `while()` used instead of say `if()` here: <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php _s_post_nav(); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> So I've seen this since forever and I've used it too because it's what Wordpress uses by default. However today I'm feeling a bit more curious than usual - why is while used instead of if ? Am I expecting to receive more than a single post in single post view ? < <
As the WordPress Codex for `have_posts` points out: > As a side effect, have_posts starts, steps through, or resets The Loop. At the end of the loop, have_posts returns 0 after calling rewind_posts. Looking at the source as it stands today: along with calling `rewind_posts()` it also fires the `loop_end` action (which plugins may rely upon) as well as set a flag so `in_the_loop()` correctly returns false afterwards. So calling `have_posts()` on each iteration does more than just return a Boolean. I wouldn't lean too much on the specifics of the source because that's a moving object. It's enough to understand that there are other housekeeping tasks performed when you call `have_posts()` until it returns false and you're less likely to introduce subtle interoperability issues if you use it that way even when there is only a single post involved.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "theme development, themes, single, core" }
Copying database tables to new database am trying to migrate my old site to a new site, by only copying database tables. the reason doing this way is the old site is out of date with plugins etc and i have WooCommerce installed which i dont have translated only post/pages are in 2 languages. After iv copied over the tables when i went to pages/post it shows 0, yet WooCommerce shows all. iv ran through your WPML troubleshooting to fix any errors etc… this seems to work! but it now shows all pages but not under any lang! How can i can copy this correctly ?
Export your tables using phpmyadmin interface. Just select those tables only that you want to export from the old database and import those tables in the new database or you can run the command(query) in mysql to copy one table create table newdbname.newtablename like olddbname.oldtablename; INSERT INTO newdbname.newtablename SELECT * FROM olddbname.oldtablename; Repeat the same command to copy other tables
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "database, migration, plugin wpml" }
get_intermediate_image_sizes() returning different values depending on is_admin() I have checked the code of the "Simple Image Sizes" plugin and found out how "they" read the available thumbnail/image sizes. However when I use the `get_intermediate_image_sizes()` function in a plugin with an `if( is_admin() )` clause surrounding it, it only returns the 3 standard WP sizes (thumbnail, medium, large). I have 4 custom images sizes registered with `add_image_size()`. Any ideas?
The problem was that I read the image sizes inside the "init" hook at which point the additional sizes are not loaded yet by Wordpress. I used a "later" hook now and it works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "thumbnails, images" }
Difference between the_permalink() and get_permalink() function In WordPress I am using both `the_permalink()` and `get_permalink()` functions, but I cannot get any difference in the output of both functions. What is the difference between both functions?
`the_permalink` echos out the permalink of the current post to the frontend. `get_permalink` however returns it as a variable, but does not echo it out. You can also pass a post ID to it if you want the permalink of another post. `the_permalink` is equivalent to: echo get_permalink(); Which is very close to what it actually does. This is the implementation of `the_permalink`: function the_permalink() { echo esc_url( apply_filters( 'the_permalink', get_permalink() ) ); }
stackexchange-wordpress
{ "answer_score": 20, "question_score": 12, "tags": "functions, permalinks" }
Using $seed on a custom post type for randomly displayed posts I saw this link to display posts randomly without duplicating them. However how do you apply this to a custom post type? Below is what I'm using in functions to make it randomly display. session_start(); add_filter('posts_orderby', 'edit_posts_orderby'); function edit_posts_orderby($orderby_statement) { $seed = $_SESSION['seed']; if (empty($seed)) { $seed = rand(); $_SESSION['seed'] = $seed; } $orderby_statement = 'RAND('.$seed.')'; return $orderby_statement; }
This is untested, but I think it should work. Add the filter in `pre_get_posts` if it's your post type archive, otherwise remove it for any queries that follow the post type archive main query. function wpd_add_posts_orderby( $query ){ if( $query->is_post_type_archive('your-cpt') ){ add_filter('posts_orderby', 'edit_posts_orderby'); } else { remove_filter('posts_orderby', 'edit_posts_orderby'); } } add_action( 'pre_get_posts', 'wpd_add_posts_orderby' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, query posts, pre get posts" }
Checking for existence of a page by title? I'm currently working on a plugin, and I essentially want to check if a certain page has been created. Essentially, I want to do something like this: if (file_exists($file)) { $exists = true; } else { $exists = false; } But I just want to do it so that it checks, instead, for a post_name value. (If I was further able to ensure that the post was a _page_ and not just a post with that title, that would be great too.) How do I do this? I had been getting the script to grab the headers from the url of the post and if it returned a 404, to return $exists = false, but I've pinpointed a memory leak problem with that and I don't think it's very efficient.
Using `get_page_by_title()` along the line of below exemplary code should work: if ( get_page_by_title( $page_title, $output, $post_type ) == NULL ) { $exists = false; } else { $exists = true; } _Explanation:_ * `$page_title` is obviously what you are looking for; * `$output` can be OBJECT, ARRAY_N or ARRAY - Default: OBJECT; * `$post_type` can be specified, in your case its not needed, because the default value is `page`; * Returns `NULL` if no post with the title is found; * For the inner logic take a look at the source.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, functions, title" }
How to get the slug of the homepage when editing it in WP admin? According to the WP_Class reference, `$post->post_name` holds the value of the slug of the current page being viewed. If I'm currently viewing the WP admin edit screen for my homepage as set under Settings > Reading > Front page displays > A static page > Front page, what would be the value of `$post->post_name` if I do the following? global $post; echo $post->post_name; I wasn't aware my homepage had a slug. Would the value be an empty string? Hoping someone can help clarify. Thanks in advance.
`post_name` would be the slug as it was set before the page became the front page. When the URL for the front page is output via the API, the `get_page_link` function checks if the ID matches the `page_on_front` option and returns the `home_url` in that case. This is why you should always use the API to output data and not directly access post object fields.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Single page problem when permalink type changed I have a custom post type which i create and works perfect without any problem, its a team page to show some members in a company, also i created a single-team page to show more details about each member. The problem is when i use Default Permalinks works without any problem, but when use Post name permalink a got 404 error page not found. i hope i didn't miss anything to make this work.
Can you make sure that your .HTaccess is writable with necessary permissions that includes the Following as I suspect that WP is not able to alter it : # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, permalinks, single" }
How to expand picture to cover entire header area? (twenty-twelve theme) I am running twenty-twelve theme and have applied a header background on the .site-title class. Header shows up but it's width is only 960px. How do I disable the left and right margins/padding of this theme so I can expand the picture to cover entire header area? ( I don't know what css code to add) Here's a picture if it makes more sense: Thank you in advance!
You will have to do a lot of modifications on this one. We are going to modify header.php file Firstly move this piece of code from header tag file to below body tag <?php if ( get_header_image() ) : ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php header_image(); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /></a> <?php endif; ?> wrap this code in a div <div class="header-full-width"> <?php if ( get_header_image() ) : ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php header_image(); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /></a> <?php endif; ?> </div> Now add css .header-full-width img { width: 100%; } This should do the trick.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme twenty twelve" }
Modify text after post count On my Archives page, I list categories with post counts. I've modified the post count by removing the parentheses, wrapping them in a span that floats them to the right, and putting the word "Entries" after each post count. But I'd like the text after the count to change for categories with only a single post (i.e. "Entry" instead of "Entries"). My current code for this is: <?php $variable = wp_list_categories('title_li=&echo=0&show_count=1'); $variable = str_replace( '(', '<span class="cat-count">', $variable); $variable = str_replace( ')', ' Entries</span>', $variable); echo $variable; ?> How can I modify this so that categories with 1 post say "1 Entry" and those with more than 1 say "X Entries"? You can see my Archives page here
The `_n()` function will sort out single from plural. How to use it is in the codex. **EDIT:** Apologies. My first go at an answer wasn't quite enough to get you there. The trouble with using `wp_list_categories()` in this context is that it prints out pre-formatted HTML and you don't end up with any value you can use for $count. Instead, try using `get_categories()` which will return an array of category objects you can tap into to get post counts and display accordingly. Something like the following should do the trick, or at least get you started: <?php $categories = get_categories(); echo '<ul>'; foreach($categories as $category) { echo '<li><span class="cat-count"><a href="' . get_category_link( $category->term_id ) . '">' . $category->name.'</a>'; echo ' ' . $category->count . _n(' Entry', ' Entries', $category->count ) . '</span></li>'; } echo '</ul>'; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "archives, categories, count" }
Using get_query_var() from a plugin I'm trying to do a redirect feature in a plugin and i have an issue. First, the code: add_action( 'init', function(){ add_rewrite_rule( 'go/([^/]+)/?$', 'index.php?redirect_to=$matches[1]', 'top' ); add_rewrite_tag( "%redirect_to%", '([^&]+)' );` } ); Ok, so, the rule is set. The tag is set. If i'm using `get_query_var('redirect_to')` inside of `functions.php` (or anywhere in the theme actually) it works, but if i'm trying to use the same query var from the plugin files, it silently fails. And since it's a plugin, there is no way to ask users to edit their themes :) Things i did: * i'm using it inside of `init` hook set as priority 999 * it works if i use `wp_head` instead of `init`, but this way i can't do the redirect anymore * i flushed rewrite rules So, my question is: how do i use the damn `get_query_var('redirect_to')` inside of my plugin files? Thanks!
Hook into `parse_query` instead: add_action( 'parse_query', function() { add_rewrite_rule( 'go/([^/]+)/?$', 'index.php?redirect_to=$matches[1]', 'top' ); add_rewrite_tag( "%redirect_to%", '([^&]+)' );` } ); Reason: `init` is too early, query_vars haven't been set yet. `wp_head` is too late, no can redirect at that point.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "rewrite rules" }
Getting Term_id - Taxonomy Metadata plugin I've been looking everywhere but can't find any way to make this works. I am using the Taxonomy Metadata plugin and I am trying to display the custom metadata created. For this I use: `get_term_meta($term_id, 'my_metadata', TRUE);`. The problem is that I can't find a way to get the term_id. I am in a template page inside the loop. Here is what I have tried: $term = get_term_by('name', 'name', 'custom_taxonomy'); $termid = $term->term_id; $metadata = get_term_meta($termid, 'my_metadata', TRUE); But it's not working, it just returns: `Trying to get property of non-object` for the term_id. Could you help me please? Thank you!
Alright, I have found a way. If it can be useful for someone here is how I solved it: $terms = get_the_terms( $post->ID , 'custom_taxonomy' ); if($terms) { foreach( $terms as $term ) { $term_id = $term->term_id; } } Then you can use `$term_id` in your expression.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "terms" }