INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to remove date, author and comment count from Chameleon search results page
I would like to remove the following from the search results page, I'm using the ET Chameleon theme which doesn't have a search.php file in the editor section. Any help greatly appreciated.
Posted by auscov on Feb 22, 2013 in | 0 comments | If the theme doesn't have a `search.php` file, `index.php` will be used.
> ### Template_Hierarchy
>
> Template file used to render a Search Results Index page
>
> 1. **search.php**
> 2. **index.php**
>
_[update]_
Use the following to print the current template being used to render a page:
add_filter( 'the_content', 'so_9405896_the_content_filter', 20, 1 );
function so_9405896_the_content_filter( $content )
{
if( is_admin() || !current_user_can( 'delete_plugins' ) )
return $content;
global $template;
$the_templ = '<strong style="background-color: #CCC;padding:10px">TEMPLATE = '
. basename( $template ) . '</strong><br />';
$content = sprintf( $the_templ . '%s', $content );
return $content;
}
Which results in:
> !output template name to content | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, search"
} |
post_count not working
I've fixed my initial problem but I'd like to know what I was doing wrong.
<?php
$args = array(
'post_type' => 'page',
'post__not_in' => array( $post->ID ),
'post_parent' => '43',
'post_count' => '3',
);
$my_related_posts = new WP_Query( $args );
?>
Displays 4 results, where I expected 3. I fixed the problem by doing:
<?php
$args = array(
'post_type' => 'page',
'post__not_in' => array( $post->ID ),
'post_parent' => '43',
'post_count' => '3',
'posts_per_page' => '3'
);
$my_related_posts = new WP_Query( $args );
?>
But what was I doing wrong? Changing post_count seemed to have little or no effect. Thanks | `post_count` is not a parameter of WP_Query argument.
`post_count` is a property used to get the number of posts being displayed. For example, `echo $my_related_posts->post_count;` will display the number of posts being displayed. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": -1,
"tags": "posts, count"
} |
Too many login attempts
Since a week or two I keep receiving the following automatic email message sent from my WordPress website, and I'd like to know if it indicates any security hole and if there's anything I can do to stop it :
"A host, 79.148.238.85(you can check the host at < has been locked out of the WordPress site at < until Friday, February 22nd, 2013 at 9:41:54 am UTC due to too many login attempts. You may login to the site to manually release the lock if necessary." | It looks like you have the plugin `Better WP Security`
<
installed with the `Enable login limits` feature activated here `/wp-admin/admin.php?page=better-wp-security-loginlimits`. You can configure the plugin to stop sending you these messages. But you should have the feature activated, since most likely some **bot** is trying to login. Or even consider to blacklist this IP in the plugin via the `Ban` page in `/wp-admin/admin.php?page=better-wp-security-banusers` (if you are sure this is not an actual user in your Wordpress trying to login)
ps: I get these messages a lot and on some installs I use the `htpasswd` to stop the bots from accessing the wp-login page ;-) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, login, security"
} |
Permalinks that go to a specific template
This is actually my first question here, so hello to everybody in this community!
I have developed a theme with a custom post type and a template (lets call it "my_template.php") that shows posts of this custom post type in an archive-like fashion.
What I'm trying to achieve is to make a permalink in the navigation of the site that goes to a specific template (like "my_template.php") and ignoring the wp template hierarchy.
How could one do that?
Note: I've already checked out This answer, but that one didn't really help and provided only a workaround.
Thanks! | You could see if a custom page template fits your needs. Create a Page with the desired permalink, then set its page template to "my_template.php", and you're good! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, custom post type archives"
} |
Plugin won't activate, fatal error (widget class not found)
I've been putting together a simple WordPress plugin that employs a sidebar widget and shortcode. One user has reported the following error when trying to activate the plugin on their local WP installation:
> Plugin could not be activated because it triggered a fatal error.
>
> Fatal error: Class 'Example_Widget' not found in /Applications/MAMP/htdocs/wordpress/wp-content/plugins/exampleplugin/exampleplugin.php on line 30
Here's the code in `exampleplugin.php`, beginning with line 29:
$example_plugin = new Example_Plugin;
$example_widget = new Example_Widget;
class Example_Plugin {
...
}
I'm fairly new to OOP in PHP, and can't figure out what's causing a fatal error for this user. The plugin works fine for me, making this all the more mysterious. | You should not need to instantiate the widget class at the top of your code, because of the register_widget function hooked from your main class does that work for you.
EDIT: Wordpress already instantiates your class. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, widgets, errors, fatal error, oop"
} |
WordPress Page Reload Takes forever during theme development
OK, I'm hacking my way through my first theme (while reading Prof. WP Design & Development 2nd Ed.) and ....
EVERY TIME I change -for example- a p tag or a div tag or a css rule, when I then go to reload the page to see changes ... I....wait....and....wait.... for the dang page to reload!?!
I'm seeing "cache issue", but I'm unsure of exactly what that means, so I'm not sure that IS my problem.
IF this is a cache issue, can someone please explain exactly _what is going on under the hood_ during the reload? And just what I can do about it?
Can someone break this down a bit for the noobs. :)
thanks, sleeper | From the comments above, it seems the problem is caused by a plugin. You can try to search for the error message (cache issue?) within the plugin files. Some editors and IDEs have a function "file search" which searches in every file. E.g. in Notepadd++ you can do a file search by hitting [ctrl]+[f].
If you found the error message, deactivate the plugin and install an alternative plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, theme development"
} |
Remove .htaccess portion upon plugin deactivation?
I have a plugin that inserts some rewrite rule in the .htaccess file. However, upon deactivating it, doesn't remove said rule. The rule is nested in `# BEGIN My plugin` and `# END My plugin`.
I want to create an uninstall.php file for this plugin to remove the rule created on acrivation.
I've never done this before. I suppose I can get the .htaccess with
$htaccess = dirname(__FILE__) . '/../../../.htaccess';
should I use a regex or is there a proper way to remove a specific rule from the .htaccess? | How do you add your rewrite rule?
If you are adding it manually (opening the .htaccess and adding the lines by yourself in php) then you are also supposed to remove it manually. As you suggested the best way would then be to use regex.
If the rewrite rule was added through the Wordpress API using add_rewrite_rule() you are able to remove it using flush_rewrite_rules(). You could use it like this:
register_activation_hook( __FILE__, 'myplugin_activate' );
function myplugin_deactivate() {
global $wp_rewrite;
unset($wp_rewrite->non_wp_rules['the-string-you-passed-as-param-to-add-rewrite-rule']);
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'myplugin_deactivate' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, plugin development, htaccess, rewrite rules, uninstallation"
} |
admin-ajax.php loading many times
My site is running slow, because the file "admin-ajax.php" is loaded many times. see screenshot here: <
Here the functions.php file: <
How can i disable the file on the frontend and why is it loaded so many times?! Can i reduce it to only ONE time?
Thanks! | For everybody else: It has been the plugin zilla-likes in combination with the Hoarder Theme. I deactivated the plugin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, wp admin"
} |
Nonce check causing issues when creating new post
I have created a new custom post type and some custom fields for it. My function for saving the custom meta fields fires on the 'save_post' hook.
The problem is that I am getting a warning when I go to add a new post:
Notice: Undefined index: my_meta_box_nonce....
// verify nonce
if ( ! wp_verify_nonce( $_POST[ 'my_meta_box_nonce' ], basename( __FILE__ ) ) )
return $post_id;
When I enter the post details and hit publish the error is not displayed, it's only there when I create a new empty post. What's wrong here?
My code is almost identical and based on this tutorial: <
In the comments of that tutorial it seems that there were others who had the same problem, but there is no solution given. | I know that this is not the only tutorial that has code that check nonce for meta boxes but this is truly idiotic. Nonce should be checked per the whole action not per parts of it and if your save_post hook was called it means that the save nonce was already checked and found valid, so There is no need for more security checks.
My advice is to simply remove anything related to nonce from your metabox code, but if you will feel better having it around just change the code to
// verify nonce
if ( !isset($_POST[ 'my_meta_box_nonce' ]) || !wp_verify_nonce( $_POST[ 'my_meta_box_nonce' ], basename( __FILE__ ) ) )
return $post_id;
which will bail out when no nonce was supplied or the nonce failed validation | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "nonce"
} |
Better WP Security : dashboard doesn't work any more
Just installed Better WP Security (with File Change Detection feature activated), then logged out. Now wp-login.php is blank with the message :
Notice: unserialize() [function.unserialize]: Error at offset 0 of 93 bytes in /home4/mysite/public_html/wp-content/plugins/better-wp-security/inc/secure.php on line 20
What can I do do access the dashboard again? | Rename the directory in which the plugin resides to disable it | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "plugins"
} |
Preset categories in wordpress by GET-paremters
I tried google and used #wordpress.
Is there a way to preset categories for my new posts (post-new.php) via GET-parameters? If not how can I achieve this? | Dublicate question. But I think my question + link will help some ppl out.
How to add category to: 'wp-admin/post-new.php'? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, posts"
} |
How can I get the Jetpack Image plugin to open links in a new window?
The Jetpack image widget does not offer a target option for links. Is there a way to open all Jetpack image widget links in a new window without hacking the plugin? Like through a hook or function? | There is no hook available in the plugin.
One solution is to simply copy this Jetpack Widget and add the target option.
Another is through jQuery, in the file `/theme/functions.php`:
add_action( 'wp_enqueue_scripts', 'jetpack_widget_wpse_88067' );
function jetpack_widget_wpse_88067()
{
wp_enqueue_script(
'jetpack-hack',
get_stylesheet_directory_uri() . "/js/jethack.js",
array( 'jquery'), // dependencies
false, // version
true // in footer
);
}
And in the file `/theme/js/jethack.js`:
jQuery(document).ready(function($) {
$('.jetpack-image-container a').attr('target','_blank');
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin jetpack"
} |
How is it possible to list custom post types by "category" like with simple posts?
I created a custom taxonomy, "partners". I would like to categorize these items, so I created a custom post type with a taxonomy.
register_taxonomy("partners-category", array("partners"), array("hierarchical" => true, "label" => "Partners", "singular_label" => "Partner", "rewrite" => true, "slug" => 'partners-category'));
I would like to list these posts by categories for example: categoryname-category.php. I know it's working only with posts, so what's the best way?
Thank you very much and sorry, I'm newbie. | You have to create an template file called taxonomy-{name}.php to show the posts assigned to a custom taxonomy. So in your case it should be taxonomy-partners-category.php . Category related archive pages work only with "Posts".
Info: < . Scroll down to Custom Taxonomies display. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom post types, custom taxonomy"
} |
wpdb-> not adding prefix to custom table
I know it should work with custom table and I think it worked in previous development I believe. But this time I don't know whey it is not getting custom table with `$wpdb->tablename`
Code:
global $wpdb;
$items = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->review_media"));
This is not giving any result but when I tried with `$wpdb->prefix than it works
$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."review_media"));
Any idea | `$wpdb->tablename` works only with the tables initially present in a WordPress installation. These tables are defined in `wp-includes/wp-db.php`.
The second method you used is perfectly acceptable. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "wpdb"
} |
Does post-meta belong in header?
The template I used as a start for my own design places the metadata inside the header tag of the single-post.php. Is that a correct use of header, or should there only be h-tags in there? What about the post image? Could that be part of the header? | The w3 specification says that only h-tags are allowed inside of the hgroup-tag. The basic purpose of it is to group a main-headline and a sub-headline together.
<hgroup>
<h1>My maintitle</h1>
<h2>Subtitle of my content</h2>
</hgroup>
**edit** html5 also adds the header-tag to use within the body. Inside of this any other html element is allowed. You just shouldn't confuse it with the head tag. :-) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta, headers, html5"
} |
query_posts and custom taxonomy posts order
i have a custom taxonomy defined for "Projects" and a page that shows all the projects. In this page there's a jquery filtering menu (isotope). Initially the page must show all the projects but chronologically ('chronological' is a category and 1970, 1980, 1990, etc are subcats for a Projects element) ordered in DESC mode.
Now the query that initially shows the Projects in the page is
query_posts('post_type=portfolio&project-type='.get_post_meta($post->ID, 'portfolio_page_cats', true).'&posts_per_page=-1&orderby=menu_order&order=ASC');
There are a lot of questions about this argument, i know. Please, what is the best way to do that?
Regards, | If you are trying to order your posts by taxonomy terms, it's not technically possible in one query (since multiple terms can belong to multiple posts - which means that WordPress _cannot_ support 'orderby' for taxonomies or terms because there are potentially more than one).
Your solution would be:
1. Fetch a list of your (sub)terms and loop through them.
2. In each term loop, run query_posts() to fetch only posts attached to the current term.
3. In each term loop (after the query), create your content-output loop to display your posts. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, query posts, sort"
} |
Can't remove menu items added by plugin
I am trying to remove menu items from the backend but for some reason I can't remove specific menu items added by plugins. For example, I can use this line to remove the plugins page and it works just fine:
remove_menu_page('plugins.php');
I have a plugin, CW Image Optimizer, that adds a sub menu under the Settings menu. The php file the plugin uses is named cw-image-optimizer.php. If I use the following line to remove the sub menu it doesn't work:
remove_submenu_page('options-general.php', 'cw-image-optimizer.php');
Is there something specific I need to do to remove menu and sub menu items added by plugins? | I'll assume you're calling it in your functions.php file?
If that's the case, likely the plugin is adding the menu item after you're call is being called. Try placing it in the admin_init() hook, at the very end.
if ( ! function_exists( 'remove_wp_menu_items' ) ) {
function remove_wp_menu_items() {
remove_submenu_page( 'themes.php', 'theme-editor.php' );
}
}
add_action( 'admin_init', 'remove_wp_menu_items', 999 );
< < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, plugin development, menus, sub menu"
} |
Organize Existing Posts from the Admin Area to a New Category
I want to create and admin area that allows you to add, reorder, and remove existing posts to a 'featured' category by selecting from a dropdown menu that has a list of categories and posts in that category, preferably with a drag and drop functionality.
Would this be done with a custom post type? If so, can anyone direct me to an article somewhere that can get me started on doing this? | While it's not _exactly_ what you're asking for, check out Zoninator. It does everything you're asking except that it doesn't use categories. I'm guessing you just wanted to use categories to target a featured area of the site, and if so, this does that extremely well. It even has a widget for listing the posts, so no code is required. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
What is user_trailingslashit() for?
What does the `user_trailingslashit()` function do, and when should I use it? How is it different from the `trailingslashit()` function? | The `trailingslashit()` function adds a `/` to the end of a URL if it lacks one.
`user_trailingslashit()` uses the permalink template as set under _Settings > Permalinks_ to decide whether to add or remove the trailing slash from the end of the URL
For example, if you had the permalink format set to `/%year%/%monthnum%/%day%/%postname%/` (note the trailing slash), `user_trailingslashit()` would append a trailing slash to the URL passed in as the first parameter.
If the permalink format was `/%year%/%monthnum%/%day%/%postname%` (no trailing slash), any trailing slash on the URL would be stripped off.
Basically, `user_trailingslashit()` forces the URL to be consistent with what is set in the permalink preferences. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "functions"
} |
Adding Second Plugin Author
**Background:** I have a few plugins in the WordPress directory and have recently made the decision to team up with another individual to grow one plugin faster. I'm planning on adding him as a plugin author, but I want to be sure that if I do so there's no risk of me "losing control" of my plugin.
**Question:** If I add another author, is there any way that the new author can remove me as plugin author? Can they upload the plugin with their username and password, or am I still the only one that can upload changes?
I couldn't find anything on this topic, and I'd really hate to have my plugin stolen as I've become somewhat attached to it. | You can add the author as contributor and all I know, he does not get automatically write access to your svn repository. You can also just mentioning the other author without adding him as contributor.
My personal opinion is, if you're worried that the other author steals your code, then he is the wrong helper. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development"
} |
How to access a variable on all page?
I added a variable to my functions.php file:
$options = get_option( 'simple_options' );
I can access to this variable on every page, but If I call it in the footer.php it's not working. How to fix that? | Generally, you cannot access local variables in a function from outside the function, so this...
function func() {
$var = 2;
}
$var = 1;
func();
echo $var;
would result in "1".
To make a global variable, you can do this to make `$option` available outside `functions.php`:
function func() {
global $option;
$option = get_option( 'simple_options' );
}
However, I cannot recommend it, since every other script may change the value. You can use a define:
define('MY_OPTION',get_option( 'simple_options' );
And in your footer:
echo MY_OPTION; // note that there are no quotation marks
But also this wouldn't be that neat, since you'd have to make sure no other script defines this `MY_OPTION` and you cannot change it later on.
**No, your best bet is to get the option just again in your footer.** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "variables, options"
} |
Recommended sidebar / content widths
I'm developing my own theme. Does WordPress recommend or require a minimum or maximum when it comes to the width of the content or sidebar elements of an post, page or archive page? If not, are there any unofficial guidelines? | There are no recommended sidebar widths, however there are LOTS of plugins that make assumptions about this (especially those that handle advertisements).
If you plan on running ads, please check the ad width requirements and use that as your baseline. For example, if you are running AdSense ads and the ad requires 300px, then make sure that sidebar has a minimum width of 300px or your might break your layout or the ad might not show.
This can be tricky with responsive or fluid layouts, but being aware of it is half the battle. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes, sidebar, content"
} |
How to change user role setting in members plugin so that user can only edit his own post?
I want enable a user to only edit specific post. I am using the members plugin. I do not see a way to achieve this. Do I need to do some code for that post?
Thank you! | the Short and sweet way would be to store the post id that they are allowed to edit in custom user meta. Then us wp_update_post and check if the id is in the user meta if so update if not don't. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "user roles, user access, members"
} |
how to check if a shortcode is used more than one time in the same post
I've written a shortcode plugin. Basically the plugin has the following structure:
PL::setup();
class PL {
public static function setup() {
add_shortcode("myshortcode", array ( __CLASS__,"myshortcode_handler"));
}
public static function myshortcode_handler(
... some variable assignment?
if (time the shortcode is invoked == 1) {
...
}
else {
...
}
... some other code lines
}
}
I need to distinguish the case the shortcode is invoked for the first time or not. I think I have to declare some variable, but I do not know how and where I have to declare it. | In your shortcode callback `myshortcode_handler()`, use a static variable:
function myshortcode_handler()
{
static $first_call = TRUE;
if ( ! $first_call )
{
# callback was called earlier …
}
# set it to FALSE after you have handled the condition.
$first_call = FALSE;
return;
}
Please do not misuse the global namespace for this: avoid constants, global variables and similar workarounds that might lead to unexpected conflicts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, shortcode"
} |
Sidebars are no longer working
I am trying to figure out why my sidebar is no longer working. I tried reinstalling my theme, disabling all of my plugins, and uploading a fresh version of widgets.php, with no luck.
I am using the Photogram theme, but the problem doesn't go away if I change to a different theme.
Here is what I see when I go to my widgets page:
!Widgets page
!Zoom in of the area | ## uploading a fresh version of widgets.php
which widgets.php?
I guess you updated **wp-admin/includes/widgets.php**?
you actually need to update **wp-includes/widgets.php** where dynamic_sidebar function defined in. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sidebar"
} |
Theme options not displaying correctly after theme update
I am redesigning a theme options panel but when I present to a client, the display is not exactly the same with the one I made. I investigate on this problem and it seems that he is actually seeing a part of the old version of the theme options panel so a full clearing of the browser cache should solve the problem. I have replicate his issue and clearing the browser solve this one.
But I'm looking for some ways to somehow reset or flush old changes on the browser for the theme options without actually clearing your cache. As I have observed the client is not yet ready to clear his browser probably due to some important reasons.
Is there a solution to this? Thanks. | Browsers will cache any files so it's hard to know without more detail _which_ files are your issue. That said, this happens most often with CSS and JS files, and WordPress is built to address this issue. wp_enqueue_style and wp_enqueue_script each have a parameter for file version (4th param in each). So long as you use these functions and up this version whenever you make a change, you should never run into caching issues with either file type. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development"
} |
Override methods in Yoast SEO breadcrumb class
I've been trying to figure out if it is possible to override the output of the Yoast SEO breadcrumb class rather than editing the original file?
Each url segment is wrapped in `<span></span>` but i'd like to wrap it in `<li></li>`
Is this possible? Any pointers in the right direction would be appreciated.
Thank you. | In cases like this, open the plugin files in a good code editor and search for the elements you need, as there may be an useful hook.
So, for this we have the filter `wpseo_breadcrumb_single_link`.
Maybe you can replace `span` for `li` in `$link_output`, or use `$link` to build your own:
add_filter( 'wpseo_breadcrumb_single_link', 'filter_breadcrumb_wpse_88254', 10, 2 );
function filter_breadcrumb_wpse_88254( $link_output, $link )
{
// do your stuff
return $link_output;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, theme development, plugin wp seo yoast"
} |
301 Redirect /author/username/ to /profile/username/
I have changed the `/author/` slug to `/profile/` by adding the following code in the file `functions.php`:
function new_author_base() {
global $wp_rewrite;
$author_slug = 'profile';
$wp_rewrite->author_base = $author_slug;
}
add_action('init', 'new_author_base');
Since Google is crawling my author pages now I need to redirect the old `/author/` urls to the new `/profile/` ones in the `.htaccess`...
Any ideas? | Add this to 'your' section of the `.htaccess` file (so not in the WordPress section):
Redirect 301 /author | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect, author"
} |
Option to delete value in metabox
I'm making a metabox with a textbox that displays the value of the metakey if I user types and saves data. What I need help with is how the user can delete previous entries as well as edit them if they need to. I've looked all over and can't find anything.
This is what I have to display entries:
<?php if ( get_post_meta($post->ID, 'brk_news_update', true) ) : ?>
<?php
$mykey_values = get_post_custom_values('brk_news_update');
foreach ( $mykey_values as $key => $value ) {
echo "$value <br />"; }?>
<?php endif; ?>
All help is greatly appreciated. | Use delete_post_meta to delete a value.
Example:
delete_post_meta($post->ID, 'brk_news_update');
If you want to update it, then use update_post_meta
update_post_meta($post->ID, 'brk_news_update','value'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "metabox"
} |
Should i use _n for pronouns in translation?
**I use _x() now! I accepted the answer just because he understood right and was first. So don't get confused!**
$like_me_on = __('Like me on %s', 'my-plugin');
$like_us_on = __('Like us on %s', 'my-plugin');
$follow_me_on = __('Follow me on %s', 'my-plugin');
$follow_us_on = __('Follow us on %s', 'my-plugin');
$my_x_profile = __('My %s profile', 'my-plugin');
$our_x_profile = __('Our %s profile', 'my-plugin');
I have this code and i read about _n() and saw only examples with $count on wordpress codex.
The text is for a bunch of social services that will later be %s, if i would use _n then i would have this variables combined, but the translation string would be more complicated to read. So what is best practice and is this intended for pronouns or just for numbers? | It's interesting idea and I think that such approach will work for you. What I would recommend you is that it will be better to use constructions like this:
// $singular = 1 - for 'me', 2 - for 'us'
$like_on = _n('Like me on %s', 'Like us on %s', $singular, 'my-plugin');
In this case it will be easier to understand how to translate the phrase.
Also read this question How-to: Translate plural forms for themes/plugins with PoEdit to understand how to configure your `poedit` to support plural forms with WordPress keywords (like `_n`, `_n_noop`, `_nx` and `_nx_noop`). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "translation, localization"
} |
Using Underscore Templates in WordPress
I've noticed that since WP 3.5 that we now have the Backbone.js and Underscore.js libraries included. The new Media Modal uses Underscore templates and I was wondering how would I be able to insert them, especially in the admin side of things.Is there a correct way to insert these? | Your plugin index file:
add_action( 'print_media_templates', 'wpse8170_admin_footer' );
function wpse8170_admin_footer() {
require 'templates.php';
}
Your templates.php:
<script id="tmpl-mytemplate" type="text/html">
<h1>Hello {{data.name}}!</h1>
</script>
Your media js file:
wp.media.view.MyView = wp.media.View.extend({
template: wp.media.template('mytemplate'),
render: function() {
this.$el.html(this.template({name: 'world'}));
}
}); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "jquery, media modal, underscore, backbone"
} |
Add robots.txt to root
I have a new Wordpress 3.5.1 install (hosted on Dreamhost FWIW) that I do **not** want to be indexed by search engines. I would like to serve a simple robots.txt with `Disallow: /` for all user agents.
I have checked the "Discourage search engines from indexing this site" box on the Settings > Reading menu, but < still returns a 404.
Is there a way to have Wordpress automatically generate and serve an appropriate robots.txt file? If not, what is the best way to configure it to serve my own static robots.txt file? | First of all, in order for Wordpress to generate a robots.txt for you you must be using a non-default permalink structure. Make sure you've selected an option in the Settings > Permalinks menu.
Also, if a robots.txt file exists at your root directory it will override the setting in Wordpress. It looks like you already have a robots.txt file and that is the reason the wordpress setting is ignored. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "configuration, robots.txt"
} |
Get Posts From A Certain Post Type In An ID Array
I have some post ids in an ID array, like:
$ids = array(20,34,65,126) ;
There is many custom post types in my project, these ids are related to different post types, but I dont know which id is related to which post type in that condition. In another word, I need to do something like this:
$posts = my_get_posts(
'ids' => array(20,34,65,126),
'post_type' => 'product',
) ;
That function has to be eliminate ids which is not a producy.
How to do this? | I am assuming this-- "That function has to be eliminate ids which is not a producy"-- means "I only want to pull the post associated with the ID if that post is a product". In that case a simple query should do it:
$pqry = new WP_Query(
array(
'fields' => 'ids', // if you only want the Post IDs
'post_type' => 'product',
'post__in' => array(20,34,65,126)
)
);
## Reference:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "custom post types, loop"
} |
Showing all the posts in one page?
There are over 200 posts tagged with the keyword "Apple."
Each tag page -- example.com/tag/apple/page/2/ -- shows 10 posts.
So there are 20 tag pages.
Is it possible to show all these 200 post (links) in one page? I don't want to show any of the excerpt -- just consolidate all those 200 links in one page.
Appreciate your help! | This is what I would consider the correct solution, and is the solution alluded to by Milo's comment (if I am not mistaken).
function alter_ppp_for_tags_wpse_88337($qry) {
if ( is_tag() && $qry->is_main_query() ) {
$qry->set('posts_per_page','-1');
}
}
add_action('pre_get_posts','alter_ppp_for_tags_wpse_88337');
Using `query_posts` will cause two requests to the database-- the main query, and the query triggered by the use of `query_posts`. By using a filter on `pre_get_posts` you alter the main query before posts are fetched and thus only hit the database once.
## Reference:
< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "categories, tags"
} |
Resizing old post thumbnail images
In my `functions.php` I have defined the following:
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 475, 475, true );
I have used the **Regenerate Thumbnails** plugin to regenerate the thumbnails.
When calling `<?php the_post_thumbnail(); ?>`, the images do not look cropped. When checking my uploads folder I do not see any thumbnails set for 475x475.
Thoughts? | I've figured this out. Appears as though I really wanted `add_image_size('post', 475, 475, true);` and then reran the **Regenerate Thumbnails** plugin. After sorting out a permissions error on `/wp-content/uploads`, this worked great.
Then in my theme, I just displayed this image size for the post thumbnail. `the_post_thumbnail('post');` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails"
} |
Comments turned off, but 'Leave a reply' link still there
On my site, commenting is not enabled.
But at the top of each blog post (except for one, strangely), there's a 'Leave a reply' link.
(the link doesn't do anything -- but the words 'leave a reply' sitting there obviously make it look like you can leave a reply...)
I don't see any 'discussion module' in my edit-post page.
Here's an example page with a 'Leave a reply' link, just under the post title:
<
I'm on Mac Chrome -- in case it's a small browser-related bug... | Maybe you have forgotten to wrap the `comments_popup_link()` with `if ( comments_open() )`
if ( comments_open() ) :
comments_popup_link( [...] );
endif; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
Wrap More Link in Div
I would like to put the "more" link in it's own div and am having some trouble... my current code looks like: `the_content("<div class='more'>More >></div>");`
But the problem is that the output is not cross-browser compatible...Safari and Firefox render this fine, placing the `div` around the more link...but IE8 renders the `div` in the `a` tag of the link, making it look funny.
Is there a function I can add to my theme that would allow me to wrap a `div` around the more link so I don't have to worry about how different browsers interpret my original code?
Thanks,
Josh | I found a solution on the WordPress forums, if anyone is trying to do the same thing here is the solution: <
I added the following to my functions file:
function wrap_readmore($more_link) {
return '<div class="post-readmore">'.$more_link.'</div>';
}
add_filter('the_content_more_link', 'wrap_readmore', 10, 1);
Thanks,
Josh | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "read more"
} |
Infinite scroll loads new posts several times
I've added infinite scroll support of the Jetpack plugin to my own theme with:
add_theme_support( 'infinite-scroll', array(
'container' => 'content',
'footer' => false,
'render' => 'vividflow_infscroll_render',
'wrapper' => false,
'posts_per_page' => 12
) );
The `vividflow_infscroll_render` just loads The Loop.
However, I'm experiencing some trouble with the infinite scroll: new posts are loaded **multiple times** , so that I get **double posts** on the archive page. My archive page looks like this:
!enter image description here
I think new posts are loaded several times because I have several posts on the bottom line: 3. When I place all the post summaries beneath each other, there is no problem.
How can I resolve this issue? | The problem indeed was that there were several posts on the bottom. Adding this to the end of the loop helped:
<br style="clear:both;"/>
I think this is a bug in the Jetpack plugin, but it is easily resolved by adding this line break. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, plugin jetpack"
} |
Using Wordpress as a Mobile App Backend
I'm searching for a fast way to develop a backend for Mobile Apps. The idea is to use Wordpress as a backend.
My problem is: How can i serve the information to the Mobile App? I saw the JSon plugin but you can't use it for custom post types.
I was thinking at xml, is there a plugin i can use or should i code specific pages that serves xml?
Thanks. | You could use WP and all it's associated goodness for a mobile app backend (I'm going to do it soon myself).
Custom post types are not a problem. Make a page, grab the data with a WP_Query and serve up the query results as JSON instead of HTML, though you'll have to do this bit yourself I'd wager (I'm planning on doing it).
That's only one part of it of course, if you can give a bit more information about the project you might get some more insightful answers! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mobile"
} |
get_permalink to attachment not working
I have following code
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 12,
'post_status' => null
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li><a href="'.get_permalink( $attachment->ID ).'">';
echo wp_get_attachment_image( $attachment->ID, array('100', '100') );
echo '</a></li>';
}
}
?>
The point of this script is to show last added 12 photos (thumbs of it). And this works perfect. But I want to add second funcionality - link to the page where it comes from (usually native gallery embed into post/page)
The problem is that in this case the link is corrupted. It always links to the very first post. What I am doing wrong? | The Problem is that you query for Post Status `null`. Try setting this to `publish` or `inherit`, because `get_permalink` is a function for published items, not for any post status.
This is because Permalinks to items with a status like `draft` should not be shown to the user. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, attachments"
} |
strip last comma from get_the_category
foreach((get_the_category()) as $category) {
echo $category->cat_name . ', ';
}
So I'm echoing it like this because I don't want the categories to appear as hyperlinks, I just want the cat names.
The problem is I can't get rid of the last separator so it ends up like : category, category, category,
I tried 'stripping' it (php seriously confuses me small design mind)
foreach((get_the_category()) as $category) {
echo $category->cat_name . ', ';
echo rtrim($category, ", ");
}
That didn't trim it though. | There are two ways to solve this issue. You need a clean array of category names for both, so let’s start with that:
$cat_names = wp_list_pluck( get_the_category(), 'cat_name');
`$cat_names` is now an array with just the names:
Array
(
[0] => aciform
[1] => Cat A
[2] => Cat B
[3] => Cat C
[4] => sub
)
Now you can use the simple way:
echo join( ', ', $cat_names );
Result: _aciform, Cat A, Cat B, Cat C, sub_
But my recommendation is to use the grammatically correct list, use `wp_sprintf_l()`:
echo wp_sprintf_l( '%l', $cat_names );
Result: _aciform, Cat A, Cat B, Cat C, and sub_
`wp_sprintf_l()` will use a localized separator for the last two items, so in a German site this would output: _aciform, Cat A, Cat B, Cat C und sub_.
And you don’t even have to care about the correct translation – the proper separator is part of the regular language files. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Some images suddenly not appearing
I'm having trouble with some images not showing up. These were fine and then suddenly stopped working for no apparent reason. A couple of examples:
<
<
I've tried deleting and reinserting the images but it doesn't seem to make any difference. The images appear in the dashboard when I am editing the post but not when it's previewed or published
Any suggestions/help would be appreciated! | I had a look at your links, looks like you are using Jetpack which puts all your images on the WordPress CDN. For some reason it is not working correctly. Turn it off and it shall work properly.
Most likely you must have changed the image after publishing the post | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images"
} |
Wordpress Rewrite Rule
I have a standard page setup at `
I'd like to setup a rewrite rule in my theme functions that takes any URLs such as:
` <\-- Currently shows "Not Found"
And translates it into:
` <\-- Currently shows the standard page
NOTE ADDED:
"helloworld" is an unknown variable value, so I want ALL "/mypage/" urls to rewrite back, for example: ` ` `
Will all rewrite back to ` | As the question was modified, I modify my answer. This task is relatively easy, doable just with a single rewrite rule, which converts everything after /mypage/ string into a variable - I call it var. As this is added to query_vars via hook, is reachable via `global $wp_query; echo $wp_query->var;`.
add_filter( 'query_vars', 'binda_query_vars' );
function binda_query_vars( $vars ) {
$vars[] = 'var';
return $vars;
}
add_action( 'generate_rewrite_rules', 'binda_rewrite_rules' );
function binda_rewrite_rules( $wp_rewrite ) {
$mypage_id = 4; //setup your 'mypage' ID
$wp_rewrite->rules = array(
'mypage/(.+?)/?$' => $wp_rewrite->index . '?page_id='.$mypage_id.'&var=' . $wp_rewrite->preg_index( 1 ),
) + $wp_rewrite->rules;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, url rewriting, rewrite rules"
} |
Changing H1 to Normal Links
After following this tutorial -- Showing all the posts in one page? \-- I was able to show all post links in one tag page.
Example: <
Now I have several H1/H2 headers in those tag pages -- more than 100s.
How can I convert these H1 titles into normal titles?
Here's the code:
$title = the_title( '<h1 class="' . esc_attr( $post->post_type ) . '-title entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h1>', false );
I have changed H1 to Strong tag, but is it possible to remove/refine the code further? I tried removing rel=bookmark and other elements but my efforts were unsuccessful (errors were shown after uploading the file).
I also want the fonts to be normal, small in size.
Appreciate your help!
Thanks... | I'd change this:
class="' . esc_attr( $post->post_type ) . '-title entry-title"
and make a special class for this usage. For example, make it:
class="fb-list"
and then style it however you like in your style.css file:
.fb-list { font-size: 16px; font-weight: bold; }
I'd also change the `<strong>` tag to a `<p>` or `<span>` or something that's more appropriate. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tags"
} |
Why this filter hook is not working when passing parameters?
Supposing I have this function which I hooked into my_get_users function:
function define_users($group) {
//Query database for users belonging to a group
global $wpdb;
$users= $wpdb->get_results("SELECT user_id from $wpdb->usermeta WHERE meta_key='groupname' AND meta_value=$group",ARRAY_N);
return $users;
}
add_filter('my_get_users','define_users',10,1);
This is my_get_users function where the apply_filters are found:
function my_get_users($group) {
//Define users as array
$users=array();
$users = apply_filters('my_get_users', $users, $group);
return $users;
}
I am sure there is data in the database but the $users variable is returning as an empty array. Any ideas what's wrong? Thanks for your help. | try this
**$users = apply_filters('my_get_users',$group);** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters"
} |
add_theme_page is not working
Newbie in wordpress coding. please tell how to create theme option pages.
function my_plugin_menu() {
add_theme_page('Theme Options', 'Theme Options', 'edit_theme_options', 'theme-option-slug' , 'settings_page');
}
function settings_page()
{
echo "aa";
} | You created the callback function and the function for adding the Theme page, but you also have to tell WordPress when to call your function `my_plugin_menu`. You can do this by hooking into `admin_menu`.
add_action('admin_menu', 'my_plugin_menu');
This way WordPress knows that when it reaches the Scripts for `admin_menu`, it also has to execute your code, thus adding your Theme Page.
More information on this is available on the Codex. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development"
} |
What's the best way to implement AJAX in WordPress?
WordPress has a framework in place for handling AJAX which is well documented here: <
My concern with this is that every time you execute an AJAX query, (even if you want to return a single field from a table) this framework instantiates the whole WordPress stack, including any plugins and theme functions that may exist on your site. This strikes me as a pretty heavy method to perform what may end up being a pretty simple function.
Typically a lot of WordPress sites run on shared hosting and don't have a whole lot of processing power, so, based on my experiences, a reponse time of 2 seconds to a WordPress hosted AJAX call is not uncommon.
Any recommendations on how to improve on this response time? | The crude alternative most people resort to is the one where you add a file and include several levels up. This is arguably worse for performance if not just as bad.
But there is a variant that works better, if we create our own AJAX entrypoint URL, and specify:
define( 'SHORTINIT',true);
Then include the WordPress environment, we can skip over the majority of the loading process. This is the way to go if you want super zippy AJAX requests. The downside is that we have to load some things ourselves, and some steps of the loading process are never executed.
See this answer for more detail Ajax takes 10x as long as it should/could | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, ajax, performance, customization, server load"
} |
Saving Taxonomies to Post Revisions
In a custom post type, I first got all the revisions using `wp_get_post_revisions()`.
I looped through, and compared metadata and postdata to see the differences between the two. However, it seems that when I employ the same strategy on `get_the_terms()`, I'm getting the proper taxonomies for the actual published post, but the revisions do not have any taxonomy data.
How can I save taxonomy information for revisions? | WordPress only supports revisions for post content, not terms.
To create a system that monitors changes in post-term relationships over time, you would have to write a plugin that explicitly handles that.
If you're interested in going down that route, you would probably need to use the save_post hook to save term data (saving as serialized post meta would probably be best) and the add_meta_box hook to output a list of term updates/revisions.
This would be decoupled from the existing revision system unless you wanted to get even more technical, but it might be the most expedient way to get what you want. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, revisions"
} |
custom header text
I am creating a custom website by modifying the twenty-eleven theme. I want to create custom text in the header area that is unique to each page. Is there a way to add a 'description' to each page and then use php to call on that description? Currently it displays the "site title"
here is the url to the site so you can see what im talking about.
www.tenspeedgreens.com
where it says 'ten-speed greens' is where i would like the custom text to be displayed.
thanks | For something like this, you can use WordPress's built-in "Custom Fields" feature.
**Step 1**
On your edit page, **create a new Custom Field** (if you don't see the Custom Fields box on your edit screen, click on the grey"Screen Options" tab at the top-right of the page, and make sure the "Custom Fields" box is checked). The name can be anything, for example let's assume you want to use "Page Description"...
**Step 2**
Finally, **output that custom field into your theme.** Do this by using the following snippet wherever you want to output the custom description text...
<?php echo get_post_meta(get_the_ID(),'Page Description',true); ?>
One more thing... WordPress will remember the name of your Custom Field. Any time you want to use it on a page or post, you can select the name from a drop-down and then enter your description for that page/post. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, custom field"
} |
URL prefix to include one PHP page
is it possible to set one URL prefix to include one PHP page every time? Only Wordpress header and this PHP page. I need to include some custom application but HAVE TO include wordpress powered web-design.
For example - < is a prefix and
points to one PHP page included in Wordpress theme-page.
Thanks. | Try **`get_template_part()`**.
For example, in your `index.php` template file:
/**
* Index template file
*/
/**
* Include header
*/
get_header();
/**
* Include arbitrary file
*/
get_template_part( 'foobar' );
This will include a template-part file, `foobar.php`, located in the Theme's root directory. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Comment forum to display under the comment you're replying too
I am making a theme where I have built in my own custom threading and such using twitter bootstrap. I have it now so that, as per default, when you click reply you are shot down to the WordPress comment forum.
Is there a way to make the comment forum come to you? to display right under the comment you are replying too? | Enqueue the `'comment-reply'` script.
function wpse88530_enqueue_comment_reply() {
// Enqueue the comment-reply script on
//single blog post pages with comments
// open and threaded comments
if (
// Returns the value for the specified option.
// 'thread_comments' is a Boolean option where
// comments are threaded if TRUE, and flat if
// FALSE
get_option( 'thread_comments' )
) {
// enqueue the javascript that performs
//in-link comment reply fanciness
wp_enqueue_script( 'comment-reply' );
}
}
// Hook into comment_form_before
add_action( 'comment_form_before', 'wpse88530_enqueue_comment_reply' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments"
} |
Wordpress update and plugin install not working
I am working on a website that I installed WP on a few months back but haven't worked on beyond the install of WP and a theme. I went back to it today and needed to update WP and install a few plugins.
When I went to do that it started asking me for FTP info, which was new to me. After research I added said FTP info into the wp-config file. Now when I go to update WP or install a plugin, where it should start putting info on the screen about downloading and updating the files I get nothing in the right pane of the dashboard.
I've tried chmod wp-content to 777 and still nothing. I can FTP but I need to be able to update via WP.
I'm stumped. Any thoughts? | Wordpress is only asking for FTP credentials if your chmod permissions are misconfigured. You should start by checking them. It means all files and directories inside wordpress dir and not only wp-content. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 0,
"tags": "plugins, updates"
} |
Display 1 category only with get_the_category (by ID or slug)
After hours of unfruitful Googling, I am asking for your help on this issue.
My objective is to display only 1 category with get_the_category if the category ID matches the ID or slug set in the get_the_category function. Basically I'm asking for something like this: let's say there's a category titled "important". I want to exclude all other categories assigned to the post and only show "important" if the post is within that category. If the post isn't in important, nothing should be displayed. This should be too hard, but I could figure it out.
Here's the closest thing I found to this, but it only displays the first category for the post, no option for manual selection by ID or slug:
<?php
$category = get_the_category();
if($category[0]){
echo '<a href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
}
?>
Thank you for your contributions. | I think you could do something like this:
$categories = get_the_category();
$displayed_category_id = 1; // set this to the category ID you want to show
$output = '';
if($categories){
foreach($categories as $category) {
if ( $displayed_category_id == $category->term_id) {
$output .= '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>';
}
}
echo $output;
}
It might not be the most efficient code (and it's untested) but it should work...?
You could swap out the slug or category name pretty easily if ID isn't the key you'd like to use. G'luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "exclude, id, categories"
} |
Excerpt length: get first paragraph
I'm trying to figure out if it's possible to get an excerpt from each post, grabbing the first paragraph from each one. I'm currently using the ACF plugin and have custom post types and custom fields.
Here's my code:
function custom_field_excerpt() {
global $post;
$text = get_field('news');
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = 20; // 20 words
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
return apply_filters('the_excerpt', $text);
}
This works great, but it only trims the first 20 words (or however many words you specify), I'm trying to adjust this to pull in the first paragraph of each post instead of the first 20 words. Is this at all possible? | Assuming your paragraphs are marked with `<p>` tags, which can be set in the ACF field options, the following should work:
function custom_field_excerpt() {
global $post;
$text = get_field('news');
if ( '' != $text ) {
$start = strpos($text, '<p>'); // Locate the first paragraph tag
$end = strpos($text, '</p>', $start); // Locate the first paragraph closing tag
$text = substr($text, $start, $end-$start+4); // Trim off everything after the closing paragraph tag
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
}
return $text;
}
You could also pretty easily modify this to locate the first `<br />` tag, if you happen to be storing your ACF data with `<br />`'s instead of `<p>`'s. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom field, functions, excerpt, advanced custom fields"
} |
How to remove the parentheses from the category widget
In the default category widget, when you check the "show posts count" checkbox, the number of posts appear surrounded by parentheses, how to remove them. | Add this code to your functions.php file and it will remove the parentheses and surround the post count with a span with a class to easily style it.
function categories_postcount_filter ($variable) {
$variable = str_replace('(', '<span class="post_count"> ', $variable);
$variable = str_replace(')', ' </span>', $variable);
return $variable;
}
add_filter('wp_list_categories','categories_postcount_filter');
++Bonus In the archive widget, if you checked "Show posts count" checkbox you'll see the same parentheses around posts count, here's another filter to remove them and add a class to easily style theme.
function archive_postcount_filter ($variable) {
$variable = str_replace('(', ' ', $variable);
$variable = str_replace(')', ' ', $variable);
return $variable;
}
add_filter('get_archives_link', 'archive_postcount_filter'); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "categories, widgets"
} |
Allow Content Author to Publish, But Not Edit or Delete
I am hiring a content writer for my WordPress blog. I will be the sole blog admin. I need to define a role for this writer.
I was wondering if there was a WordPress user role that will allow him to publish posts and pages (even without admin approval), but not be able to Edit or Delete them once published (or only do this after admin approval). I need this in case he has a change of heart and decides to ruin the site by removing all posts he created or replacing them with rubbish. | I would create a new user role, and then assign that role to the user when you create their account. In your `functions.php`:
add_role('content_writer', 'Content Writer', array(
'read' => true,
'publish_posts' => true,
'edit_posts' => false,
'delete_posts' => false,
));
You can see the codex for an additional listing of available roles and capabilities. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "author, user roles"
} |
How to stop direct HTTP POST to a PHP script?
I have a form on my site, created using Contact Form 7 with Captcha. Contents of the form when POSTed are being sent to a PHP script, the "action" attribute of the form is set to `themes/<themename>/<filename>.php`
We have been receiving a lot of spam, it seems that someone can handcraft the form and use it to send spam. In the processing script I check the `HTTP_REFERRER`, `HTTP_SERVER` to see if the request came in via our site, but those headers can also be manually crafted in. What steps do I need to undertake to stop the spam coming in?
Help is appreciated.
**EDIT** : Some more clarity. CF7 will POST the form data to my script at < , that script is accessible . Someone can go to the page where my form is and copy the HTML, re-create the form on their local machine and start submitting the form to my script. How do I stop that? | You must hook the form using `wpcf7_before_send_mail` and add your PHP code to functions.php (since the script is already in your theme folder)? You won't lose any of CF7's abilities.
function wpse_process_form( &WPCF7Object ){
#process your form here
}
add_action('wpcf7_before_send_mail', 'wpse_process_form' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms, security, spam"
} |
This webpage has a redirect loop issue
I want to redirect non logged in users to page id = 2 which have registration form.
function checkLogged()
{
$pg = get_permalink();
if (!is_user_logged_in() && !is_front_page() && $pg != home_url('/?page_id=2'))
{
wp_redirect(home_url('/?page_id=2'));
exit;
}
}
add_action('wp_head', 'checkLogged');
Is this code correct ? I am getting
> This webpage has a redirect loop The webpage at < has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer. | Use following code instead of above code :
function checkLogged()
{
if (!is_user_logged_in() && !is_front_page() && 2 != get_queried_object_id())
{
wp_redirect(home_url('/?page_id=2'));
exit;
}
}
add_action('wp_head', 'checkLogged'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login, wp redirect"
} |
Custom order categories in admin dashboard
everyone, is there way to order categories in add/edit post in admin dashboard. The problem is my order must be custom, not by Name or ID. For example:
* Rumors (id 5)
* News (id 1)
* Features (id 7)
* etc.
The ideal solution will be to order categories by description. That way in category description field I will put number or letter and categories will order right.
Thank you in advance! | Use the `get_terms_args` hook and modify the `orderby` argument, like so:
add_filter( 'get_terms_args', 'my_sort_terms', 10, 2 );
function my_sort_terms( $args, $taxonomies ) {
$args['orderby'] = 'description';
return $args;
}
Possible values for this argument are listed in the codex. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "categories, admin, dashboard, order"
} |
Multidimensional array sort?
If i have a set of years, retrieved by the loop, for every years can be more post ID. Like:
2008 => 3,7,8
2009 => 4,5,6
2010 => 9
the code is:
query_posts('post_type=portfolio&posts_per_page=-1');
if (have_posts()) :
while (have_posts()) :
the_post();
$tmp_date = //get the year;
What's the better way to put years and relative posts ID in an array (later i need also an array sorting by year)? | Use `ksort``($projectsByYear)`
Of course every time you add something to the array it will need to be resorted. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sort, array"
} |
problem in query_vars parameters
I've a problem. I've tried a lot of things but I could not find a solution. I use query_vars parameters in this page and there isn't any problem. But i don't use different parameters or the same parameters in different custom page (../videolar). Parameter value is always empty. Parameters used once ? Function.php :
function parameter($qvars){
$qvars[] = 'kategori';
$qvars[] = 'ara';
$qvars[] = 'numara';
$qvars[] = 'tur';
return $qvars;
}
add_filter('query_vars', 'parameter');
videolar.php (../videolar?tur=test) :
global $wp_query;
echo $wp_query->query_vars['tur'] // empty | The problem is solved.
Re-save your permalink settings after you add the parameter. Or change the file permissions of .htaccess to 777. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, parameter"
} |
Function to change meta value in database for each post
I have a meta key called 'prijs' in each post. The value of this meta key consist of numbers in the follow structure: 2,100.00
I want to remove the comma in the meta value to get this output: 2100.00
So, i created a function but it doesn't work:
add_action('wp_insert_post', 'deleteCommaDB');
function deleteCommaDB($postID){
$price_key = 'prijs';
$getPrice = get_post_meta($postID, $price_key, true);
$newPrice = str_replace(array(','), '', $getPrice);
update_post_meta($postID, $price_key, $newPrice);
return true;
}
I created the function `deleteCommaDB`. This function gets the post meta from the meta key 'prijs', and replaces the comma for nothing. This new value is saved in the variable $newPrice. Next thing to do, is update the post meta with the new value.
What am i doing wrong? | You'll only need to run it once, but this should get all your posts, and then loop through them and update the meta.
add_action('admin_init', 'deleteCommaDB');
function deleteCommaDB(){
// The Query
$args = array ( 'posts_per_page' => -1 );
$the_query = new WP_Query( $args );
// The Loop
while ( $the_query->have_posts() ) :
$the_query->the_post();
$price_key = 'prijs';
$getPrice = get_post_meta( get_the_ID(), $price_key, true);
$newPrice = str_replace(array(','), '', $getPrice);
update_post_meta(get_the_ID(), $price_key, $newPrice);
endwhile;
}
Your function runs only when a post is inserted. You might want to consider running on `save_post` and sanitizing the `$_POST` input in the first place. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom field, post meta"
} |
What's the difference between post thumbnails and featured images (if any)?
On the Codex on Post Thumbnails, I see:
> Post Thumbnails is a theme feature introduced with Version 2.9. It was quickly changed to Featured Images with Version 3.0. Post Thumbnail, now Featured Image, is an image that is chosen as the representative image for Posts, Pages or Custom Post Types.
On the changelog for Version 3.0:
> Change Media UI labels from "Post Thumbnails" to "Featured Image"
Is there any difference in behaviour of post thumbnails and featured images, or was in 3.0 only the name changed? Why did the name change? It is a source of misunderstanding, as the image size is still called `thumbnail` or `thumb`, while it on the UI everywhere says Featured Image. | This is explained in the core ticket #12554.
> ### Change label in UI for Post Thumbnail and Page Image to "Featured Image" for both
>
> We should change the UI label for the post thumbnail box on post and page editor screens. It's post thumbnail for posts, and page image for pages, but it's not always a thumbnail and the labeling is inconsistent. Let's call it Featured Image for both, which is consistent and removes the size implication of the 'thumbnail' label. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "post thumbnails"
} |
No line breaks in tags in tag cloud
I use the tag cloud widget on my site. I have some tags which consist of more than one word, like 'free will'. In the tag cloud, there sometimes comes a line break _in_ those tags, between the words:
!enter image description here
How can I make that this doesn't happen? I thought of adding `display:inline-block;` to the style of the tags, but there is no general `tag` class or something like that. Can I add a class to all tags (and if so how?) or is there an other way to do this (and if so what way?) | Try this in your CSS (untested, but should work in theory)
.tagcloud a {
white-space: nowrap;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tags"
} |
Is There A Way To Add Another Field To Custom Post Type (Not Custom Field/Meta)?
Maybe I'm not getting the whole concept, but is there a way to modify a Custom Post Type so that it includes other 'fields' like a 'real' db table. I don't mean a Custom Field (get_meta)... I mean inside the table that can be manipulated with rules. I want to make a post type with several -mandatory- fields.
eg.
Song Record:
<Title
<Lyrics
<Date
<Length
<MP3
:end
Yeah, I can do that with a bunch of custom fields, but I was wondering/hoping if this structure could all be laid out with Register_Post_Type so it could be manipulated as a single 'object'... as one can do in Drupal.
Or have I got this all wrong?
\---JC | There is no built in way to do so. You could possibly do it via MySQL directly via ALTER TABLE but you'd have to write custom code to take advantage of this yourself. Another option is to create a new table where each set of data references a certain post. Yet again, you'd have to manage everything yourself.
My suggestion: use a plugin like Meta Box or WP Alchemy to use the custom field system that's already there. Either one creates a meta box of fields that'll save the custom post meta for you | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, customization"
} |
One post out of more than twenty shows odd picture (from post) in the header
(WP 3.5.1)
My blog has a header picture showing its name. But for some reason exactly one post shows a picture in the header which is actually used within the post itself.
<
I don't even know how I would acomplish such feat if I wanted - given that the header code as far as I know is included from header.php and hence keeps the same references in every single post...
How do I find out what the reason is, so I can change the header image back to the right one !?
* * *
!enter image description here
* * *
!enter image description here | in Twenty Eleven, any featured image in a post or static page, with image dimensions larger than the size of the header image - 1000px width in the unedited theme - will automatically get used for the header image. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, header image"
} |
Add Default Wordpress Formatting To Data From External SQL Tables?
I have a number of external SQL tables that have data in exactly the way I want and I would like to use them to populate various wordpress posts with shortcodes.
The problem is that I don't understand how wordpress 'filters' text in get_content() so that the proper
and
are added.
IOW: I have a proper WP Post and I display the contents on a page it auto-magically includes
and
tags. If I copy that text to my external table and then pull that field into the same WP post using
$result = $wpdb->get_col( "SELECT my_text FROM my_songs WHERE id = '" . $song_id . "'" );
...the results has none of the `<br>` or `<p>`s unless I explicitly add them to the text.
How can I take $result above and 'format' it so that it matches the same text from a WP Post using `get_content()` ? | You can run the `the_content` filters on your data.
foreach ($results as $r) {
echo apply_filters('the_content',$r);
}
That should get you the same formatting as in your posts.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, database, formatting"
} |
Wordpress add_permastruct unwanted matches
I'm working on a project which involves filtering some customs posts on the front-end. I managed to create the permalinks including a custom field, but it seems that the rewrite rule matches some unwanted pages, making them not display-able on the frontend.
The code I use for rewriting :
$wp_rewrite->add_rewrite_tag('%competition%', '([^/]+)', 'competition=');
$wp_rewrite->add_rewrite_tag('%prize_category%', '([^/]+)', 'prize_category=');
$wp_rewrite->add_permastruct('competition', '/au/%prize_category%/%competition%/', false);
The problem is the following. It does what it should do for this url:
`
But it also matches this one:
`
Is there anyway I could force the second parameter `%competition%` to be **mandatory**? So the rule will apply only for URLs like:
` not for `domain.com/au/param1/` ?
Thanks, George | I've been struggling all morning to solve this and found your question when searching for the answer. I'm sure it's a little late for you now but in case anyone else stumbles across this question here's the solution I found:
Change:
$wp_rewrite->add_permastruct('competition', '/au/%prize_category%/%competition%/', false);
To:
$wp_rewrite->add_permastruct( 'competition', '/au/%prize_category%/%competition%/', array( 'walk_dirs' => false ) );
`walk_dirs` rewrites the "directories" that make up the URL structure and is set to true by default. Setting it to false ensures the rewrite is only used for the full URL specified. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, permalinks"
} |
wordpress not displaying my form
When I create a page with the content as `[contact-form-7 id="199" title="Untitled"]` , it displays the form, but when I use it as
<div class="first"><?php $recentProjects = get_post('275'); echo $recentProjects->post_content; ?> </div>
it is not working. It is displaying `[contact-form-7 id="199" title="Untitled"]` instead of form. | This is correct behaviour. A simple `echo` will just return the field from the DB, unmodified.
if you want to render the shortcode try
<div class="first"><?php $recentProjects = get_post('275'); echo do_shortcode($recentProjects->post_content); ?> </div> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "forms"
} |
Displaying cf post formats with oembed
Currently using CF Post Formats ( < ) and using the following code to automatically embed a URL that has been input into the 'Audio' or 'Video' custom field:
<?php echo wp_oembed_get( get_post_meta($post->ID, '_format_audio_embed', true) ); ?>
However, if oembed does not support the service (Eg. Spotify) and the user inputs the full embed code, it does not echo out anything.
How could I get around this so that if the user inserts code starting with something like:
<iframe...
then it won't use Oembed and instead it will display normally? | `<?php if (strstr($audio, '<iframe')) { echo $audio; } else { echo wp_oembed_get( get_post_meta($post->ID, '_format_audio_embed', true) ); } ?>`
Of course, this would require that you get the custom field with the audio embed code or url into $audio :)
Edit - try:
`<?php $audio = get_post_meta($post->ID, '_format_audio_embed', true); if (strstr($audio, '<iframe')) { echo $audio; } else { echo wp_oembed_get( $audio ); } ?>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post formats, embed, oembed, audio, video player"
} |
Does WordPress automatically do 301 redirect if I change permalink
I don't know how to check this but it seems to do the redirection when I change the permalink structure. | **Yes it does.** For a long time I could not find the answer too which made worry about changing. One day I just did it and checked. The _Firefox AddOn Live-Headers_ shows it very clearly. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "permalinks"
} |
Migrating from foo.com/wordpress/ to foo.com/ -- how can I do it?
I have a working wordpress installation at mydomain.com/wordpress/index.php (not a real domain). I want to migrate it to mydomain.com/index.php. How can I do that? I tried just unzipping a new copy of wordpress in the main domain space and copying over the config file, but I don't think I got it working, since it's not even giving me an error message--just a blank screen. Furthermore, going to mydomain.com/wp-admin/ seems to automatically redirect me to mydomain/wordpress/wp-admin. | You have to change Settings -> General -> WordPress Address (URL) and Site Address (URL) in the old installation.
WP looks in the DB at these settings and creates dynamic links, etc, from there, so you need to change it in the DB (either through these settings or by editing the db manually.)
Another option (and, actually, the better one) is to use a plugin which changes the links in the entire db - this will keep all of your links, images, etc. working properly.
I've used Velvet Blues Update URLS before many times, and it works perfectly. <
Just remember - if making this change with the WP backend (through the settings page or with a plugin), you should do it on the old site. Then it should be immediately accessible at the new location. (Or you could just move your files to the new location, preserving your themes, media, etc.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "migration"
} |
child of post type (custom)
I registered a custom post type (foo) with `register_post_type`, setting `'hierarchical' => true,`so now when I want to use it I have `post_type=foo`.
How can I query child of foo? any ideas?
thanks! | You can display child pages of particular parent foo page using following code ( using parent page ID ):
$the_query = new WP_Query( 'post_type=foo&post_parent=93' );
// The Loop
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
endwhile; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, query posts, child pages, post type"
} |
How to define theme translation file?
If I have WordPress installation in English, then I can define my theme translation file in the wp-config.php file with following:
define('WPLANG', 'sv_SE');
But if I have WordPress installed in the local language then there is already WordPress translation file defined there, then how can I define my theme translation file? | It all depends a bit if your current theme already supports localization.
Does your theme's function file contain something like this?
`load_theme_textdomain( 'twentytwelve', get_template_directory() . '/languages' );`
If not, add it in there. And change `twentytwelve` to your `theme-directory-name`.
After that create a directory called `languages` in the root of your theme a drop your localization file (`theme-directory-name-sv_SE.mo`) in there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation"
} |
Return selected categories only in custom page meta box?
I have a custom meta box added to the Page edit screen. I also have categories turned on for Pages.
I'm using `get_categories($post->ID);` to retrieve a list of categories, as you would in a page template, but it returns a list of all categories instead of just the ones selected.
Is it possible to only return selected categories?
Thank you. | Figured it out, I was using the wrong function.
Correct function was `get_the_category_by_ID($cat);` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, pages, taxonomy"
} |
List Wordpress.org Blog on Wordpress.com
I have a self-hosted blog at `www.MyPersonalSite.com/blog` that runs on the Wordpress.org platform. My buddy has a blog at `www.HisName.wordpress.com`.
He seems to get a lot more traffic to his blog. My inclination is that when he makes a post, it submits it to some central Wordpress blogroll. Is this right?
**Question:** Is there a way for me to list my blog such that it gets more exposure and people can search for it through Wordpress.com and subscribe to my posts? | The only potentially WordPress specific (in the context of this site) part of this question seems to me to be about adding an update service to the list used by WordPress.
If you are correct that `wordpress.com` sites submit to a particular blogroll, and if `wordpress.com` allows outside sites to submit, then you can tell your site to submit to their list by going to `wp-admin->Settings->Writing` and then scroll to the bottom to find "Update Services" and add the list address. The rest needs to come from wordpress.com support. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wordpress.com hosting"
} |
How do I disable the "by author" hyperlink on posts?
I'm trying to disable the "author" hyperlink when making a post, but having no success.
How can I do it?
!enter image description here | Look for `single.php` in your theme directory. There you should find `the_author()`, you can remove that to remove a reference to the author.
You will be able to find all your answers in the codex, by the way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, templates, author"
} |
wp_insert_post memory consumption
I'm using **wp_insert_post** in a loop to insert 500 posts in a new WP install. It works quickly, and memory usage is from 25M to 28M. The next run of a second batch of 500 posts, takes the memory from 25M to 178M. So the memory usage seems to be based on how many posts are already in the table. A third run of 500 posts exhausts the available memory. What is being stored to increase the memory that I can cleanup? | Did some profiling, it was the 5k+ queries being stored in the $wpdb->queries array. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp insert post, memory"
} |
Implement plugins as part of a theme
I have a couple of pluins which I use every time I create a new WP-page. Is there a way to implement these plugins as part of my theme? I have searched for a soloution for a couple of hours now, without any luck - hope someone can help :) | First, I would recommend against it.
I have a package of plugins that I use on almost all of our websites (both public and internal plugins)... and plugins should _really_ remain plugins. Deploying a package of plugins is not hard or time consuming and only needs to be done once per project.
By integrating them into a theme, you lose the ability to activate/deactivate them if necessary, nor can you update them. Please consider that first.
Ok, so to incorporate them into your theme, this is what you would do...
1. Create a "plugins" folder within your theme.
2. Place both plugins in that folder.
3. Within your functions.php file, use require_once to load each of the plugins default php files (if the plugin authors correctly followed convention, the main plugin file will be the one that matches the plugin folder name).
4. Done.
Please also take note that you may have problems with activation/deactivation functions... so be careful. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, themes"
} |
Self-hosted blog Admin Panel Forwarding to WP.com
I was goofing with the settings (first problem) in the "General" tab of my wp-admin panel on my self-hosted blog.
There are two settings: Wordpress.com URL and Blog URL (or something). They were both originally set to my self-hosted `www.domain.com/blog`. I thought if I changed the Wordpress.com URL to an empty blog that I set up on Wordpress `www.myblog.wordpress.com` that it would simply connect the two blogs so that my site went into the Wordpress.com directory.
**This did not happen.**
Now, if I visit MY self-hosted URL, I see my blog, but it's clearly missing a stylesheet. And now I can't access the admin panel of my own blog. I don't know what happened.
Can I remedy this? Is there a file on my server where I can just edit the line that I changed and switch it back to what it should be? | This is sort of two questions in one, but to solve your first problem and get your blog working again you need to edit your MySQL database. If you have access to PhpMyAdmin open that up and find the `wp_options` table. Inside the table there are two values to change `siteurl` and `home` are the names I believe. Change these both to ` or whatever the appropriate link is and this hould get things working again.
The second question, if I am understanding correctly, is how do you cross post from a self-hosted WP install to a WP.com install simultaneously? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wordpress.com hosting"
} |
Custom image size doesn't work
I'm developing my own theme. I'm trying to remove the default WordPress image sizes medium, large and full. I also want my own image size, `vividflow-full-width`. I'm using this Sumtips tutorial.
At the `after_setup_theme`, this is runt:
add_image_size( 'vividflow-full-width', 682, 9999, true );
And at the `image_size_names_choose` action hook:
unset( $sizes['medium']);
unset( $sizes['large']);
unset( $sizes['full'] );
$myimgsizes = array(
"vividflow-full-width" => __( "Full width" )
);
return array_merge($sizes, $myimgsizes);
However, at the insert media screen, I only see the option to insert a thumbnail. What's going wrong?
I'm sure the functions both codes are in are runt. I don't see any errors in my error log, nor get I any notices when setting `WP_DEBUG`. | Your custom size will only show up as an option if the selected image exists at those dimensions. So, have you uploaded any images since adding the new image size to functions.php? If not, then you won't see the vividflow option.
You could always run regenerate thumbnails so bring your older images up to date. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, images"
} |
Wordpress REST endpoint with JSON for Mobile App integration
Is there some REST API that Wordpress supports, out of the box or through any plugin that exposes the same information exposed through the normal pages? (I.e. latest posts, filtering by categories etc.)
There seems to be a JSON API plugin but it seems to be very old and not maintained.
There also seems to be some plugin called Jetpack but not sure if it provides what I am looking for (seems more dedicated to content management rather than exposing it publicly).
I am trying to integrate a Mobile App with a Wordpress Blog, and I need to find the best way to transfer the information to the application in terms of performance and also displaying it right. (Any ideas appreciated) | The REST API can be used for straight-up retrieval on any blog that has enabled it. Self-hosteds require an active choice to turn the JSON interface on in Jetpack but once it's up it's wide open.
This is not necessarily appreciated by everyone, and that's somewhat understandable. I picked a blog ID at random here for the /posts/ call:
<
That's the full output. If you were trying to make life marginally harder for scrapers by only providing excerpts in your RSS feed then this pretty much undoes that. It's a pretty false sense of security - if your blog is public then it's scrapeable - but not everyone loves this fact.
For your purposes you can absolutely just use the API to pull individual posts and display them in an alternate manner. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "mobile, json"
} |
How to disable or hide "collapse menu"
Is there a code in functions.php that I can add to disable or hide "collapse menu" button?
The one that is on the left side of the admin menu in the dashboard. I'd need it for both admin, authors, contributors. | Here is a simple css display: none function, it just adds some css in the html, if there are more stuff that you want to hide i recommend you to add a new css-file with the function admin_enqueue_scripts
function wpse_remove_collapse() {
echo '<style type="text/css">#collapse-menu { display: none; visibility: hidden; }</style>';
}
add_action('admin_head', 'wpse_remove_collapse'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "wp admin, dashboard"
} |
Display current taxonomy term when inside custom post type
Well, this should be pretty simple, however I couldn't find answer anywhere on the web. all answers I found were close but no exactly what I needed. what I need is to display just the current term of a custom post type I am in. **not all the terms just one!** (the relevant one)
this is what I'm using but it displays ALL the terms which is not good for me:
<?php
$taxonomy = 'genre';
$queried_term = get_query_var($taxonomy);
$terms = get_terms($taxonomy, 'slug='.$queried_term);
if ($terms) {
foreach($terms as $term) {
echo $term->name;
}
}
?>
remember - I would like to display it in my single post type template can anyone suggest? thanks | Ok, so I finally found what I needed here: How to get current term in my custom taxonomy in WordPress?
the last update at the bottom courtesy of @user3208:
<?php // Get terms for post
$terms = get_the_terms( $post->ID , 'oil' );
// Loop over each item since it's an array
if ( $terms != null ){
foreach( $terms as $term ) {
// Print the name method from $term which is an OBJECT
print $term->slug ;
// Get rid of the other data stored in the object, since it's not needed
unset($term);
} } ?>
That solved my issue! Thanks | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 8,
"tags": "custom post types, custom taxonomy, terms"
} |
Add read more to the_content
Hi I have a custom post type that i've truncated on the archives pages using this:
function limit_the_content($content){
$word_limit = 35;
$words = explode(' ', $content);
return implode(' ', array_slice($words, 0, $word_limit));
}
How would I add a read more and a link to the end of each post.
Thanks in advance. | You could add a link manually like:
<a href="<?php echo get_permalink($post->ID) ?>">Read More...</a>
If you want to add the link at the end of the content you could do:
return implode(' ', array_slice($words, 0, $word_limit)) . '<a href="'.get_permalink($post->ID).'">Read More...</a>'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "the content, custom post type archives, read more"
} |
Remove rel="attachment wp-att-XX"
When you add an image with "Add media" to the WYSIWYG editor the link around the image automatically gets a rel="attachment wp-att-XX". I would like to remove this with a script - Can anyone help me? :) | You can remove it right before post is printed to the screen by stripping it out from content. But remember it still will meddle in Editor.
<?php
function my_remove_rel_attr($content) {
return preg_replace('/\s+rel="attachment wp-att-[0-9]+"/i', '', $content);
}
add_filter('the_content', 'my_remove_rel_attr'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images"
} |
Multiple templates for single custom post type
Does anybody know of a way to modify the wordpress template process so that a single custom post type can be displayed on two separate templates based on the value of a custom field.
For example I have a single Custom Post Type called "plans"
It is using the single-plans.php and archive-plans.php files as templates by default.
What I would like to do is use this bit of code to filter out some of the results within my loop.
<?php //Filter the results based on the presence of $var
$var = get_post_meta($post->ID, 'my_custom_field', true);
if($var !== '') { ?>
THE LOOP
<?php } ?>
This works fine but i need create two separate templates where I can test for separate $var so I can have two menu items that each call on a separate version of the template and get a unique set of results from my single CPT
Thanks, Eric | Might be side-stepping your question, but can you use get_template_part?
<?php
get_template_part( 'plans', get_post_meta($post->ID, 'my_custom_field', true ) );
?>
Then create "plans_plana.php" and "plans_planb.php" (assuming that 'my_custom_field' can have values of 'plana' and 'planb').
twentyten and twentyeleven make heavy use of get_template_part if you need some more examples. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, page template, template tags"
} |
learn to run wpdb class
I want to learn how to run commands through WP rather than SQL commands
I have a SQL command:
SELECT
post_id,
(select meta_value from wp_postmeta where meta_key = a 'geo_latitude' AND x.post_id = a.post_id) as lat is NOT NULL,
(select meta_value from wp_postmeta where meta_key = b 'geo_longitude' AND x.post_id = b.post_id) as lon is NOT NULL,
(select meta_value from wp_postmeta where meta_key = c 'address' AND x.post_id = c.post_id) as the address is NOT NULL
FROM elreal_postmeta x group by post_id, lat, lon, address
Can I run this command into the `wpdb` class? | Arbitrary SQL query can be run via `wpdb` by using `get_results()` method:
$results = $wpdb->get_results( $query );
You can work through documentation for `wpdb` at Codex to gain basic understanding of how it works. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, sql"
} |
Thumbnails for media Library images
I have somee Item in the media library, where I want to retrieve the thunbnail from. I use the normal post thumbnail functions (tried some of them), with normal posts or cpts's the work fine.
As media library items are handled, similiar to posts, I thought the normal wp thumb function could work there, too. There are also thumbs created, as i can see on the server.
But no one fo WP's Thumb Fuunctions returns that thumb.
Here an example Function, I use:
<?php echo get_the_post_thumbnail($post->ID, 'size-1'); ?>
The post ID is correct. The Thumbnail size is registered and works for other posts fine.
Thank YOu! | `wp_get_attachment_image($post->ID, 'size-1');`
The "post thumbnail" actually gets the featured image that is attached to the post. For an attachment, you want the attachment itself in a specific size, which isn't the same as the featured image. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, post thumbnails, media, media library, thumbnails"
} |
Why doesn't default Wordpress page view use force_balance_tags?
I noticed that the default WP theme uses force_balance_tags for listing posts' excerpts. This way, it doesn't cause major html breakage whenever someone writes a post like
<div><b>This is an excerpt. <!--more--> and this is more text... </b></div>
It will close tags instead of bolding everything, and breaking div.
Why doesn't the normal wordpress page do this by default, in the default theme? That way, broken page content like:
</div></div> now text is not where it's supposed to be </div> unmatched tags
would not cause unexpected behavior.
Was this an oversight, or are there certain things that break when using force_balance_tags on pages? | `force_balance_tags()` is not a really safe function. It doesn’t use an HTML parser but a bunch of potentially expensive regular expressions. You should use it only if you control the **length** of the excerpt too. Otherwise you could run into memory issues or some obscure bugs.
The other problem is: the function uses two hard-coded lists of elements for single tags and nestable tags. There are multiple places where WordPress uses such lists, and they are not kept in sync. So when you use an element that isn’t part of these lists or changed its nesting behavior you may end up with incorrect markup. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "theme development, themes, html"
} |
How to test if the widgetized area has any widgets?
I making a widgetized footer with three widgetized areas (footer1, footer2, footer3), The problem is that even if there's no widgets assigned to any widgetized footer area, the footer is still there with his black background! what I want is to remove the footer if there isn't any widget assigned. | I would use the `is_active_sidebar()` conditional:
<?php
if ( is_active_sidebar( 'footer' ) ) {
?>
<div id="sidebar-footer">
<?php dynamic_sidebar( 'footer' ); ?>
</div>
<?php
}
?>
That way, you can conditionally output the styled container itself. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets"
} |
Hide certain widgets from specific user roles in admin
I'm looking for a way to hide certain widgets from specific user types in the admin, `Appearance > Widgets` page?
For instance, admins can see all widgets, but authors can only see a select few?
I noticed there was a Code Canyon plugin, but it requires a framework with it also which I am not using. | You have to check for Roles and Capabilities in the action hook `widgets_init` and proceed accordingly.
add_action( 'widgets_init', 'remove_widgets_wpse_89138' , 15 );
function remove_widgets_wpse_89138()
{
//
if( !is_admin() )
return;
// Grab current user info
global $current_user;
// Check for specific user
/*
$username = $current_user->user_login;
if( 'the_user_login' != $username)
return;
*/
// Check for capability
if( current_user_can( 'add_users' ) )
return;
unregister_widget( 'WP_Widget_Pages' );
}
Q&A's of interest:
* Prevent widgets removal
* Limit number of Widgets in Sidebars | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, widgets"
} |
How to order posts in an arbitrary order?
I need to list posts in a very specific order that has nothing to do with the date of the posts or the title, or anything WordPress can figure out for me. I need this order to be used when I list posts in a category and on the category archive page itself.
Is it possible to do something like this, were $idlist was an array of post ids in the order I want, and it could loop through each one?
<?php query_posts(post_id=$idlist); ?>
<?php the_permalink(); ?> etc... | First off, `query_posts` is terrible doesn't use it. It does all kinds of fun things like mess up the very useful conditional tags like `is_singular` and the like as well as mess up pagination.
Short of hooking into the `posts_orderby` filter and writing some custom order by SQL, your best bet is to use the `post__in` argument combined with the `post__in` orderby argument that was added in WP 3.5.
Example:
<?php
$custom_query = new WP_Query(array(
'post__in' => array(1, 2, 4, 5, /* whatever your post ID's are here */),
'orderby' => 'post__in',
));
while ($custom_query->have_posts()) {
$custom_query->the_post();
// use the normal template tags here
?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php
}
// restore the original query
wp_reset_query(); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "posts, loop, query posts"
} |
WordPress get posts by date without query_posts
I'm want to get posts from the last 30days in a sidebar but I don't want to use query_posts, is there a way to achieve this with the get posts function? | Yes, simple add a filter before you call it and remove it after you do
function filter_where_wpa89154($where = '') {
//posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where_wpa89154');
$args = array(
'posts_per_page' => 5,
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => false
);
$posts = get_posts($args);
remove_filter('posts_where', 'filter_where_wpa89154');
notice the `'suppress_filters' => false` which is what makes this happen with `get_posts` | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "posts, query posts, get posts"
} |
Allow shortcode in the author bio textarea
Is it possible to make shortcodes available in the Author bio textarea? | It a matter of using **`do_shortcode`** in your `author.php` template file (or wherever applies). This function has to be "`echo`ed". And instead of using `the_author_meta` (which `echo`'s the result), use `get_the_author_meta`.
<?php echo do_shortcode( get_the_author_meta( 'description' ) ); ?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "shortcode, author"
} |
Why do I get a WAMP homepage when clicking on specific website's URL on LocalHost?
Using WAMPSERVER for windows 7, smartgit and Safe Search Replace I have pulled a wordpress code from my git, downloaded a database and inserted into my localhost's phpmyadmin. My home page works but when I click on one of the links I get the WAMP homepage. What am I doing wrong?
I have tried the following in WP-Config to use the localhost URL instead of the one saved to the database but it didn't work:
define('WP_HOME','
define('WP_SITEURL',' | Ok, based on that, I'm almost positive that you need to re-enable permalinks for your site. You are probably missing your .htaccess file or it is missing WordPress's rewrite rules.
Go to your admin and find Settings > Permalinks. Select an option, and click "Save Changes" _twice_ (there is a quirk that this avoids).
This will have WordPress automatically regenerate your .htaccess, which appears to be your problem. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp config, localhost, phpmyadmin"
} |
Using query_posts inside single.php loop
Inside of my loop in single.php, I used a custom query using `get_posts` to return posts belonging to a certain category.
<?php global $post;
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$myposts = get_posts("paged=$paged&category=5");?>
<?php foreach($myposts as $post) :?>
<?php the_title();?>
<?php endforeach; ?>
The problem is that the original loop, which is the single.php loop, seem to do not work after the execution of the query. For instance, the navigation links (next and previous) dont work.
Have you ever faced this issue? your help is appreciated. | You need to call `wp_reset_postdata()` after your query to restore the global `$post` variable that the navigation link functions use to determine the next/previous posts. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "navigation, get posts, globals"
} |
Javascript block in Twenty Twelve theme
I am authoring a WP plugin, and I have to generate some JS (jQuery) code in "realtime". It is working fine in general, though I've stuck with one problem with the WP 3.5.1 and its default Twenty Twelve theme: there the scripts are inserted in the footer of the page, not in the header, causing my code to throw errors.
I've looked through all the theme's files (header, footer, functions), and I can't seem to find the reason for that. Looks like the `wp_footer()` is inserting the block, but I can't find any hook or anything else that tells WordPress to insert scripts there.
So, my question is: how to make jQuery and other scripts go in the header by default, not in the footer? What does make the theme work this way (maybe the default WP behavior changed?) | By default when you use `wp_enqueue_script` the script is inserted into the `<head>` section. This is usually set in `functions.php`.
The argument also has a footer option called `$in_footer`, if you set this to true, the scripts will instead be added to the footer section. In TwentyTwelve there are several calls to `wp_enqueue_script` with footer set to true.
For example:
wp_enqueue_script(
'twentytwelve-navigation',
get_template_directory_uri() . '/js/navigation.js',
array(),
'1.0',
true
);
To remove the footer calls you can `wp_dequeue_script` it, then requeue it for the header or just add `false` for the 5th parameter. <
Ref:
wp_enqueue_script(
$handle
,$src
,$deps
,$ver
,$in_footer //this
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, scripts, theme twenty twelve"
} |
Container class not appearing on navigation menu
I want to render a menu with a container like this:
`<nav class="nav">`
However, the container is just rendering with the default class name applied which I don't want.
`<nav class="menu-main-nav-container">`
I can't understand where I'm going wrong. Here's my code:
if ( has_nav_menu( 'nav-menu' ) ) {
wp_nav_menu( array(
'theme_location' => 'nav-menu',
'container' => 'nav',
'container-class' => 'nav',
'items_wrap' => '<ul id="%1$s" class="clearfix %2$s">%3$s</ul>' ) );
}
Anyone able to help? | You should use
'container_class' => 'nav',
instead of
'container-class' => 'nav',
You can check out the parameters here:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "menus"
} |
Usage of filters
Why is the filter removed after fetching feeds in the following example (from WordPress.org?)
<?php
function return_7200( $seconds )
{
// change the default feed cache recreation period to 2 hours
return 7200;
}
add_filter( 'wp_feed_cache_transient_lifetime' , 'return_7200' );
$feed = fetch_feed( $feed_url );
remove_filter( 'wp_feed_cache_transient_lifetime' , 'return_7200' );
?> | The filter is added before the call to `fetch_feed`, then immediately removed so only that particular feed is given a different feed cache transient lifetime. Any other `fetch_feed` calls within the lifetime of the request won't have that filter applied, so will be given whatever the default cache transient lifetime value is. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.