INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Count search results in heading
On my wordpress search page I would like to show a 'total found results'. This needs to be shown at the top of the page in a heading.
I've tried this code but I gives me only the results of the specific page. What I want is all the results, not just the page.
<?php echo $wp_query->post_count; ?> | If you check the documentation for `WP_Query` you will notice that `post_count`, which you are using, returns the number of posts being displayed. That is what you see, but not what you want. `found_posts` returns the total number of results for the query, which _is_ what you want.
> $post_count
> The number of posts being displayed.
>
> $found_posts
> The total number of posts found matching the current query parameters
Note that if your query runs with `'no_found_rows' => true` the `found_posts` value will be 0, and there is a `found_posts` filter that can effect the result as well. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, search, count"
} |
Can a plugin differentiate syndication feeds from actual site views?
Is there anything in the WordPress API that I can use in a plugin to detect whether the current request to WordPress is a pull of the syndication feed -- as opposed to an actual view of the web-site?
I ask this because it is critical that one specific behavior of the plugin be different for syndication feeds than for actual web-site views. | You can use the template tag `is_feed()` to determine if the current request is for a feed:
if ( is_feed() ) {
// It's a feed!
} else {
// Regular 'ol WordPress
}
Note you'll need to use the function _after_ the request has been parsed (i.e. on or after the `parse_query` hook). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, rss, api"
} |
Overwriting yoast's og:meta output?
I'm working on a blog with hundreds of old posts, and new posts being added daily. I can't change their flow of filling out the yoast meta tag for title. They want the og:title value to be something else though, a custom post_meta value from the same post.
How can I hook into yoast before they grab the title, and say "Don't use the yoast title, instead if we have a custom title filled out, use this one."
If this isn't possible, an alternative option would be to just output a duplicate og:title tag either before or after yoast, so that the yoast tag is ignored. Would I place my tag before or after to wipe out the yoast tag, and would there be a negative impact from having the two tags? | Use the `wpseo_opengraph_title` filter:
function wpse_187763_wpseo_opengraph_title( $title ) {
if ( is_singular() && $post = get_queried_object() ) {
if ( $_title = get_post_meta( $post->ID, 'custom_field_key', true ) )
$title = $_title; // Override title with custom meta title
}
return $title;
}
add_filter( 'wpseo_opengraph_title', 'wpse_187763_wpseo_opengraph_title' );
**Update:** The single `=` is intended, since we're assigning the value & testing the expression at the same time. In other words, it's the same as:
$_title = get_post_meta( $post->ID, 'custom_field_key', true );
if ( $_title )
$title = $_title; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin wp seo yoast"
} |
Upgrading an old Wordpress install to a new one on a new host
I have a Wordpress blog on my server at home, running the latest Debian-maintained version in the 3.x series. I want to try my hand at virtualizing, and I'd like to do it on my blog, using the latest version downloaded from the site. I have read this post, but I want to clarify about different versions.
Is it recommended to upgrade in place (possibly breaking the Wordpress meta-package for Debian) then transfer, or should I transfer, then upgrade? In the latter, would I be able to just directly import a 3.x WP site, or do I need to find the old version, then update it after the data is transferred? | Most of the time any changes that need to be done on upgrade are database related. Core files can be freely swapped pretty much.
WP keeps track of this by comparing `db_version` option (stored in database) against the current value (from core files) on admin load. If there is mismatch it runs the upgrade routine to perform all the necessary changes, until the version is up to current.
In your case the easiest way would probably be:
1. Unpack latest stable WP core at new location
2. Copy old database to new location (or simply reuse old one) and configure new core to see it
3. Copy content folder to new location (configure new core to see it if not placing inside the core folder)
4. New core would pick it up as existing WP site with outdated database and perform the necessary updgrades | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "upgrade, migration"
} |
Reset password - set minimum length for new password
I’m trying to set a minimum length for the new password when resetting the password. I would like to add something like this just functional.
add_action( 'password_reset', 'reset_my_password', 10, 2 );
function reset_my_password($user, $new_pass, $errors) {
$errors = new WP_Error();
if ( strlen( $_POST['new_pass'] ) < 8 ) {
$errors->add( 'password_too_short', "<strong>ERROR</strong>: Password is too short." );
}
}
Any help with this would appreciated. | You may want to use the validate_password_reset hook instead.
Try
add_action( 'validate_password_reset' , 'se_password_min_length_check' 10, 2 );
function se_password_min_length_check( $errors, $user){
if(strlen($_POST['pass1']) < 8)
$errors->add( 'password_too_short', 'ERROR: password is too short.' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "password, reset"
} |
ACF Relationship - Exclude pages not created by author
I have pages that I would like to exclude in a ACF relationship field.
My field name is `products` and the following code excludes the pages with id 9, 10 or 11.
add_filter('acf/fields/relationship/query/name=products', 'exclude_id', 10, 3);
function exclude_id ( $args, $field, $post ) {
$args['post__not_in'] = array( $post, 9, 10, 11 );
return $args;
}
Instead I would like to exclude pages not created by a certain user.
I have user called `collaborator` and want to exclude all pages that dosen't have `collaborator` set as author.
I would rather exclude pages by author name rather than the author id, like
author_name('collaborator');
Is this possible? | If you want to exclude ALL pages that doese't have 'collaborator' set as author, then you want to exclude all other pages in the site and include all pages of that author minus, maybe, some hand picked pages of that author, then I think you can use this:
add_filter('acf/fields/relationship/query/name=products', 'exclude_id', 10, 3);
function exclude_id ( $args, $post ) { //$field input vriable wasn't neccessary in this function
$args['post__not_in'] = array( $post, 9, 10, 11 );
$args['author_name'] = 'collaborator'; // Queries only the collbaroator's posts
return $args;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "author, advanced custom fields"
} |
Wordpress tabindex Order
I created a form (through Contact Form 7, although I don't think that makes a difference here), and I believe Wordpress is causing some tabindex issues. I set field 1 to tabindex of 1, field 2 to tabindex 2, etc. Well, when I try to tab from field 1 to 2, it displays a popup in the top left of the screen saying "Skip to toolbar." After researching (not finding a whole lot), I set field 1 to tabindex 3, and went up 1 from there. Well, after tabindex 10 it tabbed to the top of the screen just above the nav. I then came across this page which offers a script that sets the tabindex's very high intentionally. My question is, is that semantically correct or just a work-around? | The "Skip to toolbar" in the WP Navbar comes `tabindex` attribute set to 1; I really think it is correct because it is the first visual element when the navbar is active. The problem is that the HTML of the navbar isn't really the first in the source code, it is in the footer, so your form fields are first in the source code. When two elements has the same `tabindex` attribute, they are navigated in the order they appear in the character stream. So, when you set your fields with tabindex 1 and 2, you go first to your field 1 (it the first in the character stream), then to next `tabindex` 1 element (WP navbar) and then to `tabindex` 2 element (your field 2).
This issue shold not happend when the navbar is inactive.
You can start the `tabindex` of the form fields in 2 or 3, there is nothing wrong with that. The `tabindex` can have any integer value, correlative or not. You can set `tabindex` like `1, 2, 3, 4`; `10, 15, 20, 25` or `84, 12, 98` and all of them are correct. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "forms"
} |
How to stop - Database Update Required - from happening again?
So I have had the issue several times now where whenever I update WordPress it gives me the "DataBase update required" and then will not login in to the site. This happens every time I upgrade to the newest version of WordPress.
My fix for this issue is to set the **db_upgraded** field in **wp_option** table in the database and purging the cache.
Fix Database update required
However what I want to know is, how can I stop this happening again? What is happening to bring up this error? Why is WordPress ending up in this loop?
Now I could understand there could be various reasons but if anyone has had any success with solving this issue your help would be greatly appreciated. | Was a bug in the core, I published the ticket ( < ) and is added for the next version 4.2.3.
In this version the code change the collation of some tables and this works fine if the change is fast. But in big tables this change take time, hive a timeout in the upgrade process and can't continue, so is a loop.
In your case, the cache data was the reason of the big table size, then you clean the cache, the table is small and you can continue the upgrade. In case you can't "clean" de wp_options table you can replace this file < , has the patch to solve this "loop".
About your question "how can I stop this happening again?", this was a bug, is not a wrong settings of your installation or a plugin or some like this.
I hope this help you. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp admin, updates, upgrade"
} |
How to show only posts with images?
I want to hide posts without images on the front page, so I need get an array of ids of those posts.
I know how hide posts on the home page by id, but I need to show only posts with images. This is what I have already:
function exclude_post($query) {
if ($query->is_home) {
$query->set('post__not_in', array(1,2) );
}
return $query;
}
add_filter('pre_get_posts','exclude_post'); | No need for post IDs what has no thumbnail. Use meta query to get only those what has thumbnail.
Add meta query
function get_only_posts_with_images( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'meta_query', array( array( 'key' => '_thumbnail_id' ) ) );
}
}
add_action( 'pre_get_posts', 'get_only_posts_with_images' );
Or use custom query.
$query = "
SELECT posts.*
FROM $wpdb->posts AS posts
INNER JOIN $wpdb->posts AS attachment
ON attachment.`post_parent`=posts.`ID`
AND attachment.`post_type`='attachment'
WHERE posts.`post_type`='post'
";
$posts_with_images = $wpdb->get_results( $query, OBJECT ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "images, query, frontpage"
} |
How to Output HTML tags in do_shortcode?
i want to output html tags in do_shortcode(); function
`<?php echo do_shortcode($content); ?>`
is it possible? thx! | Yes it is possible.
There are two ways that I can think of at this moment.
First follow what the codex says Shortcodes. Basically you just wrap your html in ob_start(); this will return the html as a string so you can echo it.
function my_shortcode() {
ob_start();
?> <HTML> <here> ... <?php
return ob_get_clean();
}
The second way is to add your html as a string to a variable then return it later. eg.
function my_shortcode() {
$output = '';
$output.= '<html>content</html>';
return $output;
} | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 5,
"tags": "shortcode, html"
} |
Missing "Registration" page with BuddyPress
So, I'm a total newbie on BuddyPress and can't seem to understand how is it supposed to work... The question is simple: there is no registration page generated, and even though "Anyone can register" is ticked, when I manually added a login page, there is still no option for registration whatsoever... Any tips would be appreciated... The site where I'm trying to get this done is: < | <
You can create a register now link which will redirect to the above page.
Just adding "?action=register" at the end of the URL will do the work for you.
You can Create a Register page too.
Do Search how to display Register form. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "buddypress, user registration"
} |
How to transfer /wordpress folder from one PC to another
I am currently developing my own website, and I am hosting it locally using `WAMP`.
I thought that if I want to copy the website on some other PC I just have to copy the `/wordpress` folder to the `/www` folder of WAMP on the other computer, but seems like that's not working at all as I expected.
Can someone explain me what else do I need to copy in order for my website and hosting to be **exactly** the same as on the original computer? | You have missed to copy the database associated with WordPress install.
Go to `PHPmyAdmin`(< Select the database and click `Export` all the tables.
In your other PC, Go to `PHPmyAdmin`, Create new user and a database. `Import` the file that was downloaded while exporting. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "localhost"
} |
Page Template For Custom Post Type doesn't work on URL containing CPT name, other URL's work
Here's a mystery for you. I created a Custom Post Type called "portfolio". Then I wanted a page template to show just those CPT's. It's a custom loop with paging, and it works perfectly if I don't call the page "portfolio" (that is, the permalink) - if I use that, it shows my static home page instead, no loop output. Very odd, since the page I'm using is not the front page.
My first thought is that maybe by using a permalink that matches the CPT name, I'm running into some standard core loop or something.
Or maybe I should just use an archive template instead of using a page template? I was considering the page template so I could have some custom output on the first page, maybe via a custom field.
I am using a cache, but I tried clearing the cache and even disabling it. Same thing.
Any thoughts?
My permalink structure is /%post-name%/
Thanks! | I have had similar mysterious behaviour with CPTs and pretty permalinks. Try to regenerate your permalinks by switching to another structure and back again.
Or check out flush_rewrite_rules() in the codex.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, page template"
} |
if is_singular array not working as expected
I'm using the following if statements within header.php to load custom tracking codes.
<?php if ( is_singular( array( 'custom-post-type', 'post-name' ) ) ) : ?>
// Specific tracking code here
<?php endif ?>
<?php if ( is_singular( array( 'custom-post-type', 'another-post' ) ) ) : ?>
// Specific tracking code here
<?php endif ?>
When I go to each post, both tracking codes are showing up. Am I doing something wrong here? | You are using an incorrect check here. `is_singular()` returns true when a post is from the specified post type or post types or the default post types when none is specified. You cannot target specific single posts with `is_singular()`
You have to use `is_single` to target a specific post
if ( is_single( 'post-a' ) {
// Do something for post-a
} elseif ( is_single( 'post-b' ) {
// Do something for post-b
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "array, single"
} |
Url link to feature image in the portfolio
I am new to Wordpress. i have issue with Feature image. just i need to add URL to feature image(when we click on that feature image , it should redirect to that particular URL).
also is it possible to give URL to Title of the Portfolio categories page which i used in normal page.
!enter image description here
This is Portfolio , i have used in the "mypage" . so in that" mypage" when we click on that image and title it should be redirect to the link (should able to give individual link)
!enter image description here
Any help would be appreciated. Thanks. | I think it is possible with custom fields.
Add a custom fields, for example, named `link`. Put the link into the value field. Then you will be able to access it something like that:
<a href="<?php echo get_post_meta( get_the_ID(), 'link', true ); ?>">
<?php the_post_thumbnail(); ?>
</a> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, post thumbnails"
} |
php string inside shortcode does not work
I want to automatically get products from woocommerce for a chosen brand, inside a brand's listing on a other part of the site using Sabai Directory.
this
<?php Sabai::_h($entity->getSlug());?>
stamp listing slug on the page
The plugin shortcode pick a list of product of a chosen brand
[shortcode_products_by_brand title="Sample brand products" per_page="12" columns="4" orderby="title" order="desc" brand="brand_slug" operator="IN"]
listing_slug equals to brand_slug so i tried with this
<?php echo do_shortcode('[shortcode_products_by_brand title="Sample brand products" per_page="12" columns="4" orderby="title" order="desc" brand="'. Sabai::_h($entity->getSlug()) .'" operator="IN"]') ?>
Obviously, it does not work :D May I ask your help? Thank you for your time, and sorry for my poor english and php skills :) | this should work
<?php echo do_shortcode('[shortcode_products_by_brand title="Promozioni" per_page="12" columns="4" orderby="title" order="desc" brand="'. $entity->getSlug() .'" operator="IN"]') ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, shortcode, slug"
} |
Adding `post_author` in php
So, I have following markup to show a shortcode:
<div class="my_edit_button">
<?php echo do_shortcode('[something]'); ?>
</div>
Then I am trying to make it so that the shortcode is only shown to post author by using the following:
return ($post->post_author == $current_user->ID);
But I am not sure how to incorporate both into one.
Could someone help me out?
Thank you very much! | Try this
<div class="my_edit_button">
<?php if ( $post->post_author == $current_user->ID ) {
echo do_shortcode('[something]');
}?>
</div> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
CNAME site attempts to load files over HTTP instead of HTTPS
The main site
loads fine. We have a CNAME pointing from the above domain to the following domain,
however, the page source shows HTTP for all the asset files. Even the Google Font which is hard coded as HTTPs
//fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic
is loaded over HTTP, why is that? | Issue turned out to be the "WordPress HTTPS" plugin. Disabling it allowed ptacfactoryparts.com to load asset files over HTTPS instead of HTTP. Not sure why it was overwriting the links. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "domain, ssl, privacy, dns, encryption"
} |
Add simple field column to the posts screen
I know that `manage_posts_columns` is the hook for managing the column in post screen.
I can add a column with following code,
// add new column hook
add_filter('manage_posts_columns', 'add_new_column_in_posts');
function add_new_column_in_posts($columns) {
$columns['premium'] = 'Premium';
return $columns;
}
My question is, how can I feed the `simple_field` value for that column? | Ref. < Just use the WP built in action called "manage_posts_custom_column" and in callback check for the correct column and add simple_field value with the function _simple_fields_value_ :
add_action( 'manage_posts_custom_column' , 'add_new_column_data_in_posts', 10, 2 );
function add_new_column_data_in_posts( $column, $post_id ) {
switch ( $column ) {
case 'premium' :
echo simple_fields_value("simple_field_slug", $post_id);
break;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, screen options, plugin simple fields"
} |
Get simple field value with post id
I can retrieve the `simple field value` by following function.
simple_fields_value("simple_field_slug")
But is it possible to get value by using a post id ? | The function second parameter is the "$post_id". Ref. <
simple_fields_value("simple_field_slug", $post_id) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "posts, plugin simple fields"
} |
How to store all featured images in a different folder?
I would like to store all featured images for my custom post type in a different directory/folder, & for all the other images used in the custom post type to be stored in the standard place. Is this possible? | there is a similar question here: Post type specific upload folder in 3.5
Just add an IF case whenever the wanted post type is the one you want to be in another folder, if not, return the directory given by the filter. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "post thumbnails"
} |
TwentyFifteen: How can it show a different color on every post page?
I have made a child theme of TwentyFifteen. Am trying to set on styles.css of the child theme a specific color on every page or post.
I tried somethin like that
.post-id-no.id .hentry,.site-footer {
background-color: #RGBColor !important;
}
But I didn't see any difference, its still white. What exactly am I doing wrong? | The CSS code syntax is not correct. For post and page specific CSS, you need to use something like this:
/* Replace x with post/page id and post with page and vice versa*/
.page-id-x .hentry,
.page-id-x .entry-footer {
background-color: #RGBColor !important;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "customization, css, theme twenty fifteen"
} |
How do I serve static content on same domain as WordPress
I have a portfolio site that I would also like to make a demo site for some of my client work. Basically, I would like to serve a subfolder statically along side the WordPress install. For instance, if I have ` that index file would be served directly from Apache rather than WordPress. I have root access to my server, just not sure how to implement this | If the files are static HTML, then you only need to be concerned with name collisions for the directory structure. And if you don't have anything in WordPress that generates /demo/subfolder/ you don't have to worry about ignoring it - it's already ignored.
I have a sandbox folder that I use for a similar purpose as you and haven't had to implement anything - It's ignored by WordPress already. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "directory"
} |
Images in Woocommerce Product Sidebar
there is an easy way to assign your custom image size to the mini-cart.php that is responsible for the cart widget. The code is on line 32:
$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image('new_cart_size'), $cart_item, $cart_item_key );
That works perfect. In a next step i wanted to assign my new_cart_size to the product sidebar that fetches the product_thumbnails, which are oversized for this purpose. I scanned the woocommerce folder, but i can't seem to find the file that is responsible for the woocommerce sidebar. Does anybody know the source file? regards theo | Open up that file (mini-cart.php) and edit line 40 where it contains
<?php echo $_product->get_image(); ?>
Change that to
<?php echo $_product->get_image( array( 150, 200 ) ); ?>
150 is the width and 200 is the height. Change it to whatever size you want.
After you have done that make sure to clear your cache and restart your browser as sometimes the mini cart gets cached. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "sidebar, woocommerce offtopic"
} |
"Edit" option for custom post types archive page
I have a custom post type archive page but I also need the user to be able to insert a bit of page text. I thought I could just use the_content() of the page but the edit link is gone from the admin menu for custom post types archive pages.
Is this something new and is there any way to enable it?
!admin bar | I'm not sure if I understand you correctly, but maybe this will help you.
If you're on CPT archive, then there is no "Edit" link, because it's archive and not a page... Archive is list of posts, so there is no single post to edit... Another example of archive page is when you're viewing search results or all posts from given year - there is nothing to edit in these views.
**What you can do/how would I do it?**
You can add new page and set its slug to the same value as CPT slug...
Let's say your CPT is 'Book' with slug 'book'. You can add normal page called 'Book' with slug 'book'.
CPT archive and single CPT has higher priority than single page in Rewrite Rules, so this page will be ignored by WP. But you can manually display it's content in `archive-book.php` template... | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "custom post types, custom post type archives"
} |
How do I add a class to all sidebars to let a Google Custom Search Engine know not to index the content?
I've replaced the WP search on my site with a Google CSE. Google has a nice feature that lets you specify that certain areas of the page should not be indexable, by adding a "nocontent" class to those sections. I need to add this class to all the sidebars.
I've tried adding a filter to register_sidebar, and the data is changed in the function, but the change that I make is not passed into the output.
add_action( 'register_sidebar', 'uft_add_nocontent_class' );
function uft_add_nocontent_class( $sidebar_info ) {
$sidebar_info['before_widget'] = str_replace('class="widget ','class="widget nocontent ',$sidebar_info['before_widget']);
return $sidebar_info;
}
I also tried this with an action with similar lack of success. Should I just modify the child theme, or is there another way to make the hook work? | If you want to add a class before each widget you should use the dynamic_sidebar_params filter. Another post explains this well. Here's the gist of it.
function uft_add_nocontent_class($params) {
$params[0]['before_widget'] = '<aside id="%1$s" class="widget %2$s nocontent">';
return $params;
}
add_filter('dynamic_sidebar_params', 'uft_add_nocontent_class');
Otherwise, go and edit your child theme files. If you don't have a lot of sidebars that's probably the easiest. You could also use some JavaScript to add the class to your selected sidebars. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, sidebar, register sidebar, google"
} |
Shorten the title length
So I'm using this filter in order to shorten the title:
function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();
if ( $length && is_numeric($length) ) {
$title = substr( $title, 0, $length );
}
if ( strlen($title)> 0 ) {
$title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
if ( $echo )
echo $title;
else
return $title;
}
}
and in my template:
<?php the_titlesmall('', '...', true, '50') ?>
This works like a charm.
However, this filter adds "..." to every post title, even if the post title is under "50" characters and it looks weird. How can I only add the "..." to the titles that are over "50" characters?
Thanks a lot! | Try this. First check if the original string length is less than or equal to passed in length, and if so, we ignore the `$after` parameter :
function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();
if( strlen($title) <= $length )
$after = '';
if ( $length && is_numeric($length) ) {
$title = substr( $title, 0, $length );
}
if ( strlen($title)> 0 ) {
$title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
if ( $echo )
echo $title;
else
return $title;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, get the title"
} |
used code below to allow Editor access to menus - but change permanent, how do I revert?
I have tried the code below to allow Editors to access menu settings. I then removed it from functions.php but the Editor access is still there so looks like this has made a permanent change!
Ayy ideas how I can roll this back (to remove editor access to Appearance).
Thanks
/**
* @var $roleObject WP_Role
*/
$roleObject = get_role( 'editor' );
if (!$roleObject->has_cap( 'edit_theme_options' ) ) {
$roleObject->add_cap( 'edit_theme_options' );
} | From WordPress Codex:
> Changing the capabilities of a role or user is persistent, meaning the added capability will stay in effect until explicitly revoked.
You might want to do something like:
$roleObject = get_role( 'editor' );
if ($roleObject->has_cap( 'edit_theme_options' ) ) {
$roleObject->remove_cap( 'edit_theme_options' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user roles, editor"
} |
How can I lock specific posts (cpt's) from editing by anyone other than ADMINS
To be 100% clear, this has nothing to do with the front end of the site.
I want to keep all users other than Admins from editing a few specific posts. The posts are a CPT that the editors/admins can create and modify, but 3 of them need to be locked so that only admins can CRUD them.
Any ideas? | Use the `map_meta_cap` filter to conditionally prevent users who cannot `manage_options` (i.e. administrators) from editing/deleting certain posts:
function wpse_188368_map_meta_cap( $caps, $cap, $user_ID, $args ) {
if ( in_array( $cap, array( 'delete_post', 'edit_post' ) ) && $args && ! current_user_can( 'manage_options' ) /** Only proceed for non-administrators */ ) {
$post_id = $args[0];
if ( in_array( $post_id, array( 1, 2, 3 /* ID's of locked posts */ ) ) )
$caps[] = 'not_allowed'; // Add a required capability they won't have - current_user_can() will then subsequently return false
}
return $caps;
}
add_filter( 'map_meta_cap', 'wpse_188368_map_meta_cap', 10, 4 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, content restriction"
} |
How can I have user registration verify a whether a new user is listed in a table of pre-approved users?
I only want existing customers to be able to register. I have a table of valid customers, so I just need a hook to interrupt the registration process with "Sorry, an account with that number does not exist." | There is a `registration_errors` filter, which native errors go through and which allows you to provide your own. Returning filled in `WP_Error` object in this filter will smoothly prevent user from being created.
The one downside is that that filter is not passed much additional data — only login and email. You will probably have to fish your custom data out of global `$_POST` state for the check. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "user registration"
} |
Delete Associated Media Upon Page / Post Deletion
I found this code.
But not work for me. Where to insert the code? I try
wp-content/theme/mytheme/functions.php - not work.
wp-includes/post.php - not work.
wp-includes/functions.php - not work.
And I make plugin (but this the first), not work. Plugin download.
My Wordpress version is 4.2.2.
Big Thanks, and sorry I'm rookie! | Just for clarity: borrowing from this answer, add the following to your theme's `functions.php`:
function wpse_188427_delete_post_media( $post_id ) {
$attachments = get_posts(
array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id,
)
);
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID );
}
}
add_action( 'before_delete_post', 'wpse_188427_delete_post_media' );
// Uncomment the following line if you also want to delete media when the post is trashed
// add_action( 'wp_trash_post', 'wpse_188427_delete_post_media' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, media library, customization"
} |
Save values generated via API as custom meta fields
I'm using the IMDB Connecter plugin to grab meta data for movies and I'm wondering if I can save some of the information it generates as custom meta data.
Basically, I want to be able to save the "Language" and "Actors" information generated by the plugin in meta fields with the same name so that posts are searchable using these values.
This is how I currently output the data in my single.php file;
$imdb = get_field('imdb_id'); // IMDB movie ID is saved as a custom meta value
$imdbInfo = get_imdb_connector_movie($imdb);
$actors = $imdbInfo['actors']; // Gets an array of actor names
$language = $imdbInfo['languages']; // Gets an array of languages
Is it possible to save these values as custom meta?
Any nudge in the right direction would be most appreciated | Use the `wp_insert_post` hook to run when a post is saved:
function wpse_188435_save_movie_data( $post_id ) {
if ( $imdb = get_field( 'imdb_id', $post_id ) ) {
if ( $imdbInfo = get_imdb_connector_movie( $imdb ) ) {
if ( isset( $imdbInfo['actors'] ) )
update_post_meta( $post_id, 'actors', $imdbInfo['actors'] );
if ( isset( $imdbInfo['languages'] ) )
update_post_meta( $post_id, 'languages', $imdbInfo['languages'] );
}
}
}
add_action( 'wp_insert_post', 'wpse_188435_save_movie_data', 50 /* Late priority, will ensure ACF has saved all data first */ ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, post meta"
} |
There's an image named g.gif somewhere in my WordPress site
I am looking for this pixel which appears full width in my mobile site, so I want to remove it.
!enter image description here
Image URL: `
Well, I can see it's g.gif and assume it has something to do with Wordpress keeping track of the blog, but I want to grab it and edit its CSS style. The thing is it doesn't show up in the page source or when I search my theme source code.
What is this `g.gif` in Wordpress about? Any info about this would be very helpful. Thanks. | That's the Jetpack Stats image, it's necessary to track the stats. You can disable it by disabling Jetpack Stats but it shouldn't be full width, that will be a CSS problem | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development, css, front end"
} |
Add a label to the editor?
I'm working on a custom post type. I have the editor enabled but the content that will go in that box is secondary and it isn't clear what should be typed there so I want to add a label for the editor. How do I do that? | After hacking around, this is the solution I came up with:
At the top of `functions.php` I have the following line:
add_action('admin_footer', 'add_title_to_editor');
Just thrown in the middle of `functions.php` I have the following function:
function add_title_to_editor() {
global $post;
if (get_post_type($post) == 'my_custom_post_type') : ?>
<script> jQuery('<h3>Optional Additional Information</h3>').insertBefore('#postdivrich'); </script>
<? endif;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, post editor"
} |
How to customize a site hosted on wordpress.com locally
I have a website on wordpress.com. Is there a way to download it to my localhost, customize it and then upload it back to wordpress.com?
Thanks | WordPress com doesn't allow you to upload any customization, other than CSS via their paid customization feature.
Notably you can _download_ WordPress com themes (link is available in sidebar of theme info page) and use them in self hosted installation. However, given that WP com doesn't provide source for much of its environment, it's unlikely that you would be able to replicate features and customization process precisely.
In a nutshell you need to go with self hosted installation for real freedom of customization. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, localhost, wordpress.com hosting"
} |
How to protect htaccess so it can't be overwritten?
I'm having a problem where Wordpress is periodically and randomly destroying the `.htaccess` file and setting it to zero bytes. When it does this, the site of course breaks until permalinks are manually flushed and `.htaccess` is rewritten. How can I protect the `.htaccess` file completely (total read only) or otherwise prevent Wordpress from ever automatically overwriting it? My FTP client won't allow me to set the permissions lower than 644 so I can't make it true read only. | Fixed this by changing permission on .htaccess to 444 from CPanel's file manager. For some reason my FTP client - even though logged in as the same CPanel user - could not make the change and the file would always revert back to 644. Cpanel had no such problem at all. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, htaccess"
} |
jQuery(selector) vs. $(selector)
Why is it that in wp-admin/js/updates.js (in Wordpress 4.2) `$(selector)` is used but in wp-admin/incldes/file.php `jQuery(selector)` is used? Is there a particular reason for this or is it just an oversight on the part of the development team? | This is because of jQuery noConflict wrappers. It is certainly not an oversight by WordPress developers; but rather, a great little way to ensure we (developers) can hook our own javascript files or libraries without conflicting with other javascript code.
Be sure to read the Codex on jQuery noConflict Wrappers.
The usage pretty much depends on your intentions; and when you want the script to be executed (when DOM is fully constructed; as opposed to immediately).
It's all explained very well on the codex page linked above. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
Wordpress wp_loaded action hook
I am using Shortcode exec php plugin and putting PHP code in a post via Wordpress Posts panel.
add_action( 'wp_loaded', 'echoFunction');
function echoFunction(){
echo "someText";
}
Why doesn't this work? and how do I make it work? | `wp_loaded` is called long, long before the post content is fetched. Put that code into a plugin.
Also, you shouldn't `echo` anything that early. The HTTP headers aren't sent yet on `wp_loaded`, so you will get the _Headers already sent_ error, and your user authentication will not work: you cannot log in anymore. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "hooks, actions"
} |
View WordPress page template usage (or unused)
When I create a new page within WordPress, I have the option of specifying which template to use from my theme (from a dropdown list on the right-hand side of the interface).
I need to find which of the available templates are unused, so that I can delete them.
How is this done please?
WP version is 4.2.2 | What you need to do is compare the values of the meta field `_wp_page_template`, which contains the page template selected for a single page with the available page templates.
For this you need to construct an array of used templates, because you want the templates used by all the pages, similar as shown here:
* Return all custom meta data for one custom post type
Use `array_unique` to get unique values.
Then you need to get the available page templates, as shown here:
* get page templates
Last but not least, you can use `array_diff` to compare the arrays of used and available templates, which subsequently gives you the unused templates. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 7,
"tags": "templates, themes"
} |
Theme twentythirteen widget area clearfix
I've put quite a lot of stuff on my widget area and now if the post is not long enough my widget area spills in the footer area as shown on the image below:
!enter image description here
Now, I'm not a designer, but I have been googling and trying to find out where to exactly place the needed CSS (I found I should use some kind of clearfix solution).
I tried adding `<div style="clear:both;"></div>` in several places (before the footer, before widgets last closing div, and few random ones), but to no luck.
So, a kind request for help to someone who has maybe dealt with this exact issue already.
My post example is: nikola-breznjak | There are many approaches to this. This is because the `position: absolute` on the sidebar-container is making it overlap over the footer.
Try this CSS to override. This is a static solution:
body.single .hentry // Selects the single posts
{
min-height: 2000px; // Set this according to the height of the sidebar
}
This one is a better solution:
To work with only large device width because the below CSS will restructure mobile device elements, To avoid that we can set `media-queries`
@media (min-width: 992px) {
#main {
overflow: hidden;
}
#primary.content-area {
float: left;
}
.site-main .sidebar-container {
position: relative;
float: right;
width: 25%;
height: auto;
padding: 0 15px;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, theme twenty thirteen"
} |
Is there a action hook for the "Empty Trash" button?
I would like to run a function when the user clicks the "Empty Trash" button for posts. Something like:
add_action('empty_trash','myFunction');
function myFunction(){
// My code
} | I don't think there exist one, but you could create your own, `wpse_empty_trash`, with something like this:
/**
* Add a custom hook 'wpse_empty_trash'
*/
add_action( 'load-edit.php', function()
{
add_action( 'before_delete_post', function ( $post_id )
{
if (
'trash' === get_post_status( $post_id )
&& filter_input( INPUT_GET, 'delete_all' )
&& 1 === did_action( 'before_delete_post ' )
)
do_action( 'wpse_empty_trash' );
} );
} );
Then you can use it with your code. Example:
add_action( 'wpse_empty_trash', 'myFunction' );
function myFunction() {
// My code
}
Hopefully you can adjust this to your needs. | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 16,
"tags": "posts, actions, customization"
} |
If post author ID is..show that
i would like to display a custom adrotate Group everytime if a user ID matches the script. So i created:
if (is_author('1'))
{
echo adrotate_group(8);
}
elseif (is_author('70'))
{
echo adrotate_group(8);
}
elseif (is_author(''))
{
echo adrotate_group(8);
}
This aint working, i see no output in my single php. Can somebody tell me what i'm doing wrong? | The function `is_author()` is used to check if you are on the archive page for the specified author. So as your code is in `single.php` this will never be true.
From the docs
> This Conditional Tag checks if an Author archive page is being displayed. This is a boolean function, meaning it returns either TRUE or FALSE.
<
To get the author ID you could use:
$author_id = get_post_field('post_author', get_the_ID()); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "author"
} |
Build a Boat Form Plugin
I am putting together a quote for a custom wordpress website for a client that specializes in the Pontoon business. I am fairly familiar with Wordpress, HTML, CSS, and a very basic JS. The client requested a custom build a boat plugin that will give users the option to spec out their boats and then populate into a wishlist that can be emailed to a dealer or printed out.
Initially I was just thinking of doing this all in a form myself or hiring someone who can do this who is experienced with Javascript (I am not) because I don't want to waste time trying to muck this together.
Any ideas, suggestions or plugins that I might be able to use to achieve this without hiring someone?
Thanks! | Your best option is to buy the Gravity Forms plugin in order to accomplish this.
<
Yes, there are other form plugin options such as Contact Form 7 but I can assure you (and everyone here) that the Gravity Forms plugin is hands down the option for this task. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, forms"
} |
How to store the_title() into a variable to reutrn the value, not just echo it
I have a loop, and need to pass one more argument through it. I need to get the current page's single post title, and then use that as the value.
I tried going about it like this:
$tagz = the_title();
$args = array(
'post_type' => 'product',
'posts_per_page' => 5,
'product_tag' => "{$tagz}" );
and the `$tagz` variable just automatically echo's the current post title. I found out through this resource this resource that `the_title()` merely echos the title and never returns it, making the `$tagz` variable null.
How can I use the current posts title as an argument? I am really stumped!! | You can use `get_the_title()` to return the current post title in the loop. | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 4,
"tags": "php, functions, array, variables"
} |
How to reference a theme image in a stylesheet?
I have a global element as part of my theme and I need to reference and image as a background image. I need the URL to the image. I assume that it's bad practice to hard-code the URL and that the URL needs to be relative to the theme location. What is the recommended way of referencing an image within a stylesheet? | It depends on your image and stylesheet location.
But this is the syntax:
.theme-image {
background-image: url('../images/header-img.jpg');
}
The above code is for the structure
wp-content
- themes
- your-theme
- images
- header-img.jpg
- css
- style.css
You are making the browser come one directory before and search for images directory. | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 7,
"tags": "images, css, urls"
} |
How to add custom column to Custom post page list?
!enter image description here
Image should explain what I am trying to accomplish. I have no idea how to do this, is anyone familiar with this sort of work?
Custom event date will be a custom event meta box value that is part of the post type. I want the custom meta box to have a column like the taxonomy event essentials(as seen in the picture)
Thanks. | There is the hook `manage_${post_type}_posts_columns` which can be used to do just that.
Basic example:
function wpse188743_events_cpt_columns( $columns ) {
$new_columns = array(
'event_date' => __( 'Event Date', 'textdomain' ),
);
return array_merge( $columns, $new_columns );
}
add_filter( 'manage_events_posts_columns' , 'wpse188743_events_cpt_columns' );
To fill the column with the related content you additionally have to make use of the `manage_posts_custom_column` hook.
Basic example:
function wpse188743_event_column_data( $column, $post_id ) {
switch ( $column ) {
case 'event_date' :
echo 'event date logic goes here';
break;
}
}
add_action( 'manage_posts_custom_column' , 'wpse188743_event_column_data', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, customization"
} |
What effect does the_content filter have on performance?
This is general question but lets say I have a function and on a specific page I want to display a table.
The function only applies to one page on my site but every post/page will run this function (and skip it when it 'realises' it isn't the right page).
**Would it be better** , from a performance point of view, **to use a page template** for this specific page **instead of this filter**? Or is this negligible and not worth worrying over.
> Hopefully you get the gist of what I'm asking, I realise there are other factors like how my table (or whatever I'm including) is processed but lets ignore that for the sake of this question.
add_filter('the_content', 'str_load_table');
function str_load_table($content) {
if(is_page('my-table')) {
$my_content = 'pretend this is a table';
$content = $content . $my_content
}
return $content;
} | The difference would be negligible.
The `the_content` filter is fired regardless of whether you use it or not because WordPress uses it for other things. So the only thing that would be performance related would be the complexity of your filter function.
But since you'd probably be doing the same level of complexity in a template or in the filter function, there's no real difference between the two.
I would say that you'd be better using the filter if you want the table to be part of the main content area. Then you don't have to worry as much about how/what styles are applied. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "filters, performance, the content"
} |
Save the outputted image into the Media Library, with a different filename and extension
For example, I have this _"/image.php"_ file in my _"/theme-directory"_ :
header ('Content-Type: image/png');
$im = @imagecreatetruecolor(120, 20)
or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
imagepng($im);
imagedestroy($im);
That code will create a new GD image stream and output an image.
How can I save the outputted image into the Media Library, with a different filename and extension like _"filename.png"_? | I found that there's a predefined WordPress function to upload a file into the Media Library but it's only working asynchronously with a `<form>` element and a `$_FILES` array.
Second, I also found that there's a second `imagepng()` parameter filename which is the path where you want to save the file. I tried to save it to a WordPress uploads' path such `"/wp-content/uploads/$yyyy/$dd/filename.png"` but it's not showing in the Media Library mostly because there's no record of it from the database.
So, the best thing you could do is to save the image in the _"/images"_ or _"/img"_ folder of your theme directory and use the path of that directory:
$source = get_template_directory() . "/images/filename.png";
imagepng($im, $source); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, theme development, images, uploads"
} |
Always show the widget title in a wordpress widget
I'm using the default category widget to show my category list in sidebar.
The problem is when I select some category to visit the corresponding category page [ex: football], the widget title [which is: My Category] disappears & shows the category title there [in this case: football]. I don't want that.
I want my widget to always show the widget title whether I select a category or not. I don't know if I explained it correctly or not! | That is not native behavior of it.
If you check the source of `WP_Widget_Categories`
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Categories' ) : $instance['title'], $instance, $this->id_base );
The title comes exclusively from the value saved in instance (or default if not). There is no logic to tie it in with current context.
Something is changing that behavior, some possibilities that come to mind:
* you might have something override native widget
* some code might be using `widget_title`, possibly incorrectly, to override
* some JS code on front end might be changing title | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets"
} |
getExcerpt: Make ellipsis appear only if character limit is reached
I have a function called getExcerpt that displays the first 140 characters of an excerpt and after that, an ellipsis appears. The call in my template is like this:
<?php echo get_excerpt(140); ?>
and my code in functions.php is:
function get_excerpt($count){
$permalink = get_permalink($post->ID);
$excerpt = get_the_excerpt();
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, $count);
$excerpt = $excerpt.'...';
return $excerpt;
}
Works. However, if the excerpt is actually less than 140 chars, you still get the ellipsis. I only want it to appear if I have 140 or more chars. What variable do I have to put in to get that? | You can check to see if the length of the excerpt is longer than the max count.
if(strlen($excerpt) > $count){
$excerpt = substr($excerpt, 0, $count) . '…';
}
`…` is the correct ellipsis character to use. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, tags, excerpt, variables"
} |
If else statement based on referral URL
I am trying to display content in a custom template based on referral URL. I put a link in my footer called < and image2.gif shows still when I click it and go to the page. I need image1.gif to show if there is traffic coming from a domain that ends with ?ref=special. How can I do this and what am I missing?
<?php
$ref1 = parse_url(wp_get_referer()); //getting the referring URL
if($ref1["path"]=='/?ref=special/')
:?>
<div id="featured_image_small" style="background: url('<?php echo esc_url( home_url( '/wp-content/uploads/2015/05/image1.gif' ) ); ?>') no-repeat scroll 0 0 transparent; background-size:cover;">
<?php else: ?>
<div id="featured_image_small" style="background: url('<?php echo esc_url( home_url( '/wp-content/uploads/2015/04/image2.jpg' ) ); ?>') no-repeat scroll 0 0 transparent; background-size:cover;">
<?php endif ;?> | The following worked for me.
functions.php
function add_query_vars_filter( $vars ){
$vars[] = "ref";
return $vars;
}
custom template
<?php
if($_GET['ref'] == 'special')
:?>
//do something
<?php else: ?>
//do something
<?php endif ;?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, conditional content"
} |
Featured Image not displaying in a page
I put featured image in a page but it's not showing up when I view the page. But in thumbnails its showing up. How to fix this?
here < | In your `page.php` or `single.php` whichever is concerned here.
After the post title code, add this:
<?php the_post_thumbnail(); ?>
Additional modification can be found in Codex | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, post thumbnails"
} |
wp_list _table You do not have sufficient permissions to access this page error
I'm trying to develop a plugin which uses custom post and custom database table with class that extends the wp_list_table to show the data from a database table. But everytime I try to do something with the record it just gives me an error that I don't have sufficient permissions. I'm trying to do the rollover edit and delete and bulk action delete and also the search box. But when I click on the button it always gives me this error and I don't know why. Any suggestions? | I figured it out. I just needed to change the form method from get to post and I don't have an error that I don't have sufficient permissions anymore. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors"
} |
Insert DIV container below 1st search result
How can I insert a DIV just below the first search result (between result #1 and #2)? | You should be able to do that with:
/**
* Setup a custom hook before the second post on the search page
*/
add_action( 'the_post', function( $post, \WP_Query $q )
{
if( $q->is_search() && $q->is_main_query() && 2 === $q->current_post )
{
do_action( 'wpse_before_second_post_in_search' );
}
}, 10, 2 );
/**
* Inject a Div after the first post on the search page
*/
add_action( 'wpse_before_second_post_in_search', function()
{
echo '<div>My Injected Div</div>';
} );
where we've introduced the custom `wpse_before_second_post_in_search` hook, that you can now play with as you need. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 6,
"tags": "search"
} |
How to move menu next to left of the search box?
I use Woocommerce plugin and StoreFront theme to build my demo website at <
I want to move the current menu to another place - on the left next to the search box on the top right corner.
How can I do that?
p.s. The `header.php` file can be viewed here (be updated soon)
!enter image description here | It's a simple solution of
1. Setting the menu position to `Secondary navigation`, AND `Handheld`
2. Setting an empty menu for for position `Primary navigation`.
In my screenshot I haven't removed the primary navigation though.
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "customization, menus"
} |
how to get custom admin submenu( custom post type ) item to highlight when its active
I have a menu item added using add_menu_page say **ABC**.
I have added a custom post_type **product** as a submenu item under **ABC** I created it with this code
add_submenu_page(
'abc',
'Products',
'Products',
'manage_options',
'edit.php?post_type=product'
);
How to highlight submenu_page **product** if selected in admin menu? | Solved the above issue by putting " **show_in_menu** " parameter to **false** while registering the Custom-Post-Type **product**. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "sub menu"
} |
how could I load a different template part by page
I would like to use `get_template_part();` to load a different template parts on different pages. so on the home page it loads `get_template_part( 'content', 'home' );` and on the blog page it would load `get_template_part( 'content', 'blog' );`.
I'm new to PHP but should there be a conditional tag that I could use to load things by page? | For question as stated it would be easiest to retrieve page's slug and pass it as second argument:
get_template_part( 'content', get_post_field( 'post_name', get_post() ) );
Note that you would want to have generic `content.php` for pages that don't have dedicated template (if any). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, templates, page template, conditional tags, get template part"
} |
How can I edit submenu headings using wp_nav_menu walker?
The whole world of menu walkers is still murky waters for me, so I'm hoping someone might be able to help me here.
I'm able to produce an auto-generated list of menu items on my page using the `wp_nav_menu` function in Wordpress. It currently looks like this:
wp_nav_menu(array(
'theme_location' => 'main-menu',
'start_in' => $post->ID,
'container' => false,
'items_wrap' => '<div class="page-categories"><ul>%3$s</ul></div>'
));
!enter image description here
What I'd like to be able to do, is change the sub-menu headings of Face, Ear and Eye to read 'Related Face procedures', 'Related Ear procedures' etc.
It's important that the actual menu items themselves are still generated dynamically, and not hard-coded. Can this be done using a walker? | Here's one way to do it with the help of the menu CSS classes:
For the menu item that you want to modify the label of, add the `wpse_menu` class to it:
!menu modifictation
This is supported with:
/**
* Modify the title of menu items that contain the 'wpse_menu' class.
* We restrict this to the primary menu.
*/
add_filter( 'wp_nav_menu_objects', function( $items, $args )
{
if( isset( $args->theme_location ) && 'primary' === $args->theme_location )
{
foreach( $items as &$item )
{
if( in_array( 'wpse_menu', $item->classes ) )
$item->title = __( ' Related ' ) . $item->title . __( ' products ' );
}
}
return $items;
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, walker"
} |
wp_query - show pages that have parent defined
Can I achieve this with wp_query? I only want to get pages that have parent selected.
I'm using JSON API plugin and need to make a http request - would this be possible with url wp query also? For example, I'm doing requests like this: ` and they work perfectly fine.
Perhaps using something like `post_parent__not_in => array()` (but in a url-like fashion?)
A better question could be: How to use WP Query arguments that accept arrays within url?
Thanks for any help | To get only child pages (pages that have parent selected), you can use this query:
And that should also give you the answer for your second question, I guess ;)
If you want to pass `array(1=>'foo', 2=>'bar')` as param called `my_array`, you should use this query:
...&my_array[1]=foo&my_array[2]=bar | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, plugin json api"
} |
dummy category, include .php file
Hello i know this is a dumb question but.... please help me
i've been across google for this and found serval solutions but none that worked for me. i'm trying to use the PHPExcel lib in a plugin i'm making but i can't get wordpress to find the file.
if (! file_exists(SPEE_PLUGIN_DIR . '/lib/PHPExcel.php') ) { echo "nope :("; }
if (! file_exists(CHECKIN_PLUGIN_DIR . '/lib/PHPExcel.php') ) { echo "nope"; }
if(file_exists(plugins_url( '/lib/PHPExcel.php' , __FILE__ ))) {echo "heyo";}
file_exists(dirname( __FILE__ ). '/lib/PHPExcel.php');
i've danced around the 2 commands above but both echo's out meaning they can't find the file. the path is correct, and written in the same capitals as the folder and the file's name. so what am i doing wrong? in advance THANKS! | Not sure it works now, used it months ago. But you can give a try please
file_exists(dirname( __FILE__ ). '/lib/PHPExcel.php'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
how to hide or disable some part in specify page
i want from my footer.php file some part like `<div class="form">----------</div>` this part will be visible all page but not show in home page and few other other. i think it is possible via use php condition.
i read is_home, and is_front_page conditional problem but that way not also work
<?php if ( !is_home() && !is_front_page() ) {
echo "Hello World";
} else {
echo "Else World";
}
?>
for all page even home page i am getting Hello World. i tried `<?php if ( ( is_page('home')) ) {` also `<?php if ( ( is_home() || is_front_page() ) ) {` also `<?php if(is_page(248)){`
not work. | You want to "reverse" your logic, in a sense. You need "not (home or front)", not "not home and not front". For example:
// var_dump(is_home(),is_front_page(),(is_home() || is_front_page()),!(is_home() || is_front_page())); // debug
if ( !(is_home() || is_front_page()) ) {
echo "Hello World";
} else {
echo "Else World";
}
An easier, more readable way to write the same thing is:
if ( is_home() || is_front_page() ) {
echo "Else World";
} else {
echo "Hello World";
}
Please be aware that the`is_home()` and `is_front_page()` functions can be confusing. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Remove from Google Tags with less than 2 posts
I would like to write some code that remove from google the tag pages which contains only a few posts.
I can do it by modifying the meta tag and the HTTP response header to 410. But how can I implement that in Wordpress? | You can use < to set the response header, and you just need to find the lines in the theme's header.php. Unfortunately, these items _are_ set by header.php so you will have to run the code on all pages of a traditional theme, but I would do something in the header.php near where the meta is currently being set like
if ( is_tag() ){
// check for how many posts are in the loop here and save as number
}
if (is_tag() && $number < 3){
//change meta here, change http response code here
}
else{
// normal meta here, normal response code here
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, tags"
} |
Open media box library from link
I am developing a plugin in which I want to open media library box after clicking on a link from Admin Panel just like we do for Choose featured image.
<a href="#">Choose Image</a>
After clicking on Choose Image I want that media library box displayed in thickbox.
Thanks | By enququing an JS file we can do like this:
<img src="#" id="img-src">
<a href="#" id="img-upload">Add Image</a>
**Content of JS file**
jQuery(document).ready(function(e){
e.preventDefault();
jQeury('#img-upload').click(function(){
var upload = wp.media({
title:'Choose Image', //Title for Media Box
multiple:false //For limiting multiple image
})
.on('select', function(){
var select = upload.state().get('selection');
var attach = select.first().toJSON();
console.log(attach.id); //the attachment id of image
console.log(attach.url); //url of image
jQuery('img#img-upload').attr('src',attach.url);
})
.open();
});
});
Like this we can have it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, media library"
} |
Wordpress archives in header -necessary?
I just had a look at my source code and found that at the very beginning there's this really long list of archives. I haven't seen this on other blogs:
<link rel="pingback" href=" />
<link rel='archives' title='May 2015' href=' />
<link rel='archives' title='April 2015' href=' />
(.... lots more ...)
<link rel='archives' title='November 2011' href=' />
It's probably the code in the second line in my header.php that's causing this:
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php wp_get_archives('type=monthly&format=link'); ?>
**My question is:**
What is the first line doing?
Can I remove both lines from my header?
If I remove it will it have any negative effects (e.g. Google crawling or SEO)?
Thank you! :) | See this WordPress support page for an explanation of what the first line does.
The second line you can remove and it will get rid of those archive entries from the header output HTML.
For the SEO impact, search engines should be just fine as long as you have a site map for your posts. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "archives, wp blog header.php"
} |
How does wordpress calculate the page depth?
When using functions such as `wp_list_pages()`, WordPress gives you the `depth` option. How is it calculated?
Is it stored somewhere in the DB? (I couldn't find it).
Or is it calculated in a loop checking post parents?
What's strange is that `wp_list_pages()` offer the parameter `depth` but that function is based of `get_pages()` which doesn't have that same option available. | Ok, lets break it down, all the links are going to be to the source code.
`wp_list_pages()` only uses `get_pages()` to (sic!) get pages, `walk_page_tree()` does the hierarchical structuring inside it. The further course of the process goes `Walker_Page` \- and the generic `Walker` of course -, unless a custom walker is used. Inside `walk_page_tree()` you will see, the walkers `walk` method is called, which subsequently calls the `display_element` method. Mainly in the `display_element`, but also in the `walk`, method you find the handling of the depth.
To make it short: the depth is handled by iterating, `display_element` calls itself until the end or the given `depth` parameter. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "pages, wp list pages"
} |
get_page_template returning nothing
I run this code in
`front-page.php`
as well in
`category-foo.php`
<?php echo is_page_template( 'front-page.php' ) ? "yes" : "no" ?>
and get both times "no" printed
i tried as well
<?php echo get_page_template() ?>
returning nothing.
I as well tried
<?php echo get_category_template() ?>
What I want to know, is in which main template file I am. E.g.
I want to call from `header.php`
<?php if ( currFilename(__FILE__) != "front-page" ) : ?>
<div>Fancy slogan</div>
<?php endif; ?>
which obviously does not work this way.
< | Have you tried `is_front_page()`? It should do what you're looking to do.
Unless you've set up front-page.php with the Page Template commented header syntax that identifies the file is a Page Template, I don't think you can use the `is_page_template()` or `get_page_template()` functions.
As for the category page, if you are loading category-foo.php, then aren't you already aware of what category template you are on and therefore do not need a conditional? Maybe I don't understand the context of the second part to the question. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, page template, code"
} |
Protecting work on client's web host
I am taking on a freelance job making modifications to a client's already existing website/Wordpress theme. What is the best way to work on the client's current web host without putting myself at risk that the client might lock me out of the server and have all the code I've done before paying? Is it possible to create a child theme that points to files on my own server? | I would get a copy of the files and then work locally using VVV, MAMP or whatever your tool of choice is. WP_Engine allows for git deploys so you could work locally and use git for version control and back up as well as deploy the changes as needed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, child theme"
} |
Remove parent theme action in child
I'm creating a child theme from Storefront.
Now I want to remove these action in child theme
add_action( 'woocommerce_before_shop_loop','storefront_sorting_wrapper',9 );
by this function:
add_action( 'after_setup_theme','remove_action', 100 );
function remove_action() {
remove_action( 'init', 'woocommerce_before_shop_loop');
}
but it doesn't work! | For removing an action hook you should use the same action name, callback name and the priority that was used to add a action in parent theme. And register it on `init`
add_action( 'init', 'remove_my_action');
function remove_my_action() {
remove_action( 'woocommerce_before_shop_loop','storefront_sorting_wrapper',9 );
}
Read about remove_action | stackexchange-wordpress | {
"answer_score": 30,
"question_score": 18,
"tags": "actions, child theme"
} |
How do I make a page the landing page?
On my website, I have made a new page which I want to set as the homepage. How do I make this page the landing page? Please guide me.
Thank you. | Log in to your Admin Panel -> Settings -> Reading ->
and follow this image :
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "homepage"
} |
Widget stuck at particular point when dragging to bottom
This is weird, but when I try to drag a widget to the bottom of sidebar it stuck in the middle, if I hold the dragging and drag it back to top it works but I can't drag it bellow that particular point.
Any help would be appreciated!
**Edit**
I recorded a video of what's going on, here it is: < Also, I didn't tell before, I am using Jetpack plugin for widgets visibility on certain pages etc. | That's a bug of WordPress core: #32094
Will be fixed in 4.2.3 version of WordPress and patch is available here: 32094.patch | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, wp admin, drag drop"
} |
Wordpress 4 invalid username special charachters issue
I have some danish users that uses special chars like æøå and they can't log in to my wordpress blog. I tried on a fresh install on 4.2.2 and on 4.1.5 and it did not work, for example Andrew Schønnemann with a simple password and it did not work, got message `ERROR: Invalid username. Lost your password?`. But with user `Andrew Schonnemann` works fine, what could be the issue? | Found the answer, created the following function:
function wscu_sanitize_user ($username, $raw_username, $strict) {
$username = wp_strip_all_tags ($raw_username);
return $username;
}
add_filter ('sanitize_user', 'wscu_sanitize_user', 10, 3); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, login, wp login form, htmlspecialchars decode"
} |
Overriding $wp_query on a template
What would be the **disadvantages/problems** of overriding a global variable, in this case the $wp_query?
Example in template **archive-books.php** :
get_header();
global $wp_query;
$wp_query = new WP_Query( 'post_per_page=6&post_type=books' ); | You are interfering with the main query/loop, which is **bad** \- there is nothing more to say.
You can do a _custom_ loop, see the codex article The Loop to start with, or use the `pre_get_posts` hook, if you want to do something other then the usual behaviour.
If you need to toy with `$wp_query`, for example to fix the pagination on custom loops, then restore it afterwards. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
How to get the Author type Label Language
I am working on a plugin and I need to have the word 'Author' appear in whatever language is set in the wordpress settings.
I have achieved this for the words: Posts and Pages using this code:
$post_type = get_post_type_object( 'page' );
$postTitle = $post_type->label;
How can this be done to get the label for 'Author'? I know that author is not a post type, so how can this be achieved? THANKS! :D | I suggest you take a look at: <
You should probably just use a get_text function such as $author = __('Author'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "author, multi language, labels"
} |
what is the point of telling add_filter how many parameters you want passed to the function?
In wp-includes/plugin.php (apply_filters) there's this:
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) ){
$args[1] = $value;
$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));
}
So if you do 9999 the function will get past more arguments than it needs? How is that a problem? If you don't need the arguments don't put them in the function declaration. Passing more arguments to a function that it's declaration would lead one to believe it accepts doesn't even cause a PHP Notice and is in fact what makes func_get_args() a useful function to use.
Is my reasoning wrong or is there a reason you wouldn't want to tell the function to pass 9999 variables to it? | The reason is that you can register native PHP functions as callbacks. Passing more parameters to them then they expect will raise a warning.
Imagine a filter that can pass 6 parameters and `trim()` as callback. PHP would now raise an error:
> Warning: Wrong parameter count for trim() in …
Some custom callbacks might also change their behavior depending on the amount of passed arguments. That’s surely not good code, but such code exists, and it would break if WP would change its current behavior now. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, filters"
} |
Wordpress search seems to look into permalink (which is bad)
It looks like when you search for the domain name in the wordpress search box, you get all your content listed because the domain name is in each permalink. I've tried many things, but it seems to be "harcoded". Is it normal ? How can I get this work 'normally' ?
thx for your time ! | When we try searching for _example.tld_ , then the default search query looks into the post _title_ and _content_ with:
... (wp_posts.post_title LIKE '%example.tld%')
OR (wp_posts.post_content LIKE '%example.tld%') ...
When we add an attachment or a local link, into the post content, we normally get the full url, for example:
so I would think that you're just picking up those in your search.
Try for example to create a post with the title _Test_ but without any post content and see if it shows up in your search results. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, search"
} |
WP Admin Bar - Get current theme name as custom menu title
I wish to echo the current theme in text in my WP Admin Bar sub menu.
How would I go about display a snippet of PHP inside the `'title' => 'php snippet here',` ?
< <
$theme_name = get_current_theme();
echo $theme_name; | First thing `get_current_theme()` is deprecated since version 3.4 you need to use `wp get theme()` to get the current theme name.
And about add_menu() you can only use it at action hook `admin_bar_menu` as codex say about it:
> This is not a function. It is a method of the $wp_admin_bar global (an instance of WP_Admin_Bar), which may not exist except during the 'admin_bar_menu' hook.
Working example
function foo_test_menu() {
global $wp_admin_bar;
$current_theme = wp_get_theme();
$wp_admin_bar->add_menu( array(
'id' => 'your_menu_id',
'title' => $current_theme->get('Name')
) );
}
add_action('admin_bar_menu', 'foo_test_menu'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, menus, multisite, admin menu"
} |
How to display the number of posts in a category using WP Query
Just a quick one but I am stuck in doing this. I am running a WP_Query for a category and and want to know how to display the number of posts in a category using WP Query!
This is the start of my WP_query but how to I just simply echo out the number of posts in this category?! It is driving me mad!
<?php
$args = array(
'cat' => 33,
'posts_per_page' => 500,
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) :?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
Thanks! | You can use the `found_posts` property, which is the **total** number posts for the current query:
echo $the_query->found_posts; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query"
} |
Capturing /page-name/[0-99999] in both template and number
Apologies if this has been answered already - I have singularly failed to word my question in a way that Google can help.
I'm trying to create a page that acts as a base URL for a range of items with numbers - those items won't have pages, but rather than
/page-name/?id=[0-99999]
I'd like to create
/page-name/[0-99999]
Capturing the ID number in variable form and forcing all instances with that 'page-name' to be handled by a single template. I've seen WooCommerce do something like this, and am currently searching the codebase to try and figure it out, but any pointers would be appreciated. | The rewrite rule already exists to handle those requests, it's for pagination of a single page post type. You can get the value of the page number with `get_query_var('page')`. You can render all pages with the same template by creating a `page-{page-name}.php` template file. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "url rewriting, page template, rewrite rules"
} |
Wp_head and wp_footer vs wp_enqueue_script javascript files?
I'm converting a bootstrap html website into Wordpress.
Now, all recommend using wp_enqueue_script() for registering javascript files. i.e.
function themeslug_enqueue_script() {
wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );
But I have some js files loading in the head and some other ones in the footer of the original html code.
I was going to use wp_head and wp_footer, is it ok to do so or better stick to wp_enqueue_script? | It looks like you've overlooked the _5th_ input parameter of:
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
Namely the boolean `$in_footer` part, that will put the script in the _footer_ , if set as `true`, else in the _header_.
You can also use `$deps` to handle dependencies.
Check out the Codex for more info.
=> I would stick to `wp_enqueue_script()` and not manually place the scripts into the header or footer. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "wp enqueue script, headers, footer, wp head"
} |
How to add custom content (text/image) at start of content (IN content ie the same line)
I would like to add some text or image at the start of each post (in a given post layout).
I have found numerous ways to implement this before the content starts ie atop the content (of course, I could just do this by adding the text above `<?php the_content(); ?>`).
But I want to insert it really at the start of the content--on the same line, like:
> HERE IS SOME CUSTOM TEXT and here starts the content entered for the post.
Any ideas, Community? | You can try the following:
! is_admin() && add_filter( 'the_content', function( $content )
{
if( in_the_loop() ) // <-- Target the main loop
{
$prepend = 'HERE IS SOME CUSTOM TEXT'; // <-- Edit your text here
$content = $prepend . $content;
}
return $content;
}, 9 ); // <-- Choose some priority < 10
where we choose the priority before the content is taken through `wpautop`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "posts, the content"
} |
how to remove default jquery and add js in footer?
I want to remove default jQuery, because I am adding new or latest jQuery. Also I want include some js in my footer. How can I do that?
I want to add another different js like a slider js or css in my footer. | This will do the trick when added to your functions file:
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", false, null);
wp_enqueue_script('jquery');
} | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 12,
"tags": "jquery, footer"
} |
How do I override the_excerpt so that it will display full content?
I am creating a plugin. Many themes display excerpt such as when `is_search()` is `1`.
I want WordPress to display full content no matter what.
How would I do so?
Should I use `add_filter ('the_excerpt', 'mycontentfunction' );`
Should I use `add_filter` or `apply_filters`? | Following code should do the trick. It takes the excerpt filter and returns the content instead.
function wpse189347_excerpt( $excerpt ){
return get_the_content();
}
add_filter( 'the_excerpt', 'wpse189347_excerpt', 10, 1 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "filters, excerpt"
} |
Add custom background to div in home page
I want to have featured image on specific `div` on home page that could be changed in customizer. I saw in documentation custom background for `body`(< But I want to make it for specific div eg. `#featured-home-image`. How?
$args = array(
'default-color' => '000000',
'default-image' => '%1$s/images/background.jpg',
);
add_theme_support( 'custom-background', $args ); | Use the `wp-head-callback` argument to specify your own handler:
add_theme_support( 'custom-background', array(
'wp-head-callback' => 'wpse_189361_custom_background_cb',
'default-color' => '000000',
'default-image' => '%1$s/images/background.jpg',
));
function wpse_189361_custom_background_cb() {
ob_start();
_custom_background_cb(); // Default handler
$style = ob_get_clean();
$style = str_replace( 'body.custom-background', '#featured-home-image', $style );
echo $style;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "theme customizer, custom background"
} |
Dashboard memory overload problem
I have a client who has a dev server, and we continue to have problems.
We recently tried to install a new theme, and it's child, and it did become active, but anytime we try to access the dashboard we get this error.
Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 196608 bytes)
There are only 24 active plugins, I have worked hard with the client to reduce the number of actively used plugins.
What else can I do?
I can't even install a caching plugin, without running into these memory errors.
Any suggestions?
Should I use ftp and delete the unused themes? | At the top of your wp-config.php you add `define('WP_MAX_MEMORY_LIMIT', '256M');` this will work only in back-end and do not increase memory in front-end.
If this doesn't work in your site, you can also add this `define('WP_MEMORY_LIMIT', '256M');` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "dashboard, performance, memory"
} |
Dashboard Widget CSS
I want to add a class name to my custom dashboard widget but I've found no way to do this searching the codex. Right now the only class name on my widget is `postbox` (which is added in '/wp-admin/includes/template.php') but I would like to add more. How can I do this?
add_action('wp_dashboard_setup', function () {
wp_add_dashboard_widget('widget2','Graph','widget_2');
});
function widget_2($post){
var_dump($post); /* string '' (length=0) */
?>
<div id="graph-points-by-time" class="graph-points-by-time"></div>
<br class="clear">
<div id="graph-legend" class="graph-legend height-auto"></div>
<?php
} | You could use `postbox_classes` filter as follow:
add_filter( 'postbox_classes_dashboard_widget2', function ( $classes ) {
// $classes is an array; add your custom classes to the array
$classes[] = 'my-class';
return $classes;
} ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, dashboard"
} |
Return Value of load_plugin_textdomain
Good Day,
I'm trying to translate my plugin but it doesn't seems to work.
I read that I should check the return value of "load_plugin_textdomain" to see if it's false (meaning it doesn't find my translation file), but I cannot find how to find this value.
Can someone point me in the right direction?
Thanks
_EDIT_ As requested here is the lines to load it
function ap_action_init() {
load_plugin_textdomain('my_plugin', false, WP_PLUGIN_DIR . '/languages' );
}
// Localization
// Add Actions
add_action('init', 'ap_action_init'); | global $langOK;
add_action( 'plugins_loaded', 'myplugin_load_textdomain' );
function myplugin_load_textdomain() {
global $langOK;
$langOK = load_plugin_textdomain( 'my-plugin', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
Later you can check the value of `$langOK` ( TRUE = success, FALSE = failure ). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, translation"
} |
Wordpress Plugin manipulate have_posts()
I want to develop a plugin, which changes the post order on the blog page, I think I need to manipulate the `have_posts()` function. How can I do this? | The standard query for posts uses `orderby => 'post_date'` and `order => 'DESC'`. The best candidate for arbitrary sort of posts would be `orderby => 'menu_order'` and `order => 'ASC'`. The `menu_order` is not generally used for posts but it is safe to be used. As suggested by Pieter Goosen use action hook `pre_get_posts`:
add_action( 'pre_get_posts', 'your_function_name' );
function your_function_name( $query ) {
if ( !is_admin() && is_home() && $query->is_main_query() ) {
$query->set( 'orderby', 'menu_order' );
$query->set( 'order', 'ASC' );
}
}
The above is for front end. For back end use visual drag and sort jquery and update the database. You can check the logic in pageMash plugin. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, loop, blog"
} |
Two questions about CSSing inside the menus
First, I would be glad if u tell me how can I assign a class(css) to default span tag that include the links inside the menu, created by WP control panel.
And second question is how to use @media queries to define different style of links inside a menus? If I'm using an image instead of the text in the menu, how can I apply different img for another resolution? Say, I got IMG_1 for higher than 999px width screen and IMG_2 for less than 999px screen. I definitely can't just img url from css... so how to make it work? I don't want to use background image as for link, it's ugly :/
Thanks!
UPDATE: Okay, so I think I answered my self the second question. I used span(in order not to go with div inside the span-the default tag comes with WP :/ ) as inline block element, and assign width and height to it, and use background image in the css. This way I can sure to make it with hover effect and also use proper @meta. | If you want your navigation span element to be a block, instead of inline element, just target it via css
nav > ul > li > a > span{
display:block;
}
This is providing your HTML structure looks something like this:
<nav>
<ul>
<li>
<a href="#" class="menu-link">
<span>Home</span>
</a>
</li>
<!-- other list elements go here -->
</ul>
</nav>
Hope this helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, css"
} |
Possibility of Create Site Specific CSS in a Multisite
I would like to know that using multisite feature, is it possible to have exactly same multiple wordpress sites, same content, same themes, (each on its own subdomain) but having few css styles specific to each site?
If so, then how can we achieve this. | Yes, you can add website specific class to BODY, for example.
Best approach is to create little multisite enabled plugin, that adds some class to BODY in `body_class` filter.
function customBodyClass( $classes ) {
global $current_blog;
$classes[] = 'website-'.$current_blog->blog_id;
return $classes;
}
add_filter( 'body_class', 'customBodyClass' );
All themes has to use `body_class()` function in BODY tag, obviously. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "multisite"
} |
Custom Posts Types using Posts Category
I'm using some custom posts types, and, I don't wanna create specific categories for each one.
I'd like to use the Post Category in all my Custom Post.
Here is a example of my new custom posts type:
I know how create new category type for my custom posts, but I don't know how use the regular categories from posts.
/* New Custom Post - Cupons
/* ------------------------------------ */
add_action( 'init', 'create_post_type_cupons' );
function create_post_type_cupons() {
register_post_type( 'cupom',
array(
'labels' => array(
'name' => __( 'Cupons' ),
'singular_name' => __( 'Cupom' )
),
'public' => true,
)
);
} | The documentation for `register_post_type` mentions a `taxonomies` parameter, giving it a value of `array( 'category' )` will do what you want.
There is also the `register_taxonomy_for_object_type` function | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "custom post types, categories"
} |
I created a custom form in HTML/CSS and now I need it to submit ... should I create custom PHP or is there a plugin I can use?
I'm new to WordPress development and any advice would be appreciated! I have been a front-end developer for a while and have always handed off forms I created to a back end guy or gal for them to create the functionality via PHP. My knowledge of PHP is extremely lacking.
Anywho what I'd like to do is take all the info the user checked off or typed etc, and send it... (you know, like forms do) but since I created this custom form that I designed and coded in HTML and CSS, is it too late to apply a plugin? Basically, I'm wondering if since it's all already coded do I have to code the PHP myself or can I pull FUNCTIONALITY ONLY from a form plugin? | The full answer is that you could code it by hand or use a plugin. :)
Many form plugins, however, generate loads of HTML and CSS already, and due to the fact that styling forms is a huge pain (even for a CSS geek like me), you'd be writing tons of CSS overrides to overcome the aggressive coding of, say, Gravity Forms or the like. I spent a huge amount of time re-styling a Gravity Form, and probably used some foul language while doing so (that was just CSS, not HTML changes).
If I were doing this, I'd use Contact Form 7, which allows you to stick all your HTML in its admin screen for each form. You would have to learn the way to define fields in Contact Form 7, which is not hard IMO - it's way easier than raw PHP. Take a peek here and see if it looks easy or hard. And you'd still need some add'l CSS to work with Contact Form 7's CSS, but maybe not too bad.
Then again, someone may chime in with an easy way to hand-code the whole thing. Not my cup of tea, though. :)
Cheers, Dave | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, forms"
} |
Removing non native customizer settings from a child theme
For removing settings, controls and sections of the customizer, we can just simply use the remove methods like this:
function remove_custom($wp_customize) {
$wp_customize->remove_setting('id');
$wp_customize->remove_control('id');
$wp_customize->remove_section('id');
}
What I notice is that there's no way to remove parent-theme customization, so non native customization of Wordpress itself. In fact, trying to remove the `blogdescription` is possible.
I can't find documentation about that. What am I ignoring? | I am guessing a lot about how your themes work but, the child theme's `functions.php` runs _before_ the parent theme's `functions.php`, so anything loaded by the parent's functions isn't going to be present for you to remove. You need to hook your function so that it runs later.
add_action('after_setup_theme', 'remove_custom');
Though you would need to mess about with the `$wp_customize` variable. It would be easier to hook into the `customize_register` hook with a high priority number so that your code runs after the parent registration code.
add_action( 'customize_register', 'remove_custom', 1000 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, customization, child theme"
} |
What exactly does the 's' parameter search for in WP queries?
I have a simple question, but can't find the answer anywhere. What exactly does the 's' parameter search when used in a query? Ex:
`$args = array( 's' => $keyword ); $query = new WP_Query($args);`
Does it just search post content, or does it also look at title, tags, etc?
**EDIT:** Just to clarify. The question is what post fields are being searched, not what data is being returned. | As usual it's most reliable to dump the resulting SQL query and see:
SELECT wp_posts.ID
FROM wp_posts
WHERE 1=1
AND (((wp_posts.post_title LIKE '%keyword%')
OR (wp_posts.post_content LIKE '%keyword%')))
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
ORDER BY wp_posts.post_date DESC LIMIT 0,5
The only two things native search is considering are title and content. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 5,
"tags": "wp query"
} |
How Do I get the author's page id?
I need to assign comments a user makes to the author's page where the user is posting the comment. So, I need to get the author's page id.
I have already tried functions like: `url_to_postid()` and `get_page_by_path()` with no success.
I am using a custom permalink structure for author pages: `
Is there a way I can accomplish this? | It sounds like you need `get_author_posts_url()` which "Gets the URL of the author page for the author with a given ID." If you have set the custom permalink correctly it should work.
If you really are looking for actual page IDs, **_there is no page ID for an author archive page_**. Those pages are dynamically generated and are not "posts", "pages", or any other post type. They are not built to support comments. You are going to have to cook up your own system for that. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, url rewriting"
} |
Is it possible to create a contact form without using a plugin?
I am going over a tutorial for WP and in it, the instructor is able to add in a contact form field from a menu option "Add Contact Form", I do not see this on 4.2.2.
Is this possible to do without using a contact form plugin for this?
**Edit:** After scouring the web, I came across this link that goes over similar steps: <
In it, they mention the following:
How to add a Contact Form
1. Hover over My Sites and click on WP Admin
2. Click Pages > Add New
3. Click Add Contact Form
4. Click Insert Into Post to generate your form’s shortcode
5. Publish the page, and view your form
I do not have the option for 'Add Contact Form' next to 'Add Media' above the text box of the page. Is there an option to turn this on somewhere? | If you install Jetpack which is a product of Automattic/WordPress you will then have the form feature you mention in the link you provided.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "contact"
} |
Display custom fields only if it has a value
I've setup standard custom fields for some products in WooCommerce which are being displayed on each product page on the front end. However, I'd like to hide those fields that don't have a value entered. I've tried some suggestions made elsewhere on this site but they didn't work for me.
This is what I have on the description.php
<div id="customfield-meta">
<?php
// Display Custom Field Value
echo "<ul>";
echo "<li>Catalogue Number: ".get_post_meta( $post->ID, 'catalogue', true )."</li>";
echo "<li>License Type: ".get_post_meta( $post->ID, 'license', true )."</li>";
echo "<li>Width (px): ".get_post_meta( $post->ID, 'iswidth', true )."</li>";
echo "<li>Height (px): ".get_post_meta( $post->ID, 'isheight', true )."</li>";
echo "</ul>";
?>
</div> <!-- end #customfield-meta -->
Any ideas how I could do this? Thank you | You can use isset() function to check if it has a value.
In your case you can do like this :
$width = get_post_meta( $post->ID, 'iswidth', true );
if( isset( $width ) ){
echo "<li>Width (px): ".$width."</li>";
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
How to run Jetpack from localhost?
I just installed the jetpack plugin on my localhost version of WordPress 4.2.2 however after activating it—when I click on 'Connect to Wordpress.com', I get the following error:
!enter image description here
> Your website needs to be publicly accessible to use Jetpack: site_inaccessible Error Details: The Jetpack server was unable to communicate with your site ` [IXR -32300: transport error: http_request_failed Couldn't resolve host 'wordpress.local']
Is there any way to work around this running on localhost? | Add this to your `wp-config.php`:
const JETPACK_DEV_DEBUG = TRUE;
This makes it possible to use features on localhost that don’t require a connection to wordpress.com. See the announcement post on jetpack.me for the background.
For your own plugins, learn that lesson: Do not rely on working outgoing connections. Respect your users privacy, and explain in clear words why such a connection is necessary, what data will be sent, and how to work with the plugin when the connection fails. In other words: Don’t do it the Jetpack way. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 7,
"tags": "plugins, localhost, plugin jetpack"
} |
Missing Jetpack Contact Form button when running locally
I am running JetPack locally using the following `define ('JETPACK_DEV_DEBUG', true);` in my wp-config.php file.
It's running fine, however after activating Contact Form, the button is not appearing when creating/editing a page.
!enter image description here
I've checked the JetPack settings and Contact Form is shown as active, yet the button is not appearing. I've checked for errors in the console log of Chrome and no errors are being displayed either.
Also, I am not using any other plugins aside from JetPack in case there was conflict.
And lastly, tried switching themes, was using 2015 then tried 2014 and 2013 and the button still doesn't appear.
Any idea why it's not working? | Finally, fixed it. I needed to add the following line below:
`define('JETPACK_DEV_DEBUG', true)`
**before** this line in wp-config.php:
`/* That's all, stop editing! Happy blogging. */`
Originally, I had this line after the line mentioned which was causing the Add Contact Form button to not appear. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin jetpack"
} |
Adding PHP in the menu
So, I have following `php` code:
<?php global $my_profile; ?>
<?php if (is_user_logged_in()) : ?>
<div class="img" data-key="profile"><?php echo get_avatar( get_current_user_id(), 64 ); ?></div>
<?php endif; ?>
It pulls the profile picture of currently logged in user. I am trying to add this to one of the menu item title, so that user profile picture is shown as a part of the menu.
It looks like I cannot directly add this code into `menu`.
What would be the best way to add this into one of the menu title?
Thanks.
Steve | Add to your functions file and use wp_nav_menu_items
add_filter('wp_nav_menu_items','wpsites_add_avatar_to_nav', 10, 2);
function wpsites_add_avatar_to_nav( $items, $args ) {
if( $args->theme_location == 'primary' )
return $items;
$dude = get_avatar( get_current_user_id(), 48 );
if (is_user_logged_in()) :
echo'<li class="your-custom-class right">' . $dude . '</li>';
endif;
return $items;
}
Might need to use output buffering.
Some work is required on your behalf to get your code working with this filter. You will need to change the class depending on which theme you're using. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, menus"
} |
Empty header tags
!Problem
When I set the 'posts for page' option to a specific page, then that page gets an empty header and the page is not structured.
The site has a customized theme of twenty eleven. Could someone point me into a direction of a possible solution?
How it should be: right display
NOTE: its not online visible, because of debugging services | It seems to be missing the opening `<?php` or else that text shouldn't be readable above the image. The file seems to be using index.php but it's possible depending on your theme setup that it's a different file missing the `<?php`. Therefore, get_header() is not filling the header at all, because it's displaying as HTML instead of acting as PHP. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.