INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Hide content editor for posts after approriate date
I am tuning my new site and i what to disable Content Editor for post created after date X, but for posts that created before that date Content Editor must be on its place. | function disable_editor_for_old_posts_wpse_101106($post) {
if (strtotime('-2 months') > strtotime($post->post_date)) {
remove_post_type_support('post','editor');
}
}
add_action('add_meta_boxes_post', 'disable_editor_for_old_posts_wpse_101106');
I couldn't find a great hook for this but `add_post_meta_boxes_*` is early enough, and it passes the `$post` object to the callback.
Basically the filter checks the post on the post edit screen and removes post type support based on the post age. I used two months as the cutoff but that is easily altered.
I don't see the point of worrying about the editor except on the backend, unless you have a front-end posting mechanism.
Removing the editor makes the page a bit ugly, but I think that adding some kind of message meta box via `edit_form_after_title` would sort that out-- as done here: <
## Reference
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "filters, hooks, content, visual editor, post editor"
} |
Why do filters/actions require an argument count?
I was just looking at plugin.php trying to answer the above question and I couldn't work it out. The actual code that calls filters is this:
do {
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']));
}
} while ( next($wp_filter[$tag]) !== false );
If `(int) $the_['accepted_args']` wasn't there then it would simply pass everything available to the target function without any adverse affects for functions with less formal params. | 1. Because of backwards compatibility.
You can use the same callback for multiple filters. Inside of that callback you should use `current_filter()` to determine the context. But some plugins use the number of passed arguments instead. Changing that would break these plugins.
That’s why you should always use the API (here: `current_filter()`) and not some made-up construct.
2. Also, PHP will raise a warning when you pass more parameters to a native function than that function expects.
See Ticket #14671 Deprecate the "accepted args" argument in add_filter() and add_action() | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "php, functions, filters, actions"
} |
How can I change the title of the Home link in the navigation bar?
I use Bones theme with a static front page. The header.php calls the `bones_main_nav()` function without parameters, while `bones_main_nav()` only calls the `wp_nav_menu()` function. | `wp_nav_menu` with no arguments and no menus defined in the back end at `wp-admin->Appearance->Menus` (which sounds like the circumstance you describe) just lists your pages, plus a "Home" link.
That is done by calling `wp_page_menu`, the default callback for `wp_nav_menu`, which means that under those conditions you can alter that text by hooking to `wp_page_menu_args` and setting, or changing, the `show_home` argument.
function alter_default_home_link_wpse_1011444($args) {
$args['show_home'] = 'Home is where the heart is';
return $args;
}
add_filter( 'wp_page_menu_args', 'alter_default_home_link_wpse_1011444'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, menus, pages, title, homepage"
} |
I lock the site's contents, click on a post, redirect to login, enter uname+password but fail to redirect to article
As stated in the following:
<
I lock the site's contents.
I then click on a post.
I am navigated to wp-login screen.
I enter the correct username + password of admin.
I am never returned back to the article but remain stuck in wp-login without any feedback.
Please help.. | You have to edit your redirect function to redirect back to the post where you were before redirection
add_action( 'template_redirect', 'login_to_see_content' );
function login_to_see_content()
{
if ( is_singular() && ! is_user_logged_in() )
auth_redirect(); // does nothing for logged in users
}
to this
add_action( 'template_redirect', 'login_to_see_content' );
function login_to_see_content(){
if(is_singular() && ! is_user_logged_in()){
$url= site_url()."/wp-login.php";
$url.='?redirect_to="'.urlencode ($_SERVER["REQUEST_URI"] );
wp_redirect($url);
exit;
}} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp login form"
} |
Wordpress multisite haml templates
I'm building a very large Wordpress multisite at the moment and while I sort out the project at a top level I want to know if it's possible to use haml or phamlp for my templates instead of php.
I have seen two plugins for Wordpress but neither of them seem to work with a multi-site.
My question is, how would I write a VERY basic plugin to read the templates and output them in place of the usual ones?
I want to use haml because it's much cleaner than large html/php templates and I just want to parse header.haml instead of header.php if possible. | Filter `template_include` and use your own templates:
add_filter( 'template_include', function() {
return $path_to_template;
});
The `$path_to_template` should point to file that renders your templates. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, multisite, templates"
} |
How To Show Get Adjacent Posts If Posts Are Sorted By Custom Field
I want to get the ID of adjacent posts.
For posts sorted chronologically you can use:
get_adjacent_post
Are there any standard methods for finding the adjacent post if the posts are sorted by custom field value. Unless its very simple my skills are not up to writing a new function for this purpose.
Thanks. | Hmmmm, the solution to this problem was to read the details of the plugin. It has the capability of returning values other than a link to the next post - this includes the ID of the Next and Previous Post.
In case anyone else reads this in the future and wants to see how to get the ID all you have to do is something like:
<?php $link=next_post_link_plus( array('order_by' => 'custom', 'meta_key' => 'Sort Number','return'=>'id') );?>
Then you can recover any information that you need from the post. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, sort, id, previous, next"
} |
Sort custom post type items by taxonomy description
I want the portfolio items to be arranged in custom order (based on the category descriptions which I use number values to order)
Current order
<ul id="portfolio-cats" class="filter clearfix">
<li class="sort"><?php _e('Sort Items','themename'); ?>:</li>
<li><a href="#all" rel="all" class="active"><span><?php _e('All', 'themename'); ?></span></a></li>
<?php
foreach ($cats as $cat ) : ?>
<li><a href="#<?php echo $cat->slug; ?>" rel="<?php echo $cat->slug; ?>"><span><?php echo $cat->name; ?></span></a></li>
<?php endforeach; ?>
</ul>
If I have 3 taxonomies named _Gender_ , _Age_ , _Height_.
I want the filter beside "All" to display them in above order, based on the taxonomy description.
Gender Desc "1", Age Desc "2" etc.
I want to to this on mass scale so not just 3 taxonomies, hence the need to number them. | You could use this plugin instead of trying to use the description field. It's very lightweight and uses drag-and-drop ordering on the admin end. Then you just `orderby => term_order` when grabbing your terms. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
TinyMCE Editor Set Default Tab
I removed the tabs from the WP editor using
wp_editor('', 'some-id', array('quicktags' => false) );
But sometimes when the page loads the TinyMCE field loads with the Text tab selected:
 ); | My solution. I found that the problem was a JS WP setting. A refresh of the page was required to make the editors initialise with the new setting
<script>
if (getUserSetting('editor') != "tinymce") {
setUserSetting('editor', 'tinymce');
location.reload();
}
</script> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "tinymce, wp editor"
} |
Add Previous/Next Buttons to CPT Single Pages Only
I'm working with a site that is displaying a portfolio CPT on the home page in a "Grid Loop." On the single pages, i'd like to add Previous & Next Item buttons. I thus added this code:
function custom_post_navigation()
{
?>
<div class="prev_next">
<div class="nav_left">
<span class="prev"><?php previous_post_link('%link', 'Previous Item</span>'); ?>
</div class="nav_right">
<div>
<span class="next"><?php next_post_link('%link', 'Next Item</span>'); ?>
</div>
</div>
<?php
}
add_action('genesis_before_post_title', 'custom_post_navigation');
On the site Safety Warehouse It now displays the links properly on the single item pages, but It is also displaying Previous and Next buttons on the home page as well.
How can I remove them from the home page? | I'm not familiar with Genesis, but I assume you can wrap the output of your function in a check if `is_single()`:
function custom_post_navigation()
{
if( is_single() )
{
// output next/prev links
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, templates, next post link, previous post link"
} |
Does is_child() exist in wp 3.5.1?
I'm trying to figure out how to get to a is_child() equivalent; I'd like to be able to target the parent page and it's children. How can this be achieved?
My pseudo-code is...
if (is_page('pagename') || is_child('pagename')) {...}
...however, the is_child() doesn't seem to work. I would like it to return true. | To check for a specific parent ID use `$post->post_parent=="123"` and replace "123" with the parent ID of your choice.
I learned how to do this by using the Widget Logic plugin. From the Widget Logic notes:
`global $post; return (is_page('pagename') || ($post->post_parent=="13"));` \-- home page OR the page that's a child of page 13
Edit: A better source is Testing for sub-Pages in the codex. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, pages, navigation"
} |
Secure Pages Best Practice
I am in process of writing a plugin that has front-end shortcodes that display a user's information/data. If the user is not logged in, I need to redirect to a front-end login page/form. What would be the best practice here? My plugin creates the pages that I use as well as add the shortcodes to those pages. So, if there is a way to "protect" those pages I would love to know. | Not sure about the best practices, but I have a few custom login-sensitive pages which simply display a message if user is not logged and is trying to view the page directly:
$logged_in = is_user_logged_in();
if($logged_in) {
?>
<article id="post">
<?php the_content(); ?>
</article>
<?php
} else {
_e('You are not logged in. Please ', 'abc');
echo '<a href="' . site_url( 'login' ) . '">'. __('log in','abc') .'</a> ' . __('or','abc') . ' ';
echo '<a href="' . site_url( 'register' ) . '">'. __('register','abc') .'</a>.';
}
Note: both the `login` and `register` pages are custom pages as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, pages, shortcode, security"
} |
Migrating database / content of non-CMS site to Wordpress
I have a non-CMS website which is fully build with PHP with a lot of content in it. I don't want to add my posts manually in Wordpress, because that's a pain in the ass (I am talking about 5000 posts)...
So my question would be: how do I do this? Is it even possible to clone something like this? | If your data is inside database as I understand, it is possible to export your database to CSV file and import this to Wordpress. CSV file is basically a comma separated list of data from your database that makes it possible to transfer data from different database structure to another.
It does indeed take some effort to configure your export/import so that you get your data right, but it's a lot easier thing to achieve than re-posting 5000 posts.
Look for Wordpress plugins "csv importer" and/or "wp ultimate csv importer".
You can export your data using your SQL-client (these often have an option to export in csv) or using PHP (see <
If your data is NOT in database, you could consider web scraping techniques (see: wikipedia / Web_scraping) where you go through your site programatically and look for id's, classes and elements to create structured data out of your html files.
Hope this was helpful! | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "database, mysql, migration, cms"
} |
Get logged in username in wordpress url
I want to get the username of the logged in users in the URL of my wordpress site. Like if user: **arvind** is logged in, I want to get the url as **'www.wp.com/arvind'** or **'www.wp.com?user=arvind'**.
Is there any solution for that? | I think this will do what you are looking for.
add_action("template_redirect", 'template_redirect');
function template_redirect() {
global $wp;
if(is_user_logged_in() && !isset($_GET['user'])){
$current_user= get_userdata(get_current_user_id());
wp_redirect(add_query_arg(array('user'=>$current_user->user_login),home_url($wp->request)));
die();
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, users, urls, site url"
} |
WooCommerce - Is is possible to replace downloadable file and allow existing customer to get it?
I have a WooWommerce 2.0 shop where I sell downloadables and, from time to time, I have to replace existing files with newer versions. When I replace the file URLs for the downloadable files, Customers who already purchased them earlier cannot get the latest version by following the link they received with their order, receiving a "No File Defined" error instead.
Is there a way to ensure that the link received with an order always grants access to all the files defined for the Downloadable Product, no matter what they are? Alternatively, would there be a way to send updated links to existing Customers?
Thanks in advance for the answers. | Wherever the actual file is, you should be able to FTP to it and simply replace it with a file with the exact same name. Unless Woocommerce keeps some kind of filesize account of what is there, it shouldn't know the difference as to whether it is delivering the old file or the new file. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins"
} |
Getting Custom Post Type content from main-site of a Multisite
I have a multi-site network with 3 sub-sites:
!enter image description here
Is it possible to "link" or include custom post to all 3 sites from the main site?
By include or link I don't mean to make other sites to edit them, I'm asking for the visual solution.
If possible, could I do that without using a plugin? | You could use the technique in this Stack Overflow answer, that's basically:
switch_to_blog(1); //switch to main site
$latest_posts = get_posts($args);
foreach( $latest_posts as $post ) {
// print post
}
restore_current_blog();
Just add **`'post_type' => 'your-custom-post-type'`** to the query. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins, custom post types, multisite, wp admin, network admin"
} |
Output Sanitation
I've read the WP codex and several tutorials about data validation and sanitation in WordPress. Now I've got this simple example code:
`$title = "<script>alert('Test')</script>"; echo esc_html($title);`
According to the tutorials and the codex this should be the output: `<script>alert('test')</script>`
But on my website I get this: `<script>alert('Test')</script>`.
Am I doing something wrong? Because the XSS isn't being executed, so the esc_html filter is working correctly.
Thanks in advance! | Your code is working correctly. If you look at the source code of the page, you will see:
<script>alert('Test')</script>
When the above text gets processed for display by your browser, it then becomes
<script>alert('Test')</script>
which is what you want to be **displayed**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "validation, sanitization"
} |
Get Permalink for the top level parent of child pages
I've this pages structure:
* TOP PAGE
* SUB PAGE 1
* SUB SUB PAGE 1
* SUB PAGE 2
[etc]
Is it possible to display on each sub page a link to come back to the top level page? And how? | Here's a way to get the top page url:
$top_page_url = get_permalink( array_slice( get_ancestors( get_the_ID(), 'page' ) , -1 ) );
where `get_ancestors()` returns an array containing all the parents (ID) of the given page. You can read more about it in the Codex here.
Here are various ways to get the last array item, but note that `end()` doesn't expects a function as an input - more about it in the PHP docs here. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "pages, child pages"
} |
Is 'preload="none"' a valid parameter in the [audio] shortcode in WordPress 3.6?
I know that MediaElement.js is part of the WordPress core in WordPress 3.6. I currently use the MediaElement.js plugin on my WordPress 3.5.1 sites. On some pages, we have several players on one page, and we need to specify `preload="none"` as a parameter in the MediaElement.js shortcode, because if we don't, some browsers (mainly iOS devices) will try to download all the MP3 files at once.
Here is the shortcode that we currently use:
[audio mp3="filename.mp3" preload="none"]
In WordPress 3.6, with MediaElement.js built-in, will the `preload="none"` parameter have any effect in the `[audio]` shortcode? | I looked at the wp_audio_shortcode function in wp-includes/media.php of the release version of WordPress 3.6. The _preload_ parameter is a valid attribute of the [audio] shortcode. However, the default is 'none', so in my case it is not needed.
From WordPress 3.6 (release), wp-includes/media.php, function wp_audio_shortcode:
$default_types = wp_get_audio_extensions();
$defaults_atts = array(
'src' => '',
'loop' => '',
'autoplay' => '',
'preload' => 'none'
);
foreach ( $default_types as $type )
$defaults_atts[$type] = '';
$atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
So the answer is, yes, it is a valid parameter in the [audio] shortcode, but the default value is 'none', so in this case it is not needed. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "audio"
} |
<ul> inside <ol> in editor
I want to add
<ol>
<li>First list</li>
<li>Second List
<ul>
<li>Sub Second List</li>
</ul>
</li>
<li>Third List </li>
</ol>
This is not possible with editor without manual job. How can we achieve this | This is entirely possible, as I just tested it in WordPress.
1. Create your unordered list
2. Add four items: "First list," "Second list," "Sub Second List," "Third List"
3. Place the cursor on "Sub Second List" and click Indent (you will need to expand the kitchen sink to access the indent button
4. With the cursor still on "Sub Second List," click Unordered List
Following the steps above will produce the following markup:
<ol>
<li>First List</li>
<li>Second List
<ul>
<li>Sub Second List</li>
</ul>
</li>
<li>Third List</li>
</ol> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "html, editor"
} |
Internal Server Error every time I push up my Wordpress Project to Heroku
We use Heroku to deploy our Wordpress project. However, everytime we push up it seems that all of the links bring the user to an Internal Server Error page. The homepage works.
Updating the permalinks (using the pretty permalinks for %postname%) solves this issue.
What we believe to be happening is that when a user hits: www.example.com/menu the permalinks haven't been updated yet, so the user sees an Internal Server Error. If you go to www.example.com/?p=2 you get redirected to www.example.com/menu but the page shows an Internal Server Error again.
Right now we have to update the permalinks **every time** we push up a new version of the site.
Anyone else have this problem and what did you do to solve it?
Much appreciation. | The problem ended up being that the wp_rewrite was not flushed on the push to the Heroku server. So, what I ended up doing was creating a file in the root directory with the following code:
<?php
global $wp_rewrite;
$wp_rewrite->flush_rules();
?>
Then I added a deploy hook for heroku via command line
heroku addons:add deployhooks:http --url=
So, now when I deploy my application on the Heroku server, it runs the flush_rules() method and all is good. Thanks s_ha_dum! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, deployment, internal server error"
} |
Showing user ID on user main page from screen options
On the user main page in the screen options, you have some choices for displaying user information e.g.. e-mail, role, posts etc..
Is there a way to be able to display the user's unique ID? | You need to use the filter `'manage_' . $screen->id . '_columns'` to add a column and `manage_users_custom_column` to display its value.
add_filter( 'manage_users_columns', 'column_register_wpse_101322' );
add_filter( 'manage_users_custom_column', 'column_display_wpse_101322', 10, 3 );
function column_register_wpse_101322( $columns )
{
$columns['uid'] = 'ID';
return $columns;
}
function column_display_wpse_101322( $empty, $column_name, $user_id )
{
if ( 'uid' != $column_name )
return $empty;
return "<strong>$user_id</strong>";
}
With this, the ID will show up in the _Screen Options_ as well. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "php, users, user meta, screen options"
} |
get all page IDs from wp_list_pages
I am looking for a way to output all page IDs from the following menu:
<?php wp_list_pages('depth=1&exclude='3,5,11')); ?>
Only top level pages needed, therefore the 'depth=1'.
Any help appreciated. | `wp_list_pages()` is for formatted markup. Use `get_pages()` and `wp_list_pluck()`:
$pages = get_pages(
array (
'parent' => 0, // replaces 'depth' => 1,
'exclude' => '3,5,11'
)
);
$ids = wp_list_pluck( $pages, 'ID' );
`$ids` holds an array of page IDs now. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp list pages, id"
} |
Limit of char count in WP custom fields
does anyone of you know what is the limit of chars count which can be stored in to database via WP custom fields? Let's say that I would want to add to custom field 20 000 chars. Would it be problem? | That field is `longtext` so it should be more than you could ever use-- about 4GB | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom field, database"
} |
Add the custom post term to the custom post title
what I need is this: add a term from a custom post to the post's title. Like this: Custom Post title - term
Right now I have:
$terms_of_post = strip_tags (get_the_term_list( $post->ID, 'my-custom-term', '','', '', '' ));
elseif ( is_single() ) { single_post_title(); {echo ' ('; echo $terms_of_post; echo ')';} ; }
I don't know why it doesn't work, but it seems it should.
I have found Copy a Taxonomy Term into the Post Title for a certain Custom Post Type, which could be 90% of the answer, but instead of replacing the post title with the taxonomy title, I need to add it to the title.
Thanks a lot! | You can try this (based on your unfinished PHP code)
if ( is_single() ) {
$terms_of_post = get_the_term_list( get_the_ID() , 'my-custom-term', '',', ', '', '' );
$terms_of_post = strip_tags ( $terms_of_post );
single_post_title();
if( $terms_of_post ){
echo ' (' . $terms_of_post . ')';
}
}
to get this format:
Title (term1, term2, term3) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, terms, title"
} |
.htm re-write is adding an ending / to my URL bar
The client site I am working on required me to make the Page post type pages to end with the .htm extension.
I got that working, however when you go to a page...
`www.domain.com/mypage.htm` it loads the page but it then add an ending `/` to the URL in the address bar so it turns into this `www.domain.com/mypage.htm/` my client is asking me if I can disable this.
Does anyone know if this is possible? | Go to Settings->Permalinks and remove the trailing slash from your Custom Structure. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting"
} |
where does this $post_id come from?
I was trying to figure out why `save_post` wasn't being fired upon 'Quick edit', and found the solution here \- apparently global `$post` is not available when updating a post in Quick edit mode.
So - I got it working now - see working example below, but I don't understand _why_ it's working.
function mytestfunc($post_id)
{
$key = 'test';
$data = 'this is a test';
update_post_meta( $post_id, $key, $data );
}
add_action( 'save_post', 'mytestfunc' );
Can someone explain to me where this `$post_id` is coming from? I'm not passing the value in `add_action` \- so I don't understand why `mytestfunc` knows which post I'm targeting? | It comes from `wp_insert_post()`, where `do_action()` is called with two additional parameters:
do_action('save_post', $post_ID, $post);
So it is not _you_ who adds the parameters, it is WordPress.
If you register your callback with the fourth parameter set to `2` …
add_action( 'save_post', 'mytestfunc', 10, 2 );
… you will even get the complete `$post` object:
function mytestfunc( $post_id, $post ) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "save post, quick edit"
} |
Bad Request (Invalid Hostname) on working server, database problem
I have a local server up using EasyPHP. I know its working because I have a default wordpress install running and up on my brower. I have a full site which I also know I have working because when I set up an empty database and then did the wordpress install the theme was working perfectly but without the content. I have a backup of the actual database this site used and when I create a database, and import the data using PHPMyAdmin and connect it in the wp-config.php file I am getting:
Bad Request (Invalid Hostname)
What am I doing wrong? | Be sure you have updated your database to reflect the correct URL. You can do this in phpmyadmin with a bit of SQL. Good article about it here:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "plugins, admin, database, mysql, wp config"
} |
WordPress's "Text" Format
When using self-hosted WordPress, you have the option of writing in "Visual" or "Text" mode.
!visual and text tabs in WordPress editor
Assuming there's no plugins installed,
1. Is this "Text" format a well defined standard or pseudo standard? (like markdown, textile, etc.)
2. Is there a single place in a plugin-less `3.5.1` WordPress where this text is converted into HTML?
3. If the answer to number 2 is "No", how is this text converted into html? | Text its just plain text, just as its saved in your db.
Wordpress changes line breaks with paragraphs with the function wpautop, through the filter `the_content` and `the_excerpt`.
If you need to remove the `wpautop` behavior, you can remove the filter by doing this in your theme's functions.php:
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
And maybe adding your own customized function:
add_filter( 'the_content', 'my_custom_format' );
add_filter( 'the_excerpt', 'my_custom_format' );
function my_custom_format ($text) {
// do something with $text
return $text;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "hooks, wysiwyg, text"
} |
Change path of the page's template
It's possible to create templates for pages with that:
`<?php /* Template Name: Contact */ ?>`
This templates are located on the theme folder, right? Is possible to change the default path where WP search for those templates? If I want to make a lot of templates, can I create a folder to put them?
Thanks | You can place the page templates wherever you want (also in a separate folder) as long as the files are within the current or parent theme's directory.
UPDATE: Follow this link to get a more detailed information about the Template File Folders: <
Take also a closer look at the Page Templates and the default TwentyTwelve Theme: their Custom Page Templates are stored within the `page-templates` folder. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "page template, paths"
} |
Amazon S3 + Cloudfront with Wordpress
I put together a wordpress site on a heroku free instance and I'm making all images to go to an S3 bucket and a Cloudfront distribution with this plugin . The thing is, it only uploads the images to S3 and serves them with the proper CNAME I set up.
What I want is to serve the wp-content (all my plugins and themes) through S3. I know it's possible because I've read about it, but all tutorials around are explaining the Origin pull and not this configuration. Can anyone tell me more about how can I achieve this? Thank you!! | There is no remotely easy way to accomplish this with "push" strategy, because (unlike attachments) plugins and themes do not really declare their resources to WordPress.
To push those resources you need to enumerate them and keep that information up to date. In pull configurations this happens automagically in actual use. For push configuration you will either have to scan _everything_ for assets and upload _all_ of them, or build some kind of way (automated or manual) to figure out which are actually used.
In a nutshell - currently WP doesn't really manage of extension's assets and has little functionality to work with them. Thus prevalence of pull configurations you see reflected in information around. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "cdn"
} |
When submitting the form site.com/blog/wp-admin it goes to site.com/wp-admin
I have 2 wordpress websites. One at `site.com` and the other at `site.com/blog`.
I want to go to administration of `site.com/blog`, but when I point to `site.com/blog/wp-login.php` or `site.com/blog/wp-admin/` and login, it goes to `site.com/wp-login`!!!! (Both wordpresses have the same user/passwords)
Please help me stay at when I point the browser to! | You have to define the home url, in the installation folder of `site.com/blog`:
define( 'WP_HOME',' );
define( 'WP_SITEURL', ' );
I think this can solve your problem. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "admin, wp admin"
} |
WordPress Twenty Twelve Child Theme. Removing default widgetized areas
I'm trying to remove Main Sidebar, First and Second Front Page Widget areas in my child theme. Basically I don't want them to be shown up in Admin Panel.
I've placed that code into my function.php file. It's seems to not work:
function remove_some_widgets(){
unregister_sidebar( 'Main Sidebar' );
unregister_sidebar( 'First Front Page Widget Area' );
unregister_sidebar( 'Secon Front Page Widget Area' );
}
add_action( 'widgets_init', 'remove_some_widgets', 11 );
I've got it from WordPress Codex but I think that was developed for Twenty Ten theme. Anyone knows the right code for Twenty Twelve parent theme. ?
Thanks for answers. | The unregister_sidebar takes the `ID`, not the `name`:
<?php unregister_sidebar( $id ); ?>
You'll need to do it like this:
<?php
function remove_some_widgets(){
unregister_sidebar( 'sidebar-1' );
unregister_sidebar( 'sidebar-2' );
unregister_sidebar( 'sidebar-3' );
}
add_action( 'widgets_init', 'remove_some_widgets', 11 );
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme twenty twelve"
} |
URL Rewriting in WordPress
How can I rewrite URLs on WordPress?
For example, I have a URL like `sitename.com/?page=<numbers>&id=<numbers>` and I want to rewrite it as `sitename.com/page/id/<other info>`. How can I do that? I don't understand the rules! | Your best bet for an easy solution is to actually use the "Custom Structure" option in your WordPress admin under Settings > Permalinks.
There are a number of other structure tags you may use as seen in the Codex.
If you're looking for even more customization and manual control, it's actually a pretty complex topic involving editing your .htaccess file. This great two part tutorial by Stephan Harris covers this topic very well. (Better than I ever could here on SO). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Wordpress ultra slow if I click on posts?
I have 5000 posts on my website, which I have uploaded from a `CSV` file. This all went well and the website is fast on the back-end and frankly on any other page. There is one exception: if I click on a post, it takes 8 to 9 seconds to open a post, which is very disturbing.
I am using _year/month/year/post-name_ as the `permalink structure` and have edited the **.htaccess** file with the code that is outputted by Wordpress on the `settings` page.
What should I do? I have used WP-Minify, but that did not have any effect at all.
FYI: it's a self hosted website, running on a fast server. The website is very fast, except at clicking on a post. Than it changes suddenly. | The problem was that post hadn't tags and I had a function which outputted related posts based on tags. So what happened was that ALL posts were loaded instead of a couple of related posts. That was the cause of the slow speed...
Thanks for your help guys, appreciated. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, posts, wp query, pages, get posts"
} |
Cancel jQuery 'noConflict' - is it really unsafe?
I use some external plugins (not wordpress plugins), that use '$', and it's very convenient for me to cancel `noConflict` mode, by adding this line
`$=jQuery`
But I guess they invented `noConflict` mode not for nothing.
The question is how much have to worry about it. And is really a problem to use `$=jQuery`? | The problem with the `$` alias is that a number of libraries quite puzzlingly decided to use the _same_ variable as an alias. If two libraries try to use the same variable, one or the other will win and anything dependent on the other one will break.
If you are only using jQuery, and never anything else, it should be fine to use the `$` but you should not ever do that except for a site that you personally maintain. I suspect you will regret it if you ever want to use another library, though. Using that hack in a plugin or a theme would be very bad form.
What you are doing is only marginally easier than this though (from the jQuery.noConflict docs):
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
But then I don't know what kind of "plugins but not WordPress Plugins" you are talking about, or whether that is even relevant.
## Reference
< | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "jquery"
} |
Will multiple BuddyPress groups slow down a site?
I'm looking into creating a support forum where each product has it's own mini support forum. I was told that BuddyPress could work well for this, but I'm wondering how that scales for a site that has hundreds or thousands of active products. Any idea what kind of impact that would have on site speed and performance?
**Edit:**
To make the reason for this more clear, the site is a marketplace, where each product can have a different seller. That's why I'm not looking (nor do I care for) a central support system. Each individual seller is responsible for their own support. | You can easily scale a site to have tens or hundreds of thousands of BuddyPress groups. Groups themselves are negligible in terms of storage. When you start getting lots of forum content etc in the groups, you'll have to worry about scaling, but you'd have to do that whether you were using BP as a wrapper or not. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "buddypress, performance"
} |
I want to fill the comment with the comment count?
I am using a custom function to pre fill the comment text area with the number of comment count but getting an error header already sent can any body guide me here's the code I am using
add_action('pre_comment_on_post', 'dump_comment');
function dump_comment($post_id, $author=null, $email=null) {
$comcnt = $cmntcount = comments_number( '#0', '#1', '#%' );
$comment = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null;
if (!$comment) {
$_POST['comment'] = 'Design' . '$comcnt';
}
} | I think the reason for your _header already sent_ error is that you are using
comments_number()
that will _echo_ the value.
Try instead
get_comments_number( $post_id );
to _return_ it.
The Codex info on this function says that it returns the total number of comments, trackbacks, and pingbacks for the post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments"
} |
How to modify the default feed via a function
I am trying to add a functionality to the default wordpress feed. The problem is i managed to do this modifying the rss feed php file. The problem number two that i have in mind is when wp gets an update also that file will be updated and my code will disappear.
So i am looking to for a way to insert my code as a filter or something else for the rss feed.
Note: **My code does not modify the default feed content, instead i want to display another feed from external site.**
add_filter( 'the_name_for_the_rss_filter', 'my_function' );
function my_function( $some_var ){ global $some_var;
if($some_var == true){
// let's say:
// echo file_get_contents("
// exit(0);
}
} | You could try out the `template_redirect` action to overwrite the default feed template:
add_action( 'template_redirect', 'custom_template_redirect' );
function custom_template_redirect() {
if (!is_feed())
return;
header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true);
// your own template stuff here
exit();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, feed"
} |
Taxonomy templates in a multilanguage site
Let's say I have a multilanguage (English and Spanish) site with a custom post type called Books, with two custom taxonomies, Authors and Publishers.
The template files used to render the taxonomy archives in English would be:
taxonomy-author.php
taxonomy-publisher.php
My question is, do I have to duplicate this file for the Spanish version too, like this?
taxonomy-autor.php
taxonomy-editorial.php
Is there a way to avoid having to do this for every language in my site?
Any ideas?
Thanks in advance | The templates use the _internal name_ of the taxonomy. These will be the same in all languages.
The internal name is the first part in `register_taxonomy($taxonomy, $object_type, $args)`. What your users _see_ is the translated name from the labels.
So, no, you don’t have to recreate the templates for each language. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy, multi language"
} |
Highlighting the current users comment
I don't know if this is possible, I've searched around but came up short. Basically, I need that the current user who is commenting to see his comments slightly different than the rest.
I'm doing this for admins/moderators, but the thing is that all users see the highlighted comments made by admin/mod, where here I just want every user to see his comments as highlighted. | assumes that your theme is using `comment_class()`;
example (to be added to functions.php of your theme):
add_filter( 'comment_class', 'comment_class_logged_in_user' );
function comment_class_logged_in_user( $classes ) {
global $comment;
if ( $comment->user_id > 0 && is_user_logged_in() ) {
global $current_user; get_currentuserinfo();
$logged_in_user = $current_user->ID;
if( $comment->user_id == $logged_in_user ) $classes[] = 'comment-author-logged-in';
}
return $classes;
}
requires formatting of the css class:
.comment-author-logged-in { }
I recently posted a plugin version in my site. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "comments, users"
} |
How to load dynamic option with ajax
Basically I'm creating an options page in which the user will click on a button to display a text input field, which will then be populated by the user with a name.
This name will be then saved into the db using ajax (all that's working already). The user will be able to as many names she/he wants.
At the moment, as a feedback to the user, I'm adding a list with the names that were previously saved with jQuery, however I'd like to load the options from the db to check whether the info collected by jQuery is correct.
I've been doing some research and it seems the way to do it is to use `wp_localize_script` which I'm finding it cumbersome to load dynamically created data.
Is using `wp_localize_script` the correct way to do it or should I just make an ajax call as you'd normally do? | I don't know if there is really a right answer to this question, and I don't know what you find cumbersome about `wp_localize_script`, but you should be able to do it either way.
The difference is that with `wp_localize_script` the data is printed to the source of the page, which you wouldn't want if the data were sensitive, and `wp_localize_script` should represent a wee bit less load on the server as it doesn't require a separate connection as AJAX does.
I'd lean towards `wp_localize_script` unless there are compelling reasons to do something else. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ajax, theme options, options, wp localize script"
} |
How to call custom function outside from the admin page?
I've created a function but i have some problems with it...
echo get_option( 'my_function', 'custom_logo' );
I try to use this in my code but it returns me an array not a string.
When i use `echo $options['custom_logo'];` on my plugin backend admin page the code returns the value as a string.
So how can i call it from my theme for example? | Out of context, it is hard to say anything definitive. There is a lot of information missing.
If you saved an `Array` to the `$wpdb->options` table (`add_option` or `update_option`) then `get_option` will return an `Array`. If you saved a string, it will return a string. If you want a string then you are _saving_ the option incorrectly, but you haven't posted the code that saves this value.
As far as `$options['custom_logo']` being correct, without knowing how the `$options` array was created I don't know what to say. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions"
} |
Get user_meta values for a user for an array of meta_keys?
I would like to retrieve the `meta_values` for an array of `meta_keys` for a user. Is there a function in WordPress core that offers this functionality? Something that would work like this:
$array_of_keys = array( 'key_1', 'another_key' );
$values = get_user_meta_array( $user_id, $array_of_keys );
And values would maybe be an array like this:
array(
'key_1' => 'some value',
'another_key' => 5,
);
I could easily write a custom function to do this, but I would rather do it 'the WordPress way' if there is one.
Thanks. | `get_user_meta()` with omitted key argument will return all data for the object.
Trying to retrieve metadata selectively is usually pointless optimization from performance point of view, since everything built on Metadata API tends to just query _all_ data anyway and cache it (which in turn object cache plugin makes persistent and snappy). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "user meta, array"
} |
How to show tags in posts with a theme that does not do it
For my wordpress site I bought a theme, but I discovered later that this particular theme does not show posts' tags (in posts' pages). Is it possible to force the theme to show tags in posts ? | Filter `the_content`, and add the result of `get_the_tag_list()`:
add_filter( 'the_content', function( $content ) {
if ( is_single() )
$content .= get_the_tag_list( '<p>Tags: ', ', ', '</p>' );
return $content;
});
The other option is to create a child theme and add `the_tags()` where you need it in a template. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, tags"
} |
Problems with loop
I have this loop in my index.php:
<?php if (have_posts()) :
while (have_posts()) :
get_template_part( 'post' );
endwhile;
endif; ?>
which calls this template
<?php
?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?></a></h2>
<?php the_post();
the_content(); ?>
<p class="date"><?php the_time('l, j F Y'); ?> </p>
<?php trackback_rdf();
?>
The loop behaves strangely printing out titles and posts in this order:
* Title post #1
* Content post #1 (and this is ok, but then...)
* Title post #1
* Content post #2
* Title post #2
* Title post #3 (and so on...)
What am I doing wrong? | `the_post()` function is what advances the internal counter and loads the data for the next post. You're calling it between the title and content:
the_title();
the_post();
the_content();
You want to change the order and move it before the output of any of the other template tags:
the_post();
the_title();
the_content(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "loop, get template part"
} |
Unable to access WP admin
I cannot access admin via:
or
>
> Fatal error: Class 'ObjectModel' not found in /home3/xxxxxx/public_html/example.com/wp-includes/class.wp-dependencies.php on line 28
>
I have had a trojan on my website that will put own `.htaccess` redirect stuff. And what is worse the WordPress version was up to date 3.5.1 and I have almost no plugins installed.
File permissions were `644` and directories `755`. How can it write to `.htaccess`?
What file permission should I set for `.htaccess`?
I am on a shared Justhost hosting. | Dear you don't need to worry about much - if its a fresh installation and you don't have any data on your website - eg post, article, images or anything then I prefer you t install a clean fresh wordpress again from the sketches after a complete scan of your hosting.
and if you have data in your hosting I am sure you can access your data base from cpanel or hosting central of your account download your data base its the most important thing you need becaue wordpress is just a CMS. after downloading data base follow step 1 and load the data base from within wordpress or from hosting center.
the third that is download wordpress and find wp-dependencies.php upload it to appropiate folder might help you keep us up to date what are you doing. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "htaccess, shared hosting, wp filesystem, virus"
} |
Add segment to URL in htaccess
I want to edit .WordPress .htaccess file, add a segment to URL in the following fashion:
Instead of:
make it
How can I do that? | Go to _Settings/Permalinks_ and add the static string to to the permalink structure:
!enter image description here
No need to touch the .htaccess.
## Update
To make WordPress sending a hash `#` for its post permalinks you have to filter `pre_post_link` to make the structure `'#%postname%'` and `post_link` to remove trailing slashes:
add_filter( 'pre_post_link', function( $permalink ){
return '#%postname%';
});
add_filter( 'post_link', function( $permalink ){
return rtrim( $permalink, '/' );
});
Be aware, you will ruin your site with those permalinks.
See also Change the link URL in default RSS feeds | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "permalinks, htaccess"
} |
how to remove sidebar from particular one page
I am writing this code in page.php for removing the sidebar in one page
<?php if (is_page('x')) : ?>
<?php else : ?>
<?php get_sidebar(); ?>
<?php endif; ?>
... where `"x"` is the ID of that page.
but I am having a bit of trouble though the forum which is the page in question does not stretch across the whole page. how can I solve this problem? | If you want to specify the page `ID` in `is_page` then you should remove the single inverted commas. Please read the documentation first. is_page() see the examples section and your issue will be solved. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, sidebar"
} |
Show more than 20 items in pages or posts edit dashboard
How can an admin display more than 20 items under "ALL posts" ( or on other pages )? | Go to `Screen Options` at the top, and change the number to something like 200. I don't think it will survive much more than that.
!enter image description here | stackexchange-wordpress | {
"answer_score": 33,
"question_score": 17,
"tags": "pages, screen options"
} |
How to check if I am inside the WP Theme Customizer preview?
I have some elements showing on the home page that I do not want to display in the Theme Customizer preview window. Is there a simple check in PHP that I can use for that ?
For example:
<img class="background" src="<?php echo $background ?>" <?php if(is_wpThemeCustomizer()) echo 'style="display:none"' ?>/>
I could do it in javascript using the js file that is enqueued only in this case, but I would like to use PHP, or even better : CSS. Is it possible ? | Check for global variable `$wp_customize`:
if ( empty ( $GLOBALS['wp_customize'] ) )
{
// show something
}
**Update:** in WordPress 4.0, you can use `is_customize_preview()`. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "template tags, theme customizer"
} |
Change the order of columns for a custom post type on the admin list page
I have created a custom post type (screen shot below), and would like to change the order of columns. Is it possible to move the "tags" column before the "date" column?
Screen shot:
!Screen shot | Yes this is possible. I have changed this for the default post type, but this is also possible for a custom one.
First check the codex:
<
function your_columns_head($defaults) {
$new = array();
$tags = $defaults['tags']; // save the tags column
unset($defaults['tags']); // remove it from the columns list
foreach($defaults as $key=>$value) {
if($key=='date') { // when we find the date column
$new['tags'] = $tags; // put the tags column before it
}
$new[$key]=$value;
}
return $new;
}
add_filter('manage_posts_columns', 'your_columns_head');
You can change the $defaults array as you like this way. | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 9,
"tags": "custom post types, screen columns"
} |
Why does wp_links still exist in the db schema?
I understand that _links_ used to be a big thing when Wordpress came out and during the blog rise, but the link feature is so underused nowadays that as of version 3.5 it is hidden by default (thus greatly discouraging its usage).
Moreover, I don't see any reason why Links themselves shouldn't be a **Custom Post Type** as it would be much more consistent with the approach Wordpress has taken in its data architecture.
Is **backwards compatibility** the only reason why such basic things as the db schema aren't touched? Or is there some other reason I am not grasping? | You answer yourself pretty much - "hidden" does not mean removed. It still works.
And yes, the reason would be backwards compatibility which is considered absolute priority in WP. See #21307 Remove Link Manager from core for context and discussion. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, links, core"
} |
Customize Editor Styles
I know there are plugins that do this, but since my needs are so small, I'm hoping there's another solution...
I want to edit the `<hr />` style in the WordPress editor to have `clear: both;`. Is there a way to do this in the functions.php or something? | @dalbeab already answered your question, but thought I would point out a way to add horizontal rule to your editor if you wish.
Within `functions.php`, you can add this:
// add horizontal rule button
function enable_more_buttons($buttons) {
$buttons[] = 'hr';
return $buttons;
}
add_filter('mce_buttons', 'enable_more_buttons');
Then you will have a TinyMCE button that looks like this which will let you add an `<hr />` with only 1 click:
!enter image description here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "editor, visual editor"
} |
Have WP Theme update from Git Repository
I have a client's theme currently hosted on github. Instead of doing a git deploy or using a service like Beanstalk's deployments. I will be pushing the same theme across many sites (79 to be exact) and want them to be able to update themselves just like a WP repo hosted theme. A good example is how the Genesis framework has it's updates work. I've seen things where you have another plugin installed to do this, but i'm looking for a more minimalist solution (if there is anyway to keep this functionality within the theme itself)? | There're a couple of libraries out there. One of the more well known is from Joey Kudish and hosted on GitHub itself.
Basically it does the following:
* utilizes the GitHub API
* Adds a callback to the `'pre_set_site_transient_update_plugins'` filter
* Adds another callback to the `'plugins_api'` filter
* finally utilizes the WP HTTP API and does a `wp_remote_get()` to the GitHub repo.
Oh, yes - close to have forgotten this - it adds a transient to avoid checking the remote repo on every request. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development, automatic updates, git, github"
} |
Add a subitem to Woocommerce section
I want to add a subitem to "Woocommerce" parent item, below "Orders", this subitem is a custom post type.
!enter image description here
I tried to use `(in $args)`:
$args = array('show_in_menu' => 'edit.php?post_type=shop_order');
register_post_type('my_posttype', $args);
But it doesn't work, I tried with another section ex. 'edit.php?anotherpage' and it works.
!enter image description here
Any idea?! | Short answer, use:
$args = array('show_in_menu' => 'woocommerce');
register_post_type('my_posttype', $args);
But this won't give you the custom post type submenus.
You can also use `add_submenu_page`, the code below is just an example:
function register_my_custom_submenu_page() {
add_submenu_page( 'woocommerce', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-custom-submenu-page', 'my_custom_submenu_page_callback' );
}
function my_custom_submenu_page_callback() {
echo '<h3>My Custom Submenu Page</h3>';
}
add_action('admin_menu', 'register_my_custom_submenu_page',99);
You need a high(er) priority number to execute it later then the `woocommerce_admin_menu` function, which has 9, and there is `woocommerce_admin_menu_after`, which has 50 - those functionbs are in `woocommerce-admin-init.php`. | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 6,
"tags": "plugins"
} |
How can I detect if the current post is in this loop?
My featured articles have been built with the following query:
$featured_posts = new WP_Query( array( 'post__not_in' =--> get_option( 'sticky_posts' ),
'meta_key' => is_featured',
'meta_value' => 1
) );
How can I detect if my current (singlepage) article is featured or not? I obviously need to query whether it has `is_featured` flag, but how do I build this query?
Many thanks. | `$is_featured_post = get_post_meta(get_the_ID(), 'is_featured', TRUE);`
This will return the value in the variable and you can check your condition.
Instead of `get_the_ID()`, you can use any post `ID`. Refer the documentation here: get_post_meta. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, featured post"
} |
Login Button CSS
I'm trying to find the Login button CSS code.
I tryed this topic, but i think the path has changed after wordpress updated:
<
Any can show me where is it? Thank you | The CSS comes from `wp-includes/css/buttons.css`. Do not change this this file; it will be overridden during the next update. Create a separate plugin instead, or add some custom code to your theme’s `functions.php`, and hook into `login_head`:
add_action( 'login_head', function() {
?>
<style>
.button {
background: red !important;
}
</style>
<?php
});
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "login, css, buttons"
} |
How to remove comment link title attribute?
When I hover over any post's comment link, I see the title: "Comment on Post Title". How can I remove it? I could not find this text in the theme.
Edit: Here's the source which generates the comments link:
<?php comments_popup_link( __('0', 'domain'), __( '1', 'domain'), __('%', 'domain')); ?> | The `title` attribute is hard-coded in `comments_popup_link()` unfortunately:
echo ' title="' . esc_attr( sprintf( __('Comment on %s'), $title ) ) . '">';
What you can do is catching the generated HTML in a variable and replacing the attribute with an empty string:
ob_start();
comments_popup_link();
print preg_replace( '~ title="[^"]+"~', '', ob_get_clean() ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, themes, comments, links"
} |
Get the content of a specific page (by ID)
I have the following front-page template made:
!enter image description here
In place of those large Lorem Ipsum blocks, I need to show an "excerpt" from a specific page to fill that box (a certain number of characters).
How do I get a pages content in String format so that I can echo it out and trim down to a certain number of characters? | <?php
// would echo post 7's content up until the <!--more--> tag
$post_7 = get_post(7);
$excerpt = $post_7->post_excerpt;
echo $excerpt;
// would get post 12's entire content after which you
// can manipulate it with your own trimming preferences
$post_12 = get_post(12);
$trim_me = $post_12->post_content;
my_trim_function( $trim_me );
?> | stackexchange-wordpress | {
"answer_score": 30,
"question_score": 20,
"tags": "pages, content"
} |
Choose to Display Post Thumbnail?
I noticed the website < does something cool with images in posts - some posts have a large featured image above the title, others have none and just have images in the content.
My best bet on how to achieve this in WordPress is to add `<?php the_post_thumbnail('large'); ?>` above the title and make a selectable option to display or not display the_post thumbnail in the post edit screen. It would need to only apply to the post (and not the excerpt)... I'm not sure how I would create that option. I would appreciate if anybody knows how this would be done, can direct me to a somewhat relevant tutorial, or has a better idea of how to achieve this. | This is modified code from `twentyten` that does what you're looking for. Put this in `header` or wherever you want the image to run. See string `post-thumbnail` \-- that is size. Make sure it is defined as `940 x 180` in `functions.php`
if ( is_singular() && current_theme_supports( 'post-thumbnails' ) &&
has_post_thumbnail( $post->ID ) &&
($image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' ) ) &&
$image[1] >= 940 ) :
// Houston, we have a new header image!
echo get_the_post_thumbnail( $post->ID );
elseif ( get_header_image() ) : ?>
<img src="<?php header_image(); ?>" width="940" height="180" alt="" />
<?php endif; ?>
It falls back to `header_image` if that is set. Feel free to change sizes. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post thumbnails"
} |
get_current_screen() inside add_action('admin_menu')
I am successfully using get_current_screen(); to get the post_type to decide whether to manipulate a meta box or not.
I also need to use it in:
add_action('admin_menu', 'infographicMetaBox');
function infographicMetaBox() {
// ...
$screen = get_current_screen();
if('post' != $screen->post_type)
return;
// ...
}
however it doesn't seem to be available in that hook function (maybe being called to early?). | I don't know exactly what you are trying to accomplish but you seem to be dealing with meta boxes. If so there are a number of meta box specific hooks.
>
> do_action('add_meta_boxes', $post_type, $post);
> do_action('add_meta_boxes_' . $post_type, $post);
>
> do_action('do_meta_boxes', $post_type, 'normal', $post);
> do_action('do_meta_boxes', $post_type, 'advanced', $post);
> do_action('do_meta_boxes', $post_type, 'side', $post);
>
>
> <
As well as the `admin_head*` hooks
>
> do_action("admin_head-$hook_suffix");
> do_action('admin_head');
>
>
> <
All of which run after `global $current_screen` is set here: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "screen options"
} |
Only Display Thumbnail if Larger Than
Is there a way to only display `<?php the_post_thumbnail( $size, $attr ); ?>` if it is larger/smaller than specified dimensions? | You may be able to make this work with a filter on `post_thumbnail_html`.
function filter_thumb_html($html, $post_id, $post_thumbnail_id, $size, $attr ) {
$dimensions = wp_get_attachment_image_src($post_thumbnail_id, $size);
if ($dimensions[1] > 500 || $dimensions[2] > 500) {
return '';
}
}
add_filter('post_thumbnail_html','filter_thumb_html',1,5);
I am not sure what you mean by "if it is larger/smaller...". I don't know if need both conditions at once, or one or the other, or if you need to change the restrictions dynamically. The code above should give you a working model though.
## Reference
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "post thumbnails"
} |
How to create a theme specific translation of buddypress?
Originally asked on the BuddyPress forums:
For distribution purposes I would like to include my customized buddypress language files in my theme alongside my other language files. No matter what I try though I can only get the language files to display if I copy them over to `wp-content/languages` as described in the buddypress codex. I thought that the following would work, but it doesn’t:
function load_buddypress_language_files() {
load_theme_textdomain('buddypress', get_template_directory() . '/lang');
}
add_action('plugins_loaded', 'load_buddypress_language_files');
This is possible isn't it?
WP: 3.5.1 BP: 1.7.2 | First, actions added to `plugins_loaded` hook will not work from theme `functions.php` or any theme file because at that point it will be already fired (too late from theme files).
What you can do is to hook your action into `after_setup_theme` and unload `buddypress` text domain first and then add your custom `buddypress` text domain file. The reason is that WordPress will not load any translation files for text domains that has already been added:
add_action('after_setup_theme', 'replace_bp_mofile');
function replace_bp_mofile() {
$mo_file = get_stylesheet_directory() . '/languages/' . sprintf( 'buddypress-%s.mo', get_locale() );
if (file_exists( $mo_file )) {
unload_textdomain('buddypress');
load_textdomain('buddypress', $mo_file);
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "buddypress, translation, theme roots"
} |
Crop featured image by default
I'm having trouble finding out how to accomplish this - I want to display a cropped version of an image in the post. So when it's uploaded, it would automatically be displayed cropped. Is there any way to do that? For example, this would be the original image uploaded and this is what it would look like in the post
Is there a way to set that cropping be default? It would be great if the user would upload the image already cropped, but if they don't, I want to have a fallback. | try this
1. define a custom image size (add_image_size)
add_image_size(name,w,h,true);
where `w` and `h` for height and width of your image.and fourth parameter true for hard croping of image.read wordpress codex for that
2. put your custom image size name in the_post_thumbnail function
the_post_thumbnail('name')
or
if your design is not responsive then you can set image size using css.
--class/id-- img{
width:w;
height:h;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails"
} |
How to get parent category ID in single page template
How can I get parent category ID in single page template, outside of loop?
$category = get_the_category();
echo $category[0]->term_id;
The code isn't working outside loop correctly. | I'm solved, by using:
$category[0]->parent
Thanks anyway. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Attachments broken after giving WordPress its own directory
I set up a fresh WordPress installation in a folder called 'wp' under root. I followed the directions for Giving WordPress Its Own Directory and pointed the URL to root successfully. I then proceeded to import some posts which had attachments to them. My uploads folder is currently set to /wp/wp-content/uploads but throughout the posts, the attachment URLs point to /wp-content/uploads.
I tried creating a symlink through the shell but that didn't work. Could someone please help me out? | Since (from what I understand) the issue only occurs to imported posts I suggest you try the plugin Search and Replace. It's a quick and easy way to solve this problem.
WP stores the uploaded images in your database. Imported images probably direct to the old root, so you should change that to the new root. Search for the string `'/wp-content/uploads'` and replace all with `'/wp/wp-content/uploads'`. Be really careful with this plugin though, it's a powerful one. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, attachments, import"
} |
New Wordpress WP Query using posts from certain categories
I want to display the last say 6 pieces of work from my portfolio. So i have written this query
<?php $the_query = new WP_Query array( 'category_name' => 'portfolio', 'showposts=6' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<?php the_post_thumbnail(); ?>
<?php endwhile;?>
Can someone advise if im missing something as it doesnt seem to be working. thanks
<?php $the_query = new WP_Query array( 'category_name' => 'portfolio', 'posts_per_page' => 6, ); ?>
This now comes up with a T Array error | There are some errors in your code, you have to change:
* `$the_query -> have_posts()` to `$the_query->have_posts()`
* `$the_query -> the_post()` to `$the_query->the_post()`
* `WP_Query array(...)` to `WP_Query(array(...))`
* `'showposts=6'` to `'posts_per_page' => 6`
Try this instead
$the_query = new WP_Query( array( 'category_name' => 'portfolio', 'posts_per_page' => 6 ) );
while ($the_query->have_posts()) : $the_query->the_post();
the_post_thumbnail();
endwhile; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query"
} |
Display custom posts in checkbox list
I am working in a WordPress backend design and I would like to know if is there any function like wp_categories_checklist but for posts.
I have an issue here: < in order to find a multiple selection of my dropdown. So if is there any way to put my posts array in a meta box like the custom categories from WordPress that would be great.
Thanks | {// post_list
case 'post_list_produktkrav':
$items = get_posts( array (
'post_type' => $field['post_type'],
'posts_per_page' => -1
));
foreach($items as $item) {
echo '<input type="checkbox" value="'.$item->ID.'" name="'.$field_related['id'].'[]" id="'.$item->ID.'"',$meta_related && in_array($item->ID, $meta_related) ? ' checked="checked"' : '',' />
<label for="'.$item->ID.'">'.$item->post_title.'</label><br />';
} // end foreach
break;} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom field, array"
} |
418 header status, I'm a teapot
I'm just backing up a clients via ftp site prior to working on it, when suddenly all urls are returning an error page with the header status being `418`.
A quick Google finds that this was created for an April Fools joke. Does any body have any idea why I would be getting this error? | You were right Toscho, it is a plugin called 'better WP-Security'
I did a search for '418' as suggested in the files I had backed up via ftp and found this:
$bwpsmemlimit = (int) ini_get( 'memory_limit' )
//if they're locked out or banned die
if ( ( $bwpsoptions['id_enabled'] == 1 ||$bwpsoptions['ll_enabled'] == 1 ) && $this->checklock( $current_user->user_login ) ) {
wp_clear_auth_cookie();
@header( 'HTTP/1.0 418 I\'m a teapot' );
@header( 'Cache-Control: no-cache, must-revalidate' );
@header( 'Expires: Thu, 22 Jun 1978 00:28:00 GMT' );
die( __( 'error', $this->hook ) );
}
So I presume as because I was backing up the site via ftp, the security plugin must have locked me out due to so much traffic. After 10 mins I could get back on the site again. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "errors, server, post status"
} |
Visual Editor not working when Jetpack plugin is active
After installing the Jetpack plugin, the visual editor stopped working. The Visual tab is still there but the editor area is empty and the toolbar is missing.
I have deactivated all other plugins and the problem is still present. (The only other one was Restricted Site Access). Disabling Jetpack (or disconnecting it from Wordpress.com) fixes the problem, but I would like to use some functionality from Jetpack.
Has anyone else seen this problem, and is there a fix? Is it a particular Jetpack configuration that causes this? I saw several complaints online, but not fixes. | I just had the same problem using Jetpack v3.3 on < I deactivated the whole jetpack plugin and the features came back, reactivated the plugin and was fine, until I connected it to my wordpress site < and they went away again. I deactivated spell-check setting but that didn't resolve. I deactivated the Shortcode Embed feature and then it was functioning again.
FYI - this still causes problems in future releases but try deactivating the shortcode embed feature and that should resolve the problem. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "visual editor, plugin jetpack"
} |
Does Wordpress check for updates of a plugin via plugins root folder name?
I just completed writing a plugin from another plugin. When I changed the developer name, version and other details from the plugin file, I thought the version tracing would now be done using the new name of the plugin but it actually linked the update to the older plugin until I changed the root folder name for the plugin. Wasn't the update supposed to be happen from the details provided in the file? Please guide. Thanks | WordPress uses the 'plug-in slug' to identify a plug-in (and uses this as an 'id' for plug-in updates, though its not clear how, as the code isn't published). The plug-in slug is determined by the location of the `.php` file header containing the comment header necessary for plug-ins. (see source)
So if your main plug-in file is `...wp-content/plugins/pluginA/pluginA.php` your plug-in slug is `pluginA/pluginA.php`, and will by default check for plug-in updates using that slug.
So to give your plug-in a different slug its necessary to change the name of the plug-in file/directory.
Of course its also possible to just prevent your plug-in from checking for updates or change where it looks (e.g. Have WP Theme update from Git Repository). (This is not allowed for repository-hosted plug-ins). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, version control"
} |
When to use the Filesystem API? Should I use it at all?
I'm wondering when it is recommended to use the Filesystem API, and whether it's useful at all?
WordPress seems a little inconsistent when it comes to Filesystem API usage, it uses the API only in a few places when uploading and unpacking files, and that doesn't make much sense to me, I mean, where's to point in using it at all when there are a lot of other situations where the PHP filesystem functions are used for direct access? Uploading packages would work even when there are ownership "problems", however I'm pretty sure that these "problems" won't go away 5 minutes later when I'm utilizing any of the functions that are using for example fwrite directly.
So why should I as a plugin/theme developer care about it anyways when half of the WordPress functions I'm using does not rely on the Filesystem API, my plugin/theme wouldn't work correctly anyways, wouldn't it? | There is a bit of practical split about where WP can write files and if `Filesystem API` is invoked. It might be easier to see this divide not as technical, but as administrative.
There is **user** space.
Users _must_ be able to do things like create attachments and _must not_ need to have admin access credentials.
For these requirements uploads directory typically requires lax permissions and code that works with it is usually _not_ using `Filesystem API`.
Rest is **admin** space.
Administrators/developers _must_ be able to (over)write anything (plugins, themes, WP core itself) and _have_ admin credentials.
For such functionality code _is_ using `Filesystem API` and will prompt for credentials, if it can't accomplish task without them.
So rule of a thumb for development distributable code is roughly - uploads directory is _one and only_ place in WP installation where you can expect to perform writes without using `Filesystem API`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp filesystem"
} |
Can a plugin be run in a different language than WordPress?
I am working with a site that is running WordPress in English, but they would like to run one of their plugins using the Welsh language. We already have the appropriate .po/.mo files for the plugin, but they are not being used while WordPress is running in English. Is there any way, perhaps with some custom PHP code in the plugin, that we can force WordPress to use the Welsh language files just for this plugin, but leave the rest of the site in English? | Assuming the plugin makes use of localization at all, you could for example try exchanging the possible `load_plugin_textdomain` call with `load_textdomain` where you can point to the file you like.
A cleaner way would be using the `plugin_locale` filter that let's you modify the locale used by a plugin:
function my_plugin_locale_filter($locale, $domain)
{
if($domain === 'the_plugins_textdomain')
{
return 'cy_CY';
}
return $locale;
}
add_filter('plugin_locale', 'my_plugin_locale_filter', 10, 2);
That way the plugin can more or less safely be updated without the custom code being overwritten. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, language"
} |
How/Where is editor.min.js Added to the wp-admin Post Page?
How/Where is the `wp-admin/js/editor.min.js` file added to the backend WordPress post editing page (`wp-admin/post.php`)? How could I change this to use the non-minified file?
I'm working on a browser extension that will interact with a WordPress installation. I'd like to add some temporary debugging code the the `editor.js` file. However, in a standard WordPress 3.5.1 site, this file is already minimized, and somehow loaded on the page via a mechanism that isn't a standard `<script/>` tag. I'd like to know how the WordPress core team includes (and/or a minimize workflow for) this file.
Put another way, if I wanted to add a feature that required changing `editor.js`, how would I go about developing that.
Competent programmer here, not super familiar with WordPress's architecture. In case my words failed me above, I'm not looking to extend WordPress, I'm trying to diagnose existing system behavior.
Thanks in advance! | WordPress concatenates scripts via the `script-loader.php` file.
You can disable the concatenation of scripts by adding this to your `wp-config.php`:
define('CONCATENATE_SCRIPTS', false);
You can load the non-minified versions by adding this to `wp-config.php`:
define('SCRIPT_DEBUG', true); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "javascript, editor"
} |
an action hook when a post reaches a certain number of views
I am using WP Post Views plugin to display the post number of views. I use:
<?php if(function_exists('the_views')) { the_views(); } ?>
I am creating a badge system for my wordpress site. My actual goal is to create a badge for number of post views: If a post has a number of views exceeding a certain threshold, then the author is awarded this badge.
How can I achieve this using action hooks? Till now, all the badges I have created use the priciple of action hooks (For instance, the badge related to the number of an author published posts uses post_publish action hook). Should I look for another approch for the views badge other than hooks?
Thank you for your help. | Use the action from `update_post_meta()`:
do_action(
"updated_{$meta_type}_meta", // example: updated_post_meta
$meta_id,
$object_id, // post ID
$meta_key, // 'view'
$_meta_value // view count
);
Something like this should work (not tested):
add_action( 'update_post_meta', 'badge_check', 10, 4 );
function badge_check( $meta_id, $post_id, $key, $value )
{
if ( 'views' !== $key or 1000 > $value )
return;
$user = wp_get_current_user();
if ( ! $user->ID )
return;
update_user_meta( $user->ID, 'badge', 'Kilo viewer' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, hooks, publish, views"
} |
How to reduce spam
I installed WordPress along with a few add-ons to combat spam. Both are for registered and non-registered members posting comments. I added a standard Captcha as well as a mathematical challenge question (5 + what = Eleven). I have tried different Things and software, but the result is the same. I receive daily spam emails.
It serves the spammer no good, as I review all comments, but that does not stop comments.
Do spammers now have humans go to the same website daily and try to just sent out spam (unlikely) or is it just a software program. In the latter case, why is the WordPress add-ons not stopping spam comments.
Do others have the same issue? Did I miss something, when setting up WordPress? | Use these three plugins in combination:
* Cookies for Comments
* Simple Trackback Validation
* Akismet
Ditch the captcha and math plugins, they're pretty much useless. The combination of these three is enough for most anybody, without having to put any problems back on the user. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "spam"
} |
Link to blog index from template
I can't believe I did not find the right function for this: I just want to retrieve the blog index url from a template.
My homepage is a static page. I am not looking for bloginfo('url') because it gives me my root url (/). I am looking for mysite.com/Blog
I am thinking about getting it via get_permalink($mypageid) but it is a bit dirty. | if you are referring to the 'posts page' as set under **_dashboard - settings - reading_** :
<?php
if( get_option( 'page_for_posts' ) ) {
echo get_permalink( get_option( 'page_for_posts' ) );
} else {
echo home_url();
}
?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "permalinks, templates"
} |
Why do I get undefined function export_wp()?
I'm trying to create a function in `functions.php` or a plugin to generate an export via a cronjob, similar to how Chris_O did this question. However it seems that I can't call `export_wp()`, I keep getting:
Fatal error: Call to undefined function export_wp() in wherever-I-call-it-from.php on line 686
Can someone tell me how to call that function? | The function lives in `wp-admin/includes/export.php` and is only included on the export admin page (see source).
If you want to use it on other pages, you'll have to include it manually:
require_once( ABSPATH . 'wp-admin/includes/export.php' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, export, filesystem"
} |
How to show multiple post types on taxonomy archive?
On a taxonomy archive, how does one create multiple loops for different post types that share that taxonomy? I'm using taxonomy-themes.php so that it applies to all three of the terms in the 'themes' taxonomy (climate change, governance, peace building).
On each term's archive page, I want to output the main taxonomy loop (posts), and then I want to create loops for each of 'events', 'resources' and 'staff' (all of which are custom post types). I'm assuming that I create new wp_query for each of the post types, but how do I tell that query which term I want it to get 'events' from (ie. the current archives' term)? | As you point out, if you want separate loops for different post types you'll need to use a separate `WP_Query()` for post type. In the template you can get the current term (ID) being viewed via: `get_queried_object_id()` (see source)
$args = array(
'post_type' => 'staff',
'tax_query' => array(
array(
'taxonomy' => 'themes',
'terms' => get_queried_object_id(),
'field' => 'id'
)
),
);
$staff = WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, custom taxonomy, archives"
} |
How to purge all transient caches?
Is there an easy way to delete all transient caches? A plugin maybe? Or like in drupal "drush cc all"? | Install < and use the command
wp transient delete --all | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "cache, transient"
} |
replace wp_get_attachment_image with my own function
How can I replace wp_get_attachment_image() function without changing the core files. The function doesnt have an action hook or a filter hook.
**What I am trying to achieve:**
for lazyload plugin output the image html like this:
<img width="150" height="150" data-src=" class="attachment-thumbnail" alt="calliope.slide" src="
instead of this:
<img width="150" height="150" src=" class="attachment-thumbnail" alt="calliope.slide"> | There is a filter, `wp_get_attachment_image_attributes`, for the image attributes-- a well designed one too.
function alter_att_attributes_wpse_102079($attr) {
$attr['data-src'] = $attr['src'];
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'alter_att_attributes_wpse_102079');
That will add the `data-src` attribute. That looks like what you need. You could add more attributes, or alter the existing onese, if you need. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "images"
} |
How to remove certain words from url slug
Trying to create a SEO plugin, that will remove stop words from slugs.
This is how to `explode` the `$slug` into a list, and explode the variable containing the stop words :
add_filter ('sanitize title', 'remove_false_words');
function remove_false_words($slug) {
if (!is_Admin()) return $slug;
$slug = explode ('-', $slug);
foreach ($slug as $key => $word) {
//The $slug has been exploded and retrieves its value
$keys_false = 'a,above,the,also';
$keys = explode (',', $keys_false);
foreach ($keys as $1 => $wordfalse) {
if ($word == $wordfalse) {
unset ($slug[$k]);
}
}
}
return implode ('-', $slug);
}
Is it correct to `unset` the value here? Or should I use a different way of achieving the same result? | There should be no problem with `unset`. There is your answer. What matters with a filter is what you return and `unset`ing those keys before your rebuild the string and return it, works.
You are doing too much processing by `explode`ing your `$keys_false` inside a loop, and you have a typo, and you are better off just making an array instead of creating a string that you convert to an array, and PHP has a function to do what your loop is doing. I reorganized it for you.
function remove_false_words($slug) {
if (!is_admin()) return $slug;
$keys_false = array('a','and','above','the','also');
$slug = explode ('-', $slug);
$slug = array_diff($slug,$keys_false);
return implode ('-', $slug);
}
var_dump(remove_false_words('a-boy-and-his-dog')); // proof of concept | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "slug, php"
} |
How to retrieve taxonomy terms of the current custom post?
I have a custom taxonomy _worktype_ and I have 3 types in this latter custom taxonomy: \- creation \- collaboration \- lab
I have also a custom post type "works". _worktype_ is used only for the custom posts type _works_
I have single-works.php as a template and everything is ok
BUT, I need to retrieve the worktype of the current single post. How can I do that ?
(the final idea: build a breadcrumb like that > ; in order to navigate a bit better) | Use `get_the_terms( $post, $taxonomy )`:
$worktypes = get_the_terms( get_the_ID(), 'worktyp' );
var_export( $worktypes );
You can also use …
get_the_term_list( $id, $taxonomy, $before = '', $sep = '', $after = '' );
… to get a formatted output. Example. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, wp query, breadcrumb"
} |
Do plugin files have to follow a specific convention to be "picked up" by WordPress?
I developed a plugin using the normal convention of naming the main plugin file after the plugin folder (i.e. `prefix-someplugin` for the folder and `prefix-someplugin.php` for the file). However, I saw some plugins that use the following structure:
prefix-someplugin
- plugin-loader.php // This file just loads src/prefix-someplugin.php
- /src
- prefix-someplugin.php
Obviously, if they used such structure, it means that it works. The issue is that I'm not sure **how** it works, hence my question. How does WP know which file to load as the main plugin file? I would have assumed that it looked for a file named after a folder, just adding `.php` as an extension, but it seems I was wrong.
Does WPjust scan `wp-content/plugins` for folders, and loads all the files it finds in them, or does it follow a different logic?
Thanks in advance for the answers. | WordPress detects a file as _plugin_ when there is a plugin header. So you can store multiple plugins in one directory, and they all will be recognized as different plugins.
Each file with at least `/* Plugin Name: something */` is a plugin.
The reason is that WordPress scans all PHP files in the main directory of a plugin.
You can use any name for the plugin file. Avoid non-plugin files in the main directory. They just eat runtime. Put all other PHP files into sub-directories. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 8,
"tags": "plugins, plugin development"
} |
Including files in Child Themes
Twenty Thirteen uses the following in functions.php: `require( get_template_directory() . '/inc/custom-header.php' );`. When I copy /inc/custom-header.php to twentythirteen-child, it isn't replaced. I can't use `require()` because two copies will be included. How this should be handled? | `get_template_directory` looks in the parent theme for files.
> In the case a child theme is being used, the absolute path to the parent theme directory will be returned. Use get_stylesheet_directory() to get the absolute path to the child theme directory.
>
> <
This file is not meant to be replaced. You will need to find another way to do what you need to do.
Perhaps remove the function hooked here and add your own? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp enqueue script, child theme, wp register script"
} |
Including style.css in Child Theme
Twenty Thirteen uses `wp_enqueue_style( 'twentythirteen-style', get_stylesheet_uri() );` in functions.php.
Wheter I use it or not use it in twentythirteen-child/functions.php the style.css from Child Theme is loaded (it is always loaded) and style.css from parent theme can never be loaded.
This is an exception to other files added via `wp_enqueue_style()`, right? It doesn't behave like all the other scripts and style files that are added with `wp_enqueue_script()`.
So, I can't load parent's style.css in the child theme other than via `@import`? | `get_stylesheet_uri` will return the current theme's stylesheet-- the _child_ stylesheet if it is a child theme. While not entirely clear from the Codex entry for that function, it is clear from the entry for `get_stylesheet_directory_uri`, which is used by `get_stylesheet_uri`. What should be happening is that the child stylesheet is being `enqueue`d twice under different slugs.
To get the parent stylesheet you need to enqueue the parent sheet with `get_template_directory_uri`, which always returns the parent. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp enqueue script, child theme, wp register script"
} |
Modular CSS and JS in Child Themes
Let's assume that twentythirteen/shortcodes/ exists and inside are folders with shortcodes. 1 folder = 1 shortcode. Each shortcode has: 1 PHP file, 1 CSS file, 1 JS file.
twentythirteen/shortcodes/load.php exists that does `scandir()` and `wp_enqueue_script()` for each JS and CSS file. Furthermore, it has an option to generate twentythirteen/shortcodes/style-cache.css and enqueue only this one (or all JS and CSS files individually).
The structure described above makes it very neat and modular but this will not work with Child Themes? Is there any way to make it work like that? It makes a lot of sense to have 1 folder with 1 CSS file, 1 JS file and 1 PHP file for each shortcode, don't you think? | Putting aside the question of what should and should not be part of a theme, I don't see why something like this wouldn't work with a child theme. Use `get_stylesheet_directory`, which will return the child theme path if it exists and otherwise will return the parent path, to build the path for `scandir` and I don't see the problem. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue script, child theme, wp register script"
} |
Count post + add number =
I'm having problems with counting posts of a custom post type called 'projects' and like to add a number to the count. We did some stuff which can't be shown in our portfolio but would like to add only as number.
Basically it goes as follow:
There are 22 published projects (custom posts type called 'projects') + 11 other projects (no posts) = echo 33 projects.
Edit:
I'm using this to get the wordpress counts:
<?php
$count_posts = wp_count_posts('projects');
$published_posts = $count_posts->publish;
?>
<?php // echo $published_posts ?>
How do I get this working?
Thanks in advance. | If you want to count posts of some custom post type, you can try out the WordPress function `wp_count_posts()`
In your case the custom post type is `'projects'` so you might try this:
$count_projects = wp_count_posts( 'projects' );
$published_projects = $count_projects->publish;
$total = $published_projects + 11; // include your additional projects
You can read more about this function in the Codex here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "count"
} |
Notice: Undefined index: suppress_filters
I'm doing some de-bugging on a theme I'm working on and I'm hoping someone can help me please.
I used this function that Justin Tadlock made to display custom post types on the blog page and with wp-debug set to true I get a Notice: Undefined index: suppress_filters message.
The code is as follows:
// Custom Post Type for the public blog posts to show on Index or blog page
add_filter( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query ) {
if ( ( is_home() && false == $query->query_vars['suppress_filters'] ) || is_feed() )
$query->set( 'post_type', array( 'news', 'attachment' ) );
return $query;
}
If anyone could help that would be great. Thanks | If `$query->query_vars['suppress_filters']` is not set you will get that message.
Use `empty($query->query_vars['suppress_filters'])` instead of `false == $query->query_vars['suppress_filters'] )` or use `$query->get('suppress_filters')` like this `false == $query->get('suppress_filters')`.
Untested (minimally tested) but I believe either of those should give you the same results minus the notice. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, posts, functions, homepage, wp debug"
} |
Undefined offset: 2
I'm using this function I found from this answer here about showing prev/next navigation for a current page
<?php
$pagelist = get_pages("child_of=".$post->post_parent."&parent=".$post->post_parent."&sort_column=menu_order&sort_order=asc");
$pages = array();
foreach ($pagelist as $page) {
$pages[] += $page->ID;
}
$current = array_search($post->ID, $pages);
$prevID = $pages[$current-1];
$nextID = $pages[$current+1];
?>
and I get an Undefined offset: 2 error with wp-debug set to true.
Could anyone help please- sorry I am a bit of a beginner with some of this, but I think it refers to the last 2 lines with $prevID and $nextID. Thanks | You will have those notices, if either of those `$pages` indexes are not set. Check for the existence of the key before trying to use it.
if (isset($pages[$current-1])) $prevID = $pages[$current-1];
if (isset($pages[$current+1])) $nextID = $pages[$current+1];
Or something along these lines ...
$prevID = (isset($pages[$current-1])) ? $pages[$current-1] : '';
$nextID = (isset($pages[$current+1])) ? $pages[$current+1] : '';
... so that you don't have other notices later when you try to use those variables. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, navigation, wp debug"
} |
How to oEmbed from custom field, responsive to container size and responsive
I am using Magic Fields 2 to add custom fields/meta boxes.
One custom field is for a Vimeo or YouTube video URL to be displayed.
The following code oEmbeds the video URL:
<?php if (!((get_post_meta($post->ID, 'video_url', TRUE))=='')) {
echo wp_oembed_get( get_post_meta($post->ID, "video_url", true) );
}?>
To resize the video, I have used added the code inside `<div class="video">` and resized it using CSS - `.video iframe {width:500px;height:312px}`.
The problem, this method is not responsive.
I have also tried `.video iframe {width:95%;height:95%}`. This outputs looks like -
!enter image description here
The Fluid Video Embeds plugin seems to do the job for oEmbeds through the normal WordPress method and through shortcode, but not with using a custom field. | I completed the task with fitvids.js by using the plugin FitVids for WordPress.
Chris Coyier describes the integration with WordPress in his screencast Integrating FitVids.js into WordPress (on YouTube).
My custom field name is `video_url`. I used the following code in my template:
<?php if (!((get_post_meta($post->ID, 'video_url', TRUE))=='')) {
echo wp_oembed_get( get_post_meta($post->ID, "video_url", true) );
}?>
In the settings of FitVids for WordPress, simply enter the containing div class or ID which represents the maximum width of the video.
!enter image description here
For those who need it, Integrating FitVids.js into WordPress screencast shows how to check the theme for jQuery and for the proper CSS selector. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "custom field, responsive, oembed"
} |
Add class name to post thumbnail
I'm using post thumbnails to link to a page.
Is it possible to add a class name to the post thumbnail image.
<li><a href="<?php the_permalink(); ?>" ><?php the_post_thumbnail(); ?></a></li> | Yep - you can pass the class you want to use to `the_post_thumbnail()` as part of the attributes argument, for example `<?php the_post_thumbnail('thumbnail', array('class' => 'your-class-name')); ?>`
Ref: < | stackexchange-wordpress | {
"answer_score": 63,
"question_score": 26,
"tags": "post thumbnails"
} |
Define constant for one plugin in mu-plugin
I'm trying to define the constant `ACF_Lite` as `true` so that the interface of the Advanced Custom Fields plugin is hidden on all of my multisite subsites except the parent. For clarity and maintainability, I'm wanting to do this from an `mu-plugins` plugin that will also control the fields displayed by that plugin.
I thought this would do it but it didn't:
if( get_current_blog_id() !== 1 )
define( 'ACF_Lite', true );
The plugin author says that this needs to be in `wp-config.php`, but I'm surprised that this doesn't work because, according to the codex, mu-plugins are:
> Loaded by PHP, in alphabetical order, before normal plugins,
I've confirmed that `get_current_blog_id()` returns the right ID, so that's not the problem. I've also tried explicitly hooking that to `muplugins_loaded` and `plugins_loaded` but that has failed.
Can anyone explain why I can't define this from `mu-plugins`? | @toscho's link solved this. PHP constants are case sensitive.
ACF uses `ACF_LITE`, you are using `ACF_Lite`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, advanced custom fields, constants, mu plugins"
} |
Permalinks is not working in my wordpress setup
I am newbie to wordpress. I have created a site using wordpress and WAMP stack. In my Apache i have enabled **mode_rewrite** , so my site is showing permalinks perfectly.
Now i have hosting provider of .NET and IIS server. So when i migrated my site to live server it is working fine without permalinks. But when i type using raw url like www.example.com/?p=12 it is working fine. So how can i make it work with IIS just like Apached did..
Is there anything in IIS like **mode_rewrite** in Apache | Thanks to @rofflox and @toscho for giving me the link. web.config file was not created as i was working on localhost as WAMP i.e Apache and it required when i shifted to production as it was running IIS.
So i created a blank web.config file and added the following content.
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
This helped me to accept permalinks perfectly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "permalinks, mod rewrite, iis"
} |
Add metabox without the container
I want to add a second input identical in design/functionality to the Title text input, directly beneath it.
I can use
add_meta_box('catchy_title', 'Short Title', array('catchyTitle', 'metaBoxShow'), 'post', 'normal', 'high');
And the content
<div id="titlewrap">
<label for="catchy_title" class="">Enter shorter title here</label>
<input type="text" autocomplete="off" id="catchy_title" value="'.$meta.'" size="20" name="catchy_title">
</div>
However this puts a grey metabox around it. Should I even be using a metabox? I basically want to duplicate this field:
!title
but I end up with
!wrong
and it's under the rich text editor too.
Here is the full code if it helps: < | Use the action `edit_form_after_title`.
Example:
add_action( 'edit_form_after_title', function() {
echo 'Enter some text: <input type=text>';
});
!enter image description here
See this answer for another example. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "metabox"
} |
Can I turn off further comments on a single page?
I have a blog post with comments on. I want to stop all people posting any further comments but keep the ones that are currently there. How do I do that? Using Wordpress 3.5.1 | You can change the setting in the **Discussion** post meta box:
!Discussion meta box with comments disabled
_(If you can't see this meta box on your post edit screen, go to the Screen Options tab and check the box next to 'Discussion')_
Changing this setting **will not delete existing comments**. It will just turn off the ability to comment as long as the setting is disabled. It only applies to the post you change the setting for. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments"
} |
How can I highlight syntax like it appears on stackoverflow?
Suppose I am writing a post and want to highlight only a couple of characters: `like this`. How can I achieve this? | HTML language includes a special tag for displaying inline code. To apply it to your text, switch to the 'Text' visual editor tab and place the `<code>` tag before your bit of code, and the `</code>` tag afterwards.
If you want to use the backtick ` character for highlighting code like you do on Stack Overflow, check out this plugin by Tom McFarlin. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "posts, syntax highlighting"
} |
Create placeholder text for wordpress search box
I need to create a search box in my default searchform.php file that has similar behaviour as the default ability in HTML5 with the "placeholder" attribute.
This is what I have in my searchform.php at the moment:
<input type="submit" id="searchsubmit" value="text" />
<input placeholder="<?php _e( 'Search here..' ); ?>">
The text 'Search here..' appears in the input and it dissapeard when I start typeing in the input. I need it to dissapear when I click the input.
Thx | Placeholder by itself will not disappear when you click the text field. I guess you need a bit of Javascript to achieve that.
<input type="text" onfocus="if(this.value=='<?php _e( 'Search here..' ); ?>'){this.value='';}" onblur="if(this.value==''){this.value='<?php _e( 'Search here..' ); ?>';}" value="<?php _e( 'Search here..' ); ?>"> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "php"
} |
header specific meta box result detect url
I've got 3 header.php files and 1 detects whether their either on page 1 or page 2. I have a custom meta box thats outputting the results onto each header - that all works fine.
However when I go a page deeper the meta box information isn't showing, I've tried various if statements but nothing shows up.
Any help would be great.
my header output looks like:
<?php
global $post;
$header_meta = get_post_meta($post->ID, 'page-header-meta', true);
if( isset( $header_meta ) ) {
echo '<h1>' . $header_meta . '</h1>';
}
else {
echo '<h1>Knowledgebase</h1>';
}
?> | global $post;
$header_meta = get_post_meta($post->ID, 'page-header-meta', true);
if( isset( $header_meta ) ) {
echo '<h1>' . $header_meta . '</h1>';
}
else {
echo '<h1>Knowledgebase</h1>';
}
What this portion of code does is it checks the 'page-header-meta' value according to the page being displayed. IF your parent page has the metavalue set then the header will display. Similarly for the child pages also you need to set the meta value to display the particular header. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "metabox, custom header"
} |
Sharing Buttons not Working - Sharing Settings
I'm trying to add a "share this" button to my site. I am having an issue configure this because when I go to settings -> sharing I get the image below!enter image description here
Update: Here is my inspector error console:!enter image description here
Uncaught SyntaxError: Unexpected token < /?ver=2:1
Uncaught SyntaxError: Unexpected token < /?ver=3:1
JQMIGRATE: Logging is active s0.wp.com/:9823 | If you experience such issues, examine the source code of the page, and search for the stylesheet used by Jetpack on the page:
You want to make sure that this URL can be accessed; if you use a caching service or plugin or if you have added redirection rules that impact this page, you will experience issues. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "options, plugin jetpack, sharing"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.