INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Get images attached to a specific page
Is there a way to fetch the URLs and captions of all images attached to page _x_? | $is = get_children("post_parent=$id&post_type=attachment&post_mime_type=image");
foreach($is as $i) {
$url = wp_get_attachment_image_src($i->ID, 'full');
$caption = $i->post_title);
}
$id is the id of your post. See < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, uploads, attachments, media, media library"
} |
Change Font Size on Blog (Twenty Twelve)
I have a Twenty Twelve child theme. I love the fonts on the site. I am willing to live with the normal font size that Twenty Twelve has on pages like the home page. However, on pages like the blog, I want to have a nice big font that is easy to read (see the size on Medium.com). The questions is how do I increase the font size on the blog posts only, and not the rest of the site. Thanks in advance, Shaan | Try to add those styles with the CSS class `.single` or `.single-post`. Because it's a child theme you'll probably need to use `!important` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme twenty twelve"
} |
Custom post type within a subdirectory
I've searched around but have not been able to find an answer to my question.
What I'm trying to do is create a custom post type that exists within a sub-directory, not just after the root as is default.
For example right now I have:
<
I would like to have:
<
The reason I'm trying to do this is that I have a client that now has additional clients that I would like to have named as a sub-directory, and not an entirely new sub domain.
I was planning on creating custom post types to create the additional blogs or the two other clients, but I can't find a way of having a sub-directory first.
Is there an easy way to do this? I'm decently versed in WP but not an expert, so I'm hoping there is an easy-ish method.
Thanks for any guidance | When you register your post type, add the subdirectory to the `has_archive` argument, and as the `slug` argument of the `rewrite` argument:
$args = array(
// ... other args removed for clarity
'rewrite' => array( 'slug' => 'subdirectory/custom-post-type' ),
'has_archive' => 'subdirectory/custom-post-type',
// ...
);
register_post_type( 'your_cpt', $args ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "custom post types"
} |
The conditional logic only works to show or hide?
I am using the Advanced Custom Fields for custom fields in the User Profile. I use conditional logic to display one of between four fields, each field will be displayed according to a radio field option previously clicked.
In this case only one option would can be sent. But, when the user update your profile all four fields are being sent.
The conditional logic in this case is only serving to show or hide.
Some tip on how to improve this?
I appreciate any help. | This is a limitation of how showing/hiding fields works with Javascript, and how Wordpress saves meta-data. Probably the best way to handle it is to use the same type of switch logic where you want to use the data. something like this:
switch ( get_field('radio_field') ) {
case 'first_option':
// get data from your first field
break;
case 'second_option':
// get data from your second field
break;
//etc
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, conditional content, advanced custom fields, radio"
} |
Strip post_tags from list of returned taxonomy terms
Thanks to GhostToast for helping me on my way with this post.
Now I am successfully able to echo out all of the taxonomy associated terms dynamically. However, this unfortunately also seems to spit out all the site's post_tags too.
So how can I use the following code, but not show the standard post_tags (I'd like to keep the post_tags available for use, just not show them as a result of this query)
// taxonomy term archives
$post_type = get_post_type();
$taxonomies = get_object_taxonomies($post_type);
if(!empty($taxonomies)){
foreach($taxonomies as $taxonomy){
$terms = get_terms($taxonomy);
if(!empty($terms)){
echo "<ul>";
foreach ( $terms as $term ) {
echo '<li><a href="'.get_term_link($term->slug, $taxonomy).'">'. $term->name . "</a></li>";
}
echo "</ul>";
}
}
} | Use this function to determine if Taxonomy is hierarchical or not:
Function Reference/is taxonomy hierarchical « WordPress Codex
Example:
// taxonomy term archives
$post_type = get_post_type();
$taxonomies = get_object_taxonomies($post_type);
if(!empty($taxonomies)){
foreach($taxonomies as $taxonomy){
// only want hierarchical -- no tags please
if(is_taxonomy_hierarchical($taxonomy)){
$terms = get_terms($taxonomy);
if(!empty($terms)){
echo "<ul>";
foreach ( $terms as $term ) {
echo '<li><a href="'.get_term_link($term->slug, $taxonomy).'">'. $term->name . "</a></li>";
}
echo "</ul>";
}
}
}
} // this was missing | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "advanced taxonomy queries"
} |
Why tags are displayed bellow the content and not inside
I am developing a theme for myself and I was wondering why wordpress tags are allways displayed bellow the_content.
I know that this can be done via shortcode, but I would like to know if this is for seo purposes, or there is any technical reason?
I´am asking because I didn´t find any information on the web...
My code:
in functions.php (found in here)
function tags_in_post($atts) { // [tags] outputs post's tags in a span
global $post;
$tags = '<span class="post-tags">';
ob_start();
the_tags( '<span class="post-tags">', ', ', '</span>' );
$tags = ob_get_contents();
ob_end_clean();
return $tags;
}
add_shortcode ('tags', 'tags_in_post');
Than this shorttag [tags] must be used inside the wordpress editor.
Thanks | So if I look closely, seems our actual question is "Why does WordPress put Post Tags at the bottom of a Post?"
The answer depends on the theme, of course. But, most themes put them after a post's body so that you can use it as part of browsing away from that post, to get involved with further reading. Basically like saying, "You've been reading about: Toys, Babies, Books" where each of those items is a link to, presumably, articles on those topics.
The idea of having them at the end of the article is so you don't get bored too quickly and jump off to read something else.
Unless you mean something else by `tags` as that can be a pretty vague thing around these parts. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, tags, the content"
} |
Renaming/translating "your profile" page
I need to rename/translate the "Your Profile" page. I've used the function below
function pietergoosen_hoofskerm_vertaling( $translated ) {
$words = array(
'Name' => 'Naam',
);
$translated = str_ireplace( array_keys($words), $words, $translated );
return $translated;
}
add_filter( 'gettext', 'pietergoosen_hoofskerm_vertaling' );
The problem is, this change all instances of Name to Naam, even when name is part of word or sentence, like 'UserName' get changed to 'UserNaam' and 'Display Name publicly as' get changed to 'Display Naam publicly as'.
Any other ways to this | This is more of PHP implementation detail. If you want a precise match you can do something like:
if ( isset( $words[$translated] ) )
return $words[$translated];
return $translated;
PS you might want to declare `$words` as static, so that array is reused and not continuously re-created on each function call (which would be _a lot_ of calls with `gettext` hook). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "profiles, translation"
} |
Remove wordpress author's capability to moderate comments on their own posts
WordPress authors have permission to edit others comments on their own post. How to disable this and still allow the authors to edit their published posts? | From quick look at code the likely permissions check for that is `edit_comment` capability in `edit_comment()` function.
Your options to remove that capability roughly are:
* customize the role with plugin, for example Members
* customize role with code, probably using remove cap functionality
* filter thiungs around `map_meta_cap` or `user_has_cap` if you need to achieve more elaborate logic (for example denying permission in context of specific comment, rather than comments in general)
PS not sure if this will properly omit related parts of interface, might need to deal with that separately | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "user roles, author, capabilities, permissions"
} |
Is there a reason I cannot get the current category in a loop?
I think I am doing this wrong but if I do:
if(have_posts()){
$category_id = get_query_var('cat');
var_dump($category_id);
while (have_posts()){
the_post();
}
}
the var dump comes back empty. Why? Is there a better way to get the current category object in a loop? the same question applies to tags. Can I also get the current tag object if this was a `is_tag()`? | `get_query_var` will get the category from the main query, and it is only going to be set for some pages, such as category archives. It is not set for "single" pages or tag archives or a many other kids of "pages".
The value that `get_query_var` returns is something like a 'search' variable. It will be set when the query is instructed to look for posts in a particular category. It doesn't reflect the value of current post in the Loop, though of course if `get_query_var('cat')` is set then all posts should be assigned to that category.
What you want to get the category for the current post in the Loop is `get_the_category`, but it should come after `the_post`. `get_the_tags` will do the same for tags and the more generic `get_the_terms` can be used for any taxonomy. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, loop, tags, conditional tags"
} |
How to best delete orphan wp_postmeta
I'm in the middle of doing some fairly complex queries involving metadata from a custom post type. Unfortunately if any posts are deleted the metadata stays put which complicates matters as I am counting it.
I was wondering how best to go about deleting the orphan metadata in the event that the post is deleted.
Should I include a function that deletes them the database through $wpdb?
I found an SQL query that does just that but I'm not sure how to format it.
DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL
I tried it in phpmyadmin on a backup copy of my database but to no avail. | This snippet is good enough, use it with `$wpdb`. In this case I would use :
<?php
add_action( 'before_delete_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
?>
Source | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "custom post types, post meta, wpdb"
} |
How do I disable a plugin enforced by my host (in mu-plugins)?
My host makes mandatory two plugins which get automatic updates under mu-plugins folder.
Is there a way I can disable them with some trick, for example with a plugin folder of the same name under my local plugins folder or by duplicating some function and make them empty? | You disable mu-plugins by removing the plugin file from the `mu-plugins` directory. They are outside the normal plugin activation/deactivation cycle "and cannot be disabled except by removing the plugin file from the must-use directory, which is found in wp-content/mu-plugins by default." I assume you don't have the authority to remove the files.
The plugins may be using hooks and you may be able to remove some actions or filters and disable all or part of the plugins functionality, but without knowing how the mu-plugins work it is impossible to say how.
But... I suspect your host would **_shut down your site_** if you succeed in circumventing something they _require_. I imagine that requirement to be somewhere in your Terms of Service and not really a surprise to you. If you don't like the requirement, get another host. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "plugins"
} |
Dark Bar at the top of wordpress page can't be seen?
I am new to wordpress and created a website as shown in the picture bellow. My webpage used to have a black bar at the top, which allowed me to insert "New Posts". (area shown in red circle). But this black bar is gone from my wordpress site now. Can you please tell me how can I get it back?
Image Link: < | Some things you have to check:
1. Check if `wp_footer` function is called in your footer.php file.
2. Check if the toolbar isn't disabled in your user settings.
3. Check if toolbar is showing after disabling all plugins you are using. If yes, then turn plugins on one by one to find out, which one of them is hiding the toolbar.
4. If disabling plugins didn't help, switch to some standard WP theme (Twenty...). If it helped, then it is some problem with your theme. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, php, options"
} |
add_post_meta -- not working
I am trying to insert data into wp_post and wp_postmeta tables but it seems like i am doing something wrong.
Here is my code:
$post_data = array(
'post_title' => $data[0],
'post_content' => $data[1],
'post_status' => 'publish',
'post_type' => 'product'
);
$id = wp_insert_post($post_data);
add_post_meta($id, '_stock', $data[6]);
add_post_meta($id, '_price', $data[7]);
The post is inserted as it should but when i check the postmeta table no values had been inserted. I also tried the update_post_meta but still doesn't work.
Any suggestions? | What user34296 said is `update_post_meta()` will update the value of the existing meta key (custom field) for the specified post. If it does not already exist it will call `add_post_meta($post_id, $meta_key, $meta_value)` instead. That's why you should use it.
**EDIT: in this case it should work, error is coming from another part of the code.**
Source | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, wpdb"
} |
what's the meaning of the field wp_capabilities in table wp_usermeta
I am new to wordpress, in table `wp_usermeta` I notice that we have a row
meta_key meta_value
wp_capabilities a:1:{s:13:"administrator";b:1;}
First, what's the meaning of meta_value `a:1:{s:13:"administrator";b:1;}` , where can I found the exactly explanation of this filed ? Or I what to know all about the `role` `user` `Capabilities` , where can I get these information.
Second, how can I create new roles via `wordpress's API` by code
Thanks in advanced. | The wp_capabilities saves the value as serilized array, you can try it in your php or for this example here: <
The Code:
a:1:{s:13:"administrator";b:1;}
Is:
Array
(
[administrator] => 1
)
Meaning the user is an administrator.
You can add new roles to the database by running the function add_role, and only run it **once**! | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 10,
"tags": "plugin development, user roles, capabilities"
} |
how do I add role and capability after I create a new user
I have a simple requirement:
1. create a user
2. create a role for the user
3. add capability for the role
First, create a new user
$uid = wp_insert_user($userdata);
Second & Third, create a new role and adding capability on it
add_role( $role, $display_name, $capabilities )
How can I make the relationship between the role and the user ? | You should use WP_User class (<
It has methods: set_role, add_role, remove_role.
Example:
$uid = wp_insert_user($userdata);
$u = new WP_User( $uid );
add_role( $role, $display_name, $capabilities ); // I assume $role, $display_name, $caps are already set before
$u->set_role( $role ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, user roles, user meta, capabilities"
} |
How to programatically change username (user_login)?
As in the title, how to programatically change user's login?
I wanted to use `wp_insert_user` function, but it appears that when updating current user, it doesn't change their username. Should I use `$wpdb->update` for that? If yes, how would code for changing username look like? What consequences would changing user login have, given that WordPress API doesn't allow changing usernames? | I was sure that `wp_update_user()` should do this.
It even gets user_login as param, but it looks like it ignores it, when you set this param.
So this code looks OK, but it doesn't work as you wish it did :( :
wp_update_user(
['ID' => $user_id, 'user_login' => $new_login]
);
You have to call custom SQL query to update user_login:
global $wpdb;
$wpdb->update(
$wpdb->users,
['user_login' => $new_user_login],
['ID' => $user_id]
);
It works OK and I don't think it has any serious consequences, because WP uses users ID to assign posts/comments (and so on) to user.
The only problem I can think of is that when this user is currently logged in, he will be logged out after user_login change. | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 18,
"tags": "users, wpdb, user access"
} |
Auto-fill Custom comment fields
Thank you for reading,
I added custom fields to the comment form, and saved the input in the DB, following this tutorial <
Now i'd like the meta-fields in the comment form to auto-fill after the user has commented once.
Just like wordpress does with the Name, E-mail and Url; once you've commented the value stays in the fields. However, wordpress does this with $commenter['comment_author'] and this array doesn't have the data I'm looking for. | You can store these values in cookies and fill them when you are creating form inputs.
So in `save_comment_meta_data` add something like this:
$commenter_data = array(
'phone' => $phone,
...
);
setcookie('commenter_data', serialize($commenter_data), time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);
And then when you're creating form:
$commenter_data = isset($_COOKIE['commenter_data']) ? unserialize($_COOKIE['commenter_data]) : array();
echo '<p class="comment-form-title">'.
'<label for="phone">' . __( 'Commenter Phone' ) . '</label>'.
'<input id="phone" name="phone" type="text" size="30" tabindex="5" value="'. (array_key_exists('phone', $commenter_data) ? $commenter_data['phone'] : '') .'" /></p>'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "comments, comment form"
} |
Apply the_content filter to a custom field with multiple values
I have a custom meta box set up that allows users to paste the Youtube URL of a video so that it can be embedded into a post/page.
The meta box can be repeated so that a user can add as few or as many URL's as they wish so I'm using this code snippet to display each as a list item;
<?php
$video = get_post_meta($post->ID, 'youtube-url');
foreach ($video as $vid) {
echo '<li>'.$vid.'</li>';
}
?>
Is there a way that I can run `the_content` filter on each individual list item so that I can make use of oEmbed that is shipped with Wordpress?
Or perhaps there's a more efficient way... | All you need to do use `apply_filters`.
foreach ($video as $vid) {
echo '<li>'.apply_filters('the_content',$vid).'</li>';
}
It _may_ be more efficient to concatenate a string and then run the filter on the whole thing.
$lis = '';
foreach ($video as $vid) {
$lis .= '<li>'.$vid.'</li>';
}
echo apply_filters('the_content',$lis);
I haven't benchmarked the one versus the other but given that the latter calls the filter once and the former many times, I'd bet on the latter. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 5,
"tags": "custom field, filters, oembed"
} |
Additional .htaccess rules based on wp page
I've created a page in the dashboard called Authors, created a new template-authors.php with completely own logic. It works well, going to website.com/authors/ I see a list of all authors, specifying the URL I can get to their details, for instance: `example.com/authors/?name=George`. I can also switch profile pictures: `example.com/authors/?name=George&pic=1`, `example.com/authors/?name=George&pic=2` etc (default is 1).
I'm trying for half a day get user-friendly URLs been working but can't figure out a correct way... I'd like to achieve this kind of links: `example.com/authors/George` and `website.com/authors/George/2`.
Tried even a really basic code in the `functions.php`, but it doesn't work:
add_rewrite_rule('^qwerty', 'index.php/authors/', 'top');
`example.com/qwerty` displays 404. | I'm pretty sure you have wrong "rewrite" parameter in your `add_rewrite_rule` call.
I'm writing it directly in here, so it can be buggy... But it should look something like this:
add_rewrite_rule('^authors/([^/]*)/([^/]*)/?','index.php?page_id=<YOUR AUTHOR PAGE ID>&my_author_name=$matches[1]&my_author_pic=$matches[2]','top');
Then you can use `add_rewrite_tag` (< to add your custom query variables (`my_author_name` and `my_author_pic`).
And in your author page you should use these custom query variables. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, htaccess, rewrite rules"
} |
Why Won't Exported Blog From One Site Import Into New Site?
I have an old RHEL Workstation site, running the latest wordpress version 3.5.1.
I have a newer CentOS 6.4 site, running the latest wordpess version 3.5.1.
I have added the Wordpress import plugin tool into the new site successfully.
I have exported the entire blog from the older wordpress site successfully.
I have attempted to import the resulting xml file, but it appears not to succeed, but without any errors or explanation.
The import appears to start successfully after pressing the button for uploading and importing, after the .xml file is selected, and I see some activity. However, the Import page goes blank, and there are no errors or any other kind of message.
The blog is still usable; that is nothing has frozen.
What do I need to do to import properly? | Here is what I did to fix the problem.
I looked at an export of the old blog after wordpress, php, and apache had all been upgraded.
I looked at an export of the mostly blank new blog (on the recently installed CentOS 6.4 system).
I made the title and other fields look the same for the first few lines in the xml file to be imported from the older blog.
Most of the XML required no editing.
Everything updated just fine after that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, import"
} |
How can I only display one link rather than many?
So using this snippet:
<?php
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(10, $childcat)) {
echo '<a href="'.get_category_link($childcat->cat_ID).'">';
echo $childcat->cat_name . '</a>';
}}
?>
I'm able to output all the child categories of the parent category with the id 106. However, I only want to output _one_ child category if there's more than one. How can I do this, please? | Just use the `break` statement to abort after the first cat that is found and that is a child category.
foreach ( get_the_category() as $cat )
{
if ( cat_is_ancestor_of( 10, $cat ) )
{
printf(
'<a href="%s">%s</a>',
get_category_link( $cat->cat_ID),
echo $cat->cat_name
);
break;
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Overriding a function in wordpress
A theme that I bought is adding unnecessary inline JS code that is not needed in the front page.
/* Scripts - dynamic css */
add_action('wp_footer', 'upme_custom_scripts');
function upme_custom_scripts(){
require_once upme_path . 'js/upme-custom-js.php';
}
I would like to add to my custom.js file an override so that I dont have to edit the core file in case it gets updated. Can this be achieved? if so please show me
I was thinking about overriding the function then registering and en-queueing the js file, but i dont know how to override it.
Thanks | Remove the action:
add_action('wp_footer', 'remove_upme_script', 0 );
function remove_upme_script()
{
remove_action('wp_footer', 'upme_custom_scripts');
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, wp enqueue script, pluggable"
} |
Import existing image as a single post
I want to add a bunch of existing images on the server but I want each of them added as a separate post instead of all images into one post. How can I do this? | See my answer here:
The Media Library lives in both wp_posts and wp_postmeta.
* wp_postmeta contains the image URL
* wp_posts contains an entry for each image insertion into a post, along with the post ID.
Exporting and importing these 2 tables as SQL did not work for me - I received 'duplicate entry for key 7'...
Exporting and importing these 2 tables as CSV did work, using "CSV using load data".
Before importing, I emptied the 2 tables in the recipient database. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, uploads"
} |
get_the_term_list() display in ul li and remove <a> tag
I want to remove tag in get_the_term_list()
<?php echo '<ul class="styles">';
echo get_the_term_list( $post->ID, 'portfolioType', '<li>', ',</li><li>', '</li>' );
echo '</ul>'; ?>
It's need to return
<ul>
<li>List one </li>
<li>List two </li>
</ul>
i tried with preg_replace() but not working | <?php $terms = get_the_terms();
echo '<ul class="styles">';
foreach($terms as $term){
echo "<li>".$term->name."</li>";
}
echo "</ul>";
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "terms"
} |
Custom theme template files
Im trying to create a Theme from scratch, its quite challenging, cause im new to WP. I follow this developing process at Teamtreehouse. All is very good, its just, im puzzled with the template file creation.
Its all fine with `front-page.php` and `home.php` files, but eventually I want to have as well the: `partnership.php`, `gallery.php`, `contact_us.php`, `prices.php` files too.
Anyhow, when I created the `partnership.php` file and linked it to display the Partnership webpage title with testimonials and link to the webpage, I got default `index.php` to display. I understand that WP will display the `index.php` if it does not find any other file in the structure, but the files are all in the `example.com/wp-content/themes` directory. Im working on localhost.
It seems that WP did not recognize the custom template files.
Share your thoughts on this please.
Many Thanks | If you want to use custom page templates, yo have to:
1. Create file for your template.
2. On beginning of your file add comment defining that this file is custom template file (`/* Template Name: One column, no sidebar */`).
3. Manually set that chosen page should use this custom template.
Of course you can also create custom templates for taxonomies, categories, and so on.
Here you can find great image showing how exactly the template to display is chosen by WordPress: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, pages, page template"
} |
How to include Related Posts in WP RSS feed
How to include Related Posts in WP RSS feed not use plugin? I have search around on google and stackexchange but have no result about this. Thanks all friends! | You have to use `the_content` and `the_excerpt_rss` hooks. You can do this like this:
function rss_append_footer($content) {
if(is_feed()) {
$related_posts_html = ... // I assume you already can compute it
$content .= $related_posts_html;
}
return $content;
}
add_filter('the_content', 'rss_append_footer');
add_filter('the_excerpt_rss', 'rss_append_footer'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, rss, feed"
} |
Prioritizing wp enqueue scripts error
I wanted to load the following two scripts before any other script so I added priority 1 and 2, however I am getting an error. I read it on a tutorial that this is how to prioritize
add_action('wp_enqueue_scripts', array(__CLASS__, 'frontend_enqueues', 1));
add_action('print_head_scripts', array(__CLASS__, 'print_js', 2));
> Warning: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in xxx/xx/xxx/wp-includes/plugin.php on line 406
>
> Warning: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in xxx/xx/xxx/wp-includes/plugin.php on line 173
Please advice :) | You got parentheses levels slightly wrong and that broke your callbacks.
It should be:
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'frontend_enqueues' ), 1 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp enqueue script, actions"
} |
Comments: Approve when admin Replies, from the Front end
Thank you for reading,
In the admin panel, when a comment is awaiting moderation, you can "Approve and Reply" in the same action.
However, in the front end, if you show the awaiting comments to the admin, and she hits Reply, the comment wont approve.
Does anybody know how to get the proper link, or where modify the code, to auto-approve comments when the admin replies ?
**Why:** I'm creating the site for a client, and trying to make it as easy as posible so she won't need to learn WP's admin panel. | Well... All you have to do is to check what hooks are available during comment posting.
The one I think might be helpful is `wp_insert_comment`. So you could do something like this:
function my_wp_insert_comment($id, $comment) {
if ( is_admin() && $comment->comment_parent ) {
if ( wp_get_comment_status( $comment->comment_parent ) == 'unapproved' )
wp_set_comment_status( $comment->comment_parent, 'approve' );
}
}
add_action('wp_insert_comment', 'my_wp_insert_comment', 10, 2);
Just place this code in `function.php` file of your theme. This function will be called every time a comment is inserted into database. No matter how (from admin area, front end or by some plugin, etc.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "comments"
} |
Load script only on selected Pages
The following function within my functions.php loads a JS script..
function my_scripts_method() {
wp_enqueue_script(
'myashdrop',
get_template_directory_uri() . '/js/dropdown.jquery.min.js',
array('jquery')
);
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
How could i modify this function so that the JS script is loaded only on specified pages (perhaps by providing their ID in the function's arguments..) | You can use conditional tag such as is_page(). Register your script on hook `wp_enqueue_scripts` and enqueue it in if statement :
wp_register_script('myashdrop',
get_template_directory_uri() . '/js/dropdown.jquery.min.js',
array('jquery'));
if (is_page(PAGEID)) { wp_enqueue_script('myashdrop'); } | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
Wordpress for questions and responses website
I am using Wordpress to create a Q&A website.
The question is returned by `the_content.`
If I store the answers as post meta field array:
{
[1] => 'first answer',
[2] => 'second answer',
[3] => 'third answer',
.....
}
How can I create separte comments for each item (comments for question, then comments for first answer, then comments for second answer....)? Noramlly, I use `<?php comments_template( '', true ); ?>` which creates comments relative to `the_content`. If I reuse it, it will display a new comment for all the items. `comments_template` doesnt have a pramater to identify a list of comments against other lists. | (adding answer from comments above)
Set up your Responses as a Custom Post Type. Then you can use WordPress's native comment system for, well, comments on the Responses.
To tie the Responses to the Questions, you can simply use something like `update_post_meta( $response_id, 'question_id', $question_id );`. See `update_post_meta()` for details. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments, post meta"
} |
Prevent child theme from inheriting a parent theme's required file
My parent theme has a file with a class that defines ads for that specific theme. It is required in functions.php. My child theme needs a duplicate file with different ad parameters so I would like to not include the parent theme's file.
Is there an easy way to ensure the parent theme file will not be required in the child theme? | You could use `is_child_theme()` in the parent theme's `functions.php` file:
if ( ! is_child_theme() ) {
require( 'path/to/ads/file.php' );
}
**Update**
If you don't want to edit the parent theme -- for instance, so that any updates to the parent theme won't overwrite what you've done -- you could do something like this in the child theme's `functions.php` file:
global $ads_class; // whatever your ads class is named
if (
is_child_theme() &&
(
class_exists( 'Ads_Class' ) &&
'Ads_Class' == get_class( $ads_class)
)
) {
$ads_class->__destruct();
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "child theme"
} |
how can i display all youtube videos from a users youtube account
I want to display all recently uploaded youtube videos from my youtube account as a widget on the right side of the page. Just like how technobuffalo.com has done. Is there such a plugin that will do this?
ps: as for what I've tried, i have searched on wordpresses plugin pages and all i see are plugins that allow me to add a short code for the video as a post. But this isnt what i want. I just want to display all recently uploaded videos automatically on the right side just like technobuffalo. | You can use YouTube developer API. Example how to get recent videos below:
$data = wp_remote_get('
$response = new SimpleXMLElement($data['body']);
foreach ($response->entry as $entry):
$vid_id = '';
if ( preg_match('#videos/([^/]+)$#', $entry->id, $matches) ) {
$vid_id = $matches[1];
}
if ( $vid_id ):
?>
<a href=" echo $vid_id; ?>">
<img src=" echo $vid_id; ?>/1.jpg" width="220" height="130" />
<span class="video-title"><?php echo esc_html($entry->title); ?></span>
<span class="video-description"><?php echo esc_html($entry->content); ?></span>
</a>
<?php
endif;
endforeach; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, youtube"
} |
select a single val though a table in wordpress
The table is like this:
category_id category_name category_parent_name
I would like to get `category_id` by using `category_name`. I searched online, and the code is like below:
`$ad_cat` is the category name.
global $wpdb;
$tbl_categories = $wpdb->prefix."awpcp_categories";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $tbl_categories where category_name =".$ad_cat );
$category_id=intval($retrieve_data->category_id);
I echo'ed category name and `id` for testing. The name shows fine, but `id` is always `0`. Any idea or solution? | Use the method `get_var()` instead. I've also tidied up your code (if you're gonna use double quotes, take advantage of them!) & added data escaping with the handy `prepare()` method.
global $wpdb;
$cat_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT category_id FROM {$wpdb->prefix}awpcp_categories WHERE category_name = %s",
$ad_cat
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, plugin development, database, mysql, wpdb"
} |
how to show only particular category post in archive widgets
i want to display blog category month list in archive widgets. but i i can't figure out yet how. i have more category like review, gallery etc. normally show all month list in archive widgets but i want only BLOG show in archive widgets. i already figure our how to show only blog post in archive page but now problem is widgets. any idea guys how ? | add_filter( 'getarchives_join' , 'getarchives_join_filter');
function getarchives_join_filter( $join ) {
global $wpdb;
return $join . " INNER JOIN {$wpdb->term_relationships} tr ON ($wpdb->posts.ID = tr.object_id) INNER JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)";
}
add_filter( 'getarchives_where' , 'getarchives_where_filter');
function getarchives_where_filter( $where ) {
global $wpdb;
return $where . " AND tt.taxonomy = 'category' AND tt.term_id='blog category id' ";
}
Change 'blog category id' with your blog category id. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, archives"
} |
Can I use a form in a dashboard widget?
I'm building a plugin and would like to add a dashboard widget with a custom form. In this form, users should be able to edit a list of strings (add, edit and remove items). Is there a WordPress API to do something like that? I already know how to add a dashboard widget, but I don't know how to make a form in a dashboard widget / how to process the data.
The only thing I can think of is to redirect the user to my options page - there must be a neater way. Is there any? | There are two options to use forms in a dashboard widget:
1. Use the parameter `control_callback`. See the Codex
wp_add_dashboard_widget(
'my_id', // $widget_id
'my_name', // $widget_name
'my_render_widget', // $callback
'my_control' // $control_callback
);
function my_control()
{
// print some form elements, WordPress will handle the <form> tag.
}
2. If you want to use a form in the main display handler, set the form action to `admin-post.php` and add a callback function for a custom `action` there. Example. When you are done processing the form redirect back to the dashboard. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins, plugin development, widgets, dashboard"
} |
Custom Post Type Template based on Taxonomy
I have a custom post type, Vehicles. Vehicles have a custom taxonomy, new or used. Naturally the vehicle pages use single-vehicles.php but I would like to differentiate between new and used vehicles by somehow using different templates automatically based on whether they're new or used.
For example, the New vehicles don't have certain attributes (Mileage, Year etc) as they're not relevant, so I would like to remove that from their template.
If this is possible, that would be great. If not I'd really appreciate any alternative ways around it. | I'm afraid you have to do this manually. You can put someting like this in your `single-vehicles.php` file:
if ( ... ) { // check if it's in used category/term
get_template_part('part-single-vehicles-used');
} else {
get_template_part('part-single-vehicles-new');
}
And then put new car template into `part-single-vehicles-new.php` file and used car template into `part-single-vehicles-used.php`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, templates, taxonomy"
} |
Refresh page using Cron after any post is published
I would like to refresh page after any post(custom post type) is published, how do I refresh page using the Cron after any post is published? Can anybody tell me in which direction should I go? I ve'been trying to google that info, but it seems that nobody were ever interested or it seems as impossible. | Well, I don't think you can do this with cron.
Browser sends request to server and gets response. It isn't connected permanently to your server. So if you want to refresh page which is already displayed in browser, you have to force browser to send request for this page one more time (do refresh).
Another way would be placing some JS on your page. It could send AJAX request every few minutes (or so) to your server and check if there is anything new to show and process them in any way you'd like. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "cron"
} |
Why archive page can't show full content?
I use "insert more tag" insert more tag for a post. It works fine, at front page show excerpt, at single page show full content. but at archive page show excerpt, I want show full content here. Here is the code in archive page.
<?php query_posts('cat=1&paged='.get_query_var('paged'));?>
<?php if (have_posts()) : while (have_posts()) : the_post();?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<?php the_content(); ?>
.........
no idea what's the rule for show full content or excerpt. | When there is `<!--more-->` tag inserted in post, this post will be truncated on lists pages.
You can use global `$more` variable to make WordPress think it's single page though. Here is your modified source:
<?php query_posts('cat=1&paged='.get_query_var('paged')); ?>
<?php global $more; $prev_more = $more; $more = 1; if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<?php the_content(); ?>
...
<?php endwhile; endif; $more = $prev_more; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "excerpt"
} |
Function to add class to <form> element?
I'm using the Sidebar Login script by Mike Jolley, I would like to add a class of "clearfix" to the element tag. I have been unable to find a solution to this so far.
I'd also like to understand any solution given, so if you would like to briefly explain how the function works I'd be very grateful. | That plugin does not create a `<form>` tag itself. It uses `wp_login_form` to do that, and that function does not provide a way to add a class to the `<form>` tag. You can see that by looking at the `widget` method, which is what generates the front end content.
I don't see a way to do what you want to do, but there is an action before the form-- `do_action( 'sidebar_login_widget_start' );`\-- and one after-- `do_action( 'sidebar_login_widget_end' );`\-- that would let you wrap the whole form in some other markup.
However, I very much doubt that you need to add a class to that tag. I would bet that you can do anything you need by writing CSS rules using the existing markup. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sidebar, forms"
} |
NextGEN Gallery: Use the same galleries on 2 or more sites on WP network (multisite)?
I have a wordpress network with 4 sites and i use NextGEN Gallery V1.9.13.
On the 2 sites (first and second on network) i use the same galleries. It is a bit waste of hosting space if I need to upload the same images on the 2 network sites.
Is there a possibility to use the gallery of first net site with the second net site?
I tried copy the ngg_options of wp_option(first site of network) to ngg_options of wp_2_option but it doesn't read the base of the first site | I follow the steps of this tutorial , on step 3 the only extra that you have to do is to replace all the base prefix from your site that whant to use the same gallery with the new one. If the main site is "wp_" and the subdomain that you want to use the same photos is wp_2yo u have to change on step 3 too.
Also,
**TAKE CARE NOT TO DESTROY YOUR WHOLE WORDPRESS INSTALLATION!**
1.look for the "wp_options"-table
2.edit the row "ngg_options"
3.in field "option_value" look for something like "gallerypath";s:31:"wp-content/blogs.dir/%BLOG_ID%/files/" and change it to "gallerypath";s:31:"wp-content/blogs.dir/galleries/" (or whatever you like your galleries-folder to be)
look for more tables like "wp_**_options" (where ** is the number of your blog, may be several depending of the amount of blog u set up), repeat step 2 + 3 for every wp_option table u find | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite, plugin nextgen gallery"
} |
English version of my site show french strings
This is a weird one :
< is the french version of the site < is the english one
The problem is that the english version show theme strings in french.
I have no idea why.
Infos : i use WPML and the network of websites wordpress features. | If these theme strings are prepared for translation and the theme is not in english by default (they're outputed with `__()` or `_e()` functions) and you include your theme textdomain correctly, then you probably haven't translated these strings to english.
WPML had/has some tool to do this, but it isn't very user-friendly (at least I don't like this tool). I'd suggest using Codestyling Localization plugin.
Install it, rescan your theme directory (it will find all translation strings) and then add missing translations. Don't forget to build `.mo` files after translating strings (without it new translations won't work).
EDIT: It occured that it was some problem with .po/.mo files. Installing Codestyling Localization and rebuilding translation files solved this problem. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation, plugin wpml"
} |
How about many "require_once" will affect the page load speed?
In the `functions.php` I pretty much use the function `require_once` to call about 30 files in my wordpress theme. (30 times use `require_once`)
How about that will affect the page load speed?
Have there any way to more optimally? | To me it has not a significant impact unless you got... let's say one hundred of them in the same file which I really doubt. Indeed there is more work but it's not enough to put your performance down.
I think you'd better optimize wp queries | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
Add site options UI in Multisite Sites > Infos page
I want to add meta fields for the sites in my network (such as a thumbnail and a category). I know how to do this using `get`/`add`/`update_site_option`, but I'm wondering where I could put the UI to manage those meta fields.
The best place would be in the Sites > Infos page, just after the site attributes, but I can't find any hook to hang on. I can add those fields in the "Settings" tab of the same screen, but one has to scroll down a lot to find it, and it gets mixed with advanced settings.
Any suggestion ? | I finally found a way to add more lines to the Sites > Infos table : !My own option in the Sites > Infos table
It's a little bit ugly, but it works. I simply use the action `admin_footer` to add a bunch of HTML code at the end of the page, and then use jQuery to move it to the right place.
add_action('admin_footer', 'user16975_custom_options');
function user16975_custom_options(){
global $pagenow;
if( 'site-info.php' == $pagenow ) {
?><table><tr id="user16975_custom_options">
<th scope="row">My own option</th>
<td><input type="text"/></td>
</tr></table>
<script>jQuery(function($){
$('.form-table tbody').append($('#user16975_custom_options'));
});</script><?php
}
}
The good part is that as soon as the hook will be available, I can use it without big changes in my code. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "multisite, hooks, options, user interface"
} |
How to add_filter/action to comment out CSS generated by admin function?
So in wp-includes/admin-bar.php there is a function that adds CSS styling to the page:
function _admin_bar_bump_cb() { ?>
<style type="text/css" media="screen">
html { margin-top: 28px !important; }
* html body { margin-top: 28px !important; }
</style>
<?php
}
I want to comment this out properly (either the function or the contents of the function, either one is fine) but not touch the core code. How would I do this? | I think you can do it like this:
function my_admin_bar_init() {
remove_action('wp_head', '_admin_bar_bump_cb');
}
add_action('admin_bar_init', 'my_admin_bar_init');
Add this to your functions.php file. It will disable outputting of these inline styles in `<head>` section but the wp_admin_bar will be still available.
If you would like to disable wp_admin_bar entirely, you can do it like this:
remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "admin, filters"
} |
Permalink Settings
I have a `.htaccess` problem what buggs me out for couple of hours already. I have updated the file as it should be:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /zootaxi.lv/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /zootaxi.lv/index.php [L]
</IfModule>
# END WordPress
and Im working on localhost.
I've tried both paths:
C:\wamp\www\zootaxi.lv
and
C:\wamp\www\zootaxi.lv\wp-content\themes\zootaxi
Advice much appreciated,
Thanks | `mod_rewrite`is probably not activated on your localhost that why permalink can't work. Just uncomment this line in apache :
#LoadModule rewrite_module modules/mod_rewrite.so | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks"
} |
!is_admin() condition turns true in admin pages
I need users to redirect to login if not logged and once they are, redirect them to backend if they try to see front end pages. This is my code:
add_action( 'template_redirect', function () {
if(is_user_logged_in() ):
bk1_debug('logged in');
if (!is_admin()):
bk1_debug('not in admin, redirecting...');
wp_redirect(admin_url());
endif;
else:
bk1_debug('not logged in, redirecting...');
wp_redirect(wp_login_url( admin_url() ));
endif;
}, 10 );
Of course it doesn't work... For some reason 'not in admin, redirecting...' is called also in backend, and even better, in front end nothing happens altogether! Only redirecting for not logged in user goes.
Any idea? | Following suggestions from @s_ha_dum who noted that user need be logged in anyway to go to back end and that 'template_redirect' doesn't work in backend (even if my code did trigged console messages only in back end), I simplify the code as such:
add_action( 'template_redirect', function () {
if(!is_admin()) wp_redirect(admin_url());
}, 10 );
But nothing changed. Still I go to front end and nothing happens. I also tried with 'init' and nothing.
Then I thought that maybe I was calling 'template_redirect' in the wrong moment, so I mixed the two hooks:
add_action( 'init', function () {
add_action( 'template_redirect', function(){
if(!is_admin()) wp_redirect(admin_url());
}, 10);
}, 10 );
And that finally worked!!! | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "redirect, hooks, template redirect"
} |
Pagination posts. Url format
i'm using pagination for very long posts. So i have a problem here. I'm not happy with standard utl structure (where is couple personal reasons for that in my project). For example, i have post
/post.htm
and i need to get second page of it with
/post2.htm
not
/post.htm/2
I'm sure that i won't create post/page with slug post2 How can i change standard url in a such way? I tried this
add_action( 'init', 'wpa5413_init' );
function wpa5413_init()
{
add_rewrite_rule('^([^/]+)([0-9]{1,2}).htm$','$matches[1].htm/$matches[2]','top');
}
But it doesn't work... | Your rewrite rule format is not correct. The `$rewrite` argument must point to `index.php` with query vars set so WordPress can create the default query:
add_action( 'init', 'wpa103850_init' );
function wpa103850_init()
{
add_rewrite_rule(
'^([^/]+)([0-9]{1,2}).htm$',
'index.php?name=$matches[1]&page=$matches[2]',
'top'
);
}
However, this will still not work correctly, due to the canonical redirect. WordPress wants to enforce a single URL for any given post/page. You'll have to remove that filter to prevent that from happening, but note that this will have other possibly undesirable side-effects, as no canonical redirects will happen.
remove_filter( 'template_redirect', 'redirect_canonical' );
It may be possible to selectively apply the canonical redirect, but I haven't the time to go digging in source at the moment to determine that! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, pagination, slug"
} |
Variables posting twice
I wish to create a new variable as described in the codex, but on submission of the URL the variables are submitted twice to my function
I have tried this within a plugin also a the `function.php`. I have also tried to use `wp_reset_query()`
Here is my sample code:
add_filter('query_vars', 'my_function');
function my_function ($vars) {
$vars[] = 'Q1';
$vars[] = 'Q2';
return $vars;
}
add_action('parse_query', 'query_var');
function query_var () {
if (get_query_var('Q1')){
echo ('hello');
}
} | The `parse_query` action gets called on _every query_ (menu items, sidebar recent posts widgets, etc.), but `get_query_var` pulls from the _main query_ , so that condition will be true for all queries despite the fact that the query var doesn't exist in those queries. You need to check the query object passed to your function hooked to `parse_query`:
add_action('parse_query', 'query_var');
function query_var( $query ) {
if ( isset( $query->query_vars['Q1'] ) ){
echo ('hello');
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "variables"
} |
Only Display a Featured Image on First Post Page
In WordPress a single post can be divided into multiple pages using page-links.
Currently, I use featured images on my post pages and call them by size, as shown below. If an image is larger than 500 pixels it is displayed as the top-post thumbnail and if it is smaller than that it displays as the standard thumbnail.
<?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
if ( $image_data[1] >= 500 ) { the_post_thumbnail('top-post');
} ?>
<?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
if ( $image_data[1] < 500 ) { the_post_thumbnail();
} ?>
The problem is when I include this in my single-post.php it shows up on every page of a post, even when that post is divided by page-links. How do I make these images only show on the first page? | Use the global `$page`, which holds the current page number.
// Somewhere near the top
if ( $GLOBALS['page'] === 1 && $image_data = get_post_thumbnail_id() ) {
if ( $image_data = wp_get_attachment_image_src( $image_data, 'full' ) ) {
if ( $image_data[1] >= 500 )
the_post_thumbnail( 'top-post' );
}
}
// Further down. $image_data still exists, no need to grab it again.
if ( $GLOBALS['page'] === 1 && $image_data && $image_data[1] < 500 )
the_post_thumbnail();
You'll see I also a did a little spring cleaning:
1. Removed redundant second `$image_data = ...`
2. Added check that there is indeed a thumbnail
3. Added check that `$image_data` exists | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pages, post thumbnails"
} |
Minimal WordPress load for only `get_option` to work (because ajax...)
In a plugin, I use ajax to `get_option()` which takes much longer than it has to because entire wp gets loaded.
How do I set things up so that it (my ajax) loads only what is needed? (`get_option()`)
[](
[]( | If you're building something for public consumption (a plugin, a theme, etc) use `admin-ajax.php` like you should because that is the appropriate and accepted way to do things and gives your end users the power they need to change and modify things if they so choose.
Beyond that, the best you MAY be able to do is use the `SHORTINIT` constant. Define it in a custom php file, then require `wp-load.php` and do what you need to do. `SHORTINIT` stops most of the WordPress core from being loaded.
<?php
define('SHORTINIT', true);
require '/path/to/wp-load.php';
// you'll have the basic API here, including `get_option`. Do stuff.
If you do this outside the WP core, you'll have to _guess_ where `wp-load.php` may be -- you won't have any `ABSPATH` contant to guide you. That's a risky bet unless you're in full control of the system. In other words, if this is a custom, not publicly-released thing, go for it. Otherwise, use `admin-ajax.php`. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "ajax, performance, optimization, options"
} |
Removing the main link to Jetpack from the menu
I need to remove the link to the Jetpack settings, but not the links to Omnisearch and Site Stats from the admin menu for everyone not having an administrator role:
!enter image description here
For this, I came up with this code:
function remove_posts_menu() {
if (!current_user_can('administrator')) {
remove_submenu_page('admin.php?page=jetpack', 'admin.php?page=jetpack');
}
}
add_action('admin_init', 'remove_posts_menu');
(Reference for the `remove_submenu_page()` function)
However, this doesn't work. I did check that the function is called and so by adding `remove_submenu_page('tools.php', 'tools.php');` \- when this is added to the function, just after the removal of the Jetpack settings link, the Tools link is removed, but the Broken Link Checker link (of a plugin I installed) is still visible.
What's the correct way to remove the Jetpack link? | Try this instead:
function remove_posts_menu() {
if ( ! current_user_can( 'manage_options' ) )
remove_submenu_page( 'jetpack', 'jetpack' );
}
add_action( 'admin_init', 'remove_posts_menu' );
where the _menu slug_ and _submenu slug_ are `jetpack`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, wp admin, plugin jetpack"
} |
What could cause a WP Option to get truncated?
I have a WP plugin, where all admin setting field values were suddenly changed to the letter 'a'. All settings are stored in one 'big' option in the table. Seemed like the serialization gone wrong.
I run a `var_dump` on the `get_option` value and it returned a truncated string, not an array as usual. I'll update the question once I can reproduce the truncated string again.
I only use the 'Save changes' button and let the WP Options API write to the option, getting the values from user changeable or hidden HTML fields.
Is there any special characters or similar that can prevent an option from being written properly which could result in the serialized array being truncated?
The cause has something to to with Instagram or an Instagram user name. | It was a character. Make sure you sanitize everything that gets written as field values, even if it's a username.
trim(preg_replace("/[^\w\s]+/", "", $user->full_name))
I assumed there are no special characters in Instagram usernames. Never assume. I don't really use Instagram, just my plugin supports it. BTW it got truncated on the first occurrence of the special character. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, mysql, options, plugin options"
} |
Hook in a sidebar widget and add some markup
I'm looking to hook into a sidebar widget, this one in particular loads the members.
All I'm looking to do is add a link into the widget, I managed to get a result but it's not quite right. It doesn't load the original function, instead it replaces it.
Here's how I far I got:
function members_dir_link(){
echo '<a href="/members/">View Members</a>';
}
add_filter('bp_has_members','members_dir_link'); | I don't think it can be done. I'm sorry, but this widget has no hooks in there. You can only use `bp_has_members` hook, but you shouldn't use it to echo anything, because it's used in many other places, so you may break some things doing it this way.
The only way I can see to achieve this (and it's not perfect), is to write your own widget based on this BP widget. To do that you should:
1. Find the original widget's source code. (It's in `bp-core/bp-core-widgets.php` file)
2. Copy it's code and place it in your themes `function.php`
3. Rename it properly (take care of class name, and so on).
4. Register your new widget with:
add_action('widgets_init', create_function('', 'return register_widget("");') );
You can also try to inherit this new widget class from original BP widget class (you won't need to copy entire source code then). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, hooks, sidebar"
} |
Automatically adding a link to the next page link before '<!--nextpage-->' tag in posts?
I'm using the following snippet to automatically break a too long post into multiple pages
function filter_more_with_nextpage( $content ){
$content = str_replace( '<!--more-->', '<!--nextpage-->', $content );
$content = preg_replace( '/<!--nextpage-->/i', '<!--more-->', $content, 1 );
return $content;
}
add_filter( 'content_save_pre', 'filter_more_with_nextpage' );
works like a charm, but I'd like to add automatically a link `<a>` element before the page break to help directing users to the following page.
I don't wish to put the link in the post content manually (from wp backend) nor have it inserted automatically in the post content (I don't want it saved along the post itself). Rather, I'd wish to have it generated just before `<!--nextpage-->` tag breaks the current page. | If you use `<!--nextpage-->` tag, then you could use `wp_link_pages` function. Just put it in your `single.php` template. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pagination, the content, read more, paginate links, nextpage"
} |
Wrapping the_content() in Schema articleBody tag?
I am trying to put `the_content()` inside `<meta itemprop="articleBody" content="`(content here)`">`.
But if I just put `<?php the_content() ?>` in there, it doesn't work, image goes, structure gets mis-aligned, and `">` appears after the content.
Any ideas?
Edit: I don't know why this was put on hold for not fitting in the Wordpress scope.. the_content() is a Wordpress function, I was clearly having trouble with structuring/SEO for my Wordpress site. | Fixed it by moving `itemprop="articleBody"` to the `<div>` containing the body. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "php, seo"
} |
Changing WP_CONTENT_DIR and WP_CONTENT_URL in wp-config.php does not register?
I tried to add this to the end of my wp-config.php
define('WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/somedir');
define('WP_CONTENT_URL', '
however, echo immediately after that shows the old values (with wp-content value). I tried echo because in wp admin I couldn't see the theme from new location, of course.
I have installed wp in example.com/wp subdirectory and site itself is example.com - I copied over .htaccess and index.php over to the root and everything is working fine, I just need to move wp-content into another folder over at root also with a different name. | You have probably added the definitions too late. If in fact you added that "to the end" of `wp-config.php` then you added it after these lines:
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
If so, then those constants are already defined (`wp_initial_constants`) and you cannot redefine a constant after it is already defined.
Make your edits earlier, before:
/* That's all, stop editing! Happy blogging. */ | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 4,
"tags": "wp config"
} |
bbpress Not Showing: How to troubleshoot?
BBPress isn't showing on the front-end in a custom theme I've built and I can't figure it out. I activated TwentyTwelve and it shows, so I know it's not a plugin. I also cleared out functions.php and that didn't have any impact. How do I begin troubleshooting from here? | The "most" stripped-down theme I can think of that can run **BBPress** is just a single `index.php` file containing:
<?php
// get_header();
if ( have_posts() ) :
while ( have_posts() ) : the_post();
the_content();
endwhile;
else :
_e( 'Nothing!' );
endif;
// get_footer();
?>
So my guess is that your `while` loop is missing something or you are overwriting the `the_content` filter used by BBPress!
Well, taking the extreme, it looks like it's possible to run it with the following one-liner in `index.php`:
<?php the_post(); the_content(); ?>
but that's just for fun ;-) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "bbpress"
} |
How to Explode a Textarea Field and Echo each line separately, wrapped with HTML
Need to take an advanced custom field textarea and display it in my template by breaking out each line separately. I want to wrap each line of the textarea with HTML, like an `<li>`.
I've tried the following, but it's just not working:
if (isset($instruction_textarea)){
$arry=explode( "\r\n", $instruction_textarea );
}
for ($i = 0; $i <= count($arry); $i++){
echo (trim($arry[$i])+"<br/>");
} | I would try something like this:
$lines = explode("\n", $instruction_textarea); // or use PHP PHP_EOL constant
if ( !empty($lines) ) {
echo '<ul>';
foreach ( $lines as $line ) {
echo '<li>'. trim( $line ) .'</li>';
}
echo '</ul>';
}
It should work. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "php, custom field, advanced custom fields"
} |
Storing Form data in a different database
I have two wordpress websites and I want to store the data submitted by the forms in a centralized database in order to better manage the information.
Is there a way I can store form data in a different database? | You can use `$wpdb` to access any database you have access to (credentials for) so one site or the other could access its partner's database or both could access a third database. It shouldn't be hard but you will need to write most of the `SQL` to do it.
If you are in a position to refactor this, you could consider having both sites share the same database, via distinct database prefixes, and then save to custom table instead of bothering with access to multiple databases.
Your question is not really specific enough to allow for a more detailed answer. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, multisite, database, forms, multisite user management"
} |
Loop that displays all posts by logged in user, with Post Edit link
I need a loop that pulls in all posts that were authored by the logged-in user.
I have to then create a link to the post with this in the querystring: ?_ninja_forms_action=edit. | $posts = get_posts(
array(
'post_author' => get_current_user_id(),
'post_status' => 'any',
'post_type' => 'any',
)
);
foreach ( $posts as $post )
printf( '<a href="%s">%s</a><br />',
esc_attr(
add_query_arg( '_ninja_forms_action', 'edit', get_permalink( $post ) )
),
get_the_title( $post )
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "loop"
} |
Orderby custom field for custome post type
I am trying to order a custom post type called "Teachers" by a field called sort_by. I am not sure why this isn't working.
Here is my code:
$args = array( 'post_type' => 'teacher', 'posts_per_page' => 30, 'order_by' => 'sort_by' ,'order'=>'ASC' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="entry-content"><h2 class="teachers">';
the_title();
echo '</h2>';
the_excerpt();
echo '</div>';
endwhile; | The argument is `orderby` not `order_by` but I am not sure what `sort_by` is. If that is a custom meta field you need to alter the query.
> 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect). Use 'meta_value_num' instead for numeric values.
>
> <
You need to pass one argument for the meta_key and another for the `orderby`.
$args = array(
'post_type' => 'teacher',
'posts_per_page' => 30,
'meta_key' => 'sort_by',
'orderby' => 'meta_value',
'order'=>'ASC'
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom field"
} |
why the same code got different results when using query_posts in functions.php and index.php
I am using WordPress 3.5, and my blog sites have many registered users. After they log in, I want them to see just their own posts, not others.
So I added this to my `functions.php`, but I get a blank page.
function only_login_user_post_on_homepage() {
$current_user = wp_get_current_user();
query_posts('author=', $current_user -> ID);
}
add_action( 'pre_get_posts', 'only_login_user_post_on_homepage' );
So, I comment out the `add_action`, then go to `index.php`, add the same code:
$current_user = wp_get_current_user();
query_posts("author=".$current_user -> ID);
Yeah, got the results, I don't know why? The code are the same, but why I got different result. | In your first code example, you hook into the `pre_get_posts` action, which fires during the main query. But instead of manipulating _that_ query, you trigger another one using `query_posts()`, which fires the hook again, and you end up with an infinite loop.
With the second code example, you're just overriding the main query after it's occurred. But whilst it works, you've ended up with a redundant, time-consuming query.
You're almost there, and props for your efforts, so let's bring it together:
function wpse_103997_only_posts_by_current_user( $wp_query ) {
if ( is_user_logged_in() && $wp_query->is_main_query() && $wp_query->is_home() )
$wp_query->set( 'author', get_current_user_id() );
}
add_action( 'pre_get_posts', 'wpse_103997_only_posts_by_current_user' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, wp query, query posts, hooks"
} |
How to rename theme's root directory?
I want to rename the theme's root folder for security purpose.
I put these in `wp-config.php` file:
But I want to rename the theme's root directory also:
define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/assets' );
define( 'WP_CONTENT_URL', '
define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/extension' );
define( 'WP_PLUGIN_URL', '
So, how to rename the theme's root folder like this way? | Although @TheDeadMedic is technically correct and you can't rename the `themes` folder. You CAN change some of the public facing urls.
For example, you can make a new folder `assets/new-themes` and add your CSS, and images there. Then make a theme include your styles.css (which can be just the header info) and anytime in your theme you want to refer to any image, css, or JS (public urls) set that to your new theme folder (or CDN if your fancy)
I'm not sure how changing the name of the directory would improve security as there are so many ways to find out if someone is using WP but that's just one way to apply a similar effect.
**UPDATE:** Looks like you can use the hook `register_theme_directory()` to add an additional theme dir. (see link to duplicate question above) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme roots"
} |
Clear Transients
I have build a custom theme for a client of mine, and I am using transients in order to make the site operating faster.
After a week, I have see in the wp_options a huge list of transients records (in about 360000 records). This makes me beleave that transients are not removed from the database.
How can I remove that records and how ? Is there any good tutorial ?
Kind regards | > Unfortunately, expired entries will only be deleted if you attempt to access the transient again. If you don't access the transient then, even though it's expired, WordPress will not remove it. This is a known "issue" and is due to be corrected at some point in the WordPress core code.
_-Copied from: Artiss Transient Cleaner_
Found this plugin, can help you:
> Artiss Transient Cleaner
Additionally, can modify the time of the deletion using the process mentioned **HERE** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "transient"
} |
On Category page, How can I get the category ID?
This might be very basic question, but I can't really get the category ID on category page (actually a category page of custom type post).
Filename is `taxonomy-item-category.php` & URL is `
I have tried some of the following but not working...
$cur_cat_id = get_cat_id( single_cat_title( "food", false ) );
$cur_cat_id = get_cat_id( single_cat_title( "", false ) );
get_the_category( "food" );
How can I get the category ID on category page? | `$cat_id = get_queried_object_id();` \- it's that simple! | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 2,
"tags": "categories, id"
} |
How to fetch all videos in custom page which uploaded in wp-admin (Media) in wordpress
I want to fetch all videos which are uploaded in back end wp-admin media.
How to show all videos or audios which I uploaded on a custom page? | Uploaded images, video's etc. are stored as posts with the type "attachment"; use `get_posts( )` with the right parameters.
Try this; the code loops trough all attachments and displays them:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
'post_mime_type' => 'YOUR-POST-MIME-TYPE'
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $post ) {
setup_postdata( $post );
the_title( );
the_attachment_link( $post->ID, false );
the_excerpt( );
}
}
Where `YOUR-POST-MIMET-YPE` is the mime-type you're looking for.
> A full or partial mime-type, e.g. image, video, video/mp4, which is matched against a post's post_mime_type field
So in your case you should try `video`.
You also could use `array( 'video', 'another-mime-type' )` for multiple mime-types. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "videos, audio"
} |
Image resize using url parmater
I would like to resize image in my wordpress template using url parameter. Best example for this would be Wordpress's very own twenty Twelve theme.
Following is link to image with width parameter in the end. If you change width to 50 it'll return image with 50px width.
> <
I'm confused if its server setting or we can do it using php.
Thanks. | WordPress(.org) doesn't have anything like this built into the core. A lot of theme developers use Timthumb to achieve that. The example you've linked to is on a wordpress.com server so there will be something custom going on for that functionality.
You could also look at the WordPress functions add_image_size & the_post_thumbnail. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images"
} |
remove () from category number
I have found this code here.
$args = array(
'hide_empty' => FALSE,
'title_li'=> __( '' ),
'show_count'=> 1,
'echo' => 0
);
$links = wp_list_categories($args);
$links = str_replace('</a> (', '</a> <span>(', $links);
$links = str_replace(')', ')</span>', $links);
echo $links;
This returns something like this `(5)`.
I want to remove `()` and show only 6. | This should make you good to go:
$args = array(
'hide_empty' => FALSE,
'title_li'=> __( '' ),
'show_count'=> 1,
'echo' => 0
);
$links = wp_list_categories($args);
$links = str_replace('</a> (', '</a> <span>', $links);
$links = str_replace(')', '</span>', $links);
echo $links;
The `(` and `)` were in the code.
And if you only want to show 6 categories replace the `$args` part with:
$args = array(
'hide_empty' => FALSE,
'title_li'=> __( '' ),
'show_count'=> 1,
'echo' => 0,
'number' => 6
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugin development"
} |
Insert After Second Paragraph Without <P> Tag?
I use a code like the one shown below to insert ads after the first paragraph.
The problem is that this code requires the content to be displayed within paragraph tags and I would like to use this code to insert a DIV.
When I simply replace the tags with div tags the code no longer works.
How do I remove the paragraph tags from the code while allowing the code to remain functional?
<?php
$paragraphAfter= 1; //display after the first paragraph
$content = apply_filters('the_content', get_the_content());
$content = explode("<p>", $content);
for ($i = 0; $i <count($content); $i++ ) {
if ($i == $paragraphAfter) { ?>
CONTENT GOES HERE
<?php }
echo $content[$i] . "</p>";
} ?> | I need to stress that I think this is going to be very unstable and you may not always get the results you want, but in simple cases this should work.
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content, 2);
// var_dump($content); // debug
echo $content[0].'</p>';
echo '<div>Extra Content</div>';
if (!empty($content[1])) {
echo $content[1];
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, functions, single"
} |
Why does deactivating a plugin cause error: "You do not have sufficient permissions to access this page"?
We recently deactivated the bbPress plugin because we don't use it anymore. Immediately following that, no admin users can get into the dashboard without hitting the infamous:
`"You do not have sufficient permissions to access this page?"`
We tried removing ALL plugins to rule out a dependance from one of those, but it didn't work. | For the specific case of bbPress, it adds new user roles and capabilities, like the "Keymaster" role. Those users who had a role that was bbPress specific won't have access to anything anymore, because after you removed the plugin, the role no longer exists.
Some users have reported that using the "User Role Editor" plugin and resetting their roles to default have fixed this issue: <
If you have any admin that can login, he can manually reset the roles of affected users by editing their user profile and giving them the proper role on the site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugins, permissions, bbpress, deactivated plugin"
} |
Is there a way to share your Facebook Page's stream on a WordPress page or post?
Everybody knows how to share a WP post to Facebook.
**Is the reverse possible**? Is there a way to share things you post on a Facebook page to a particular WordPress page or post?
If so, I'd really love to hear about a solution; I've googled to no avail. Thanks! | The solution is simple, you need your FB page RSS feed. To have it you can modify this simple URL:
As you can see the number after 'id=' and before '&format' is the page ID. If you don't know how to find your page ID use this simple online service: <
Then with any Wp feed poster plugin you'll be able to have your FB stream on your blog. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, facebook"
} |
How to add videos on my home page slider?
How would you recommend adding videos to my website's home page slideshow, here is the php code that creates the slideshow:
<?php global $gpp; ?>
<div class="app">
<div id="slideshow">
<?php
$slides = array('gpp_slideshow_image_1','gpp_slideshow_image_2','gpp_slideshow_image_3');
$i=0;
foreach ($slides as $slide) {
if($gpp[$slide]<>"") {
echo '<div class="slide"><img alt="'.get_bloginfo('name').'" src="'.$gpp[$slide].'" /></div>',"\n";
}
}
?>
</div>
</div> | From the GPP Slideshow description:
> The GPP Slideshow plugin for WordPress allows you to create **minimalist _image_ slideshows**...
This plugin is built to only handle image slideshows, so I seriously doubt it could easily handle non-image content such as videos. You're much better off moving on to a slideshow that is built to handle multiple types of media. (Sidenote: And if that's the slideshow code then it's rather inaccessible anyway and you're better off moving on for that reason alone.)
As a rule I don't like slideshows so I don't use them much, but some plugins that might be better-suited to your task are AnythingSlider (might be abandoned, though, so proceed at your own risk) or one that uses FlexSlider 2. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, slideshow"
} |
get_footer can't find any variables set in functions.php
footer.php can't find any variables I set in functions.php, I've tried a global (urggh) and object array like so:
$foo = (object)array("bar" => "test text");
It works within page template, just not in the header or footer, does anyone know why this is happening?
Thanks for reading. | This is a variable scope problem.
Your variable in `functions.php` is not in scope where you are trying to use it in your footer.
To make this work declare the variable global in `functions.php`
global $tst;
$tst = 'd00d';
And then pull it in with the `global` keyword when you need to use it.
global $tst;
echo $tst;
Or, even better, **_rethink things so that you don't need the global at all_** \-- maybe build a class or a function with a static variable. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "functions, array"
} |
the_excerpt Read More Filter
Currently, I call the_excerpt via traditional means:
<?php the_excerpt(); ?>
But I add a filter in functions.php for a custom "read more" message.
// Changing excerpt more
function new_excerpt_more($post) {
return ' <a class="read_more" href="'. get_permalink($post->ID) . '">' . 'read more' . '</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
Here's the problem; I would like to call the_excerpt inside posts as well without any read more type of link being displayed while leaving the_exerpt being used in the actual excerpts unimpacted. | Just add the filter where you need it.
Define the filter callback in `functions.php` but don't add the filter...
// Changing excerpt more
function new_excerpt_more($post) {
return ' <a class="read_more" href="'. get_permalink($post->ID) . '">' . 'read more' . '</a>';
}
In your template file just before you need the custom more link:
add_filter('excerpt_more', 'new_excerpt_more');
And remove it afterwards
remove_filter('excerpt_more', 'new_excerpt_more');
Or make it self-removing...
function new_excerpt_more($post) {
remove_filter('excerpt_more', 'new_excerpt_more');
return ' <a class="read_more" href="'. get_permalink($post->ID) . '">' . 'read more' . '</a>';
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "excerpt"
} |
Using a nonce in a Custom Login Form
I am trying to create my own login form for WordPress using wp-login.php as a template.
In the form that is used to collect login information from the user (lines 680 through 703 of wp-login.php), there doesn't seem to be any implementation of a nonce.
I have been told by quite a few people that I should always be using a nonce when collecting information from forms - but there is not a single reference to a nonce in this entire file - despite their being four fairly critical forms.
So - what am I missing?
I know that the login form uses a testcookie and that you create a securecookie when reading through the POST information - but does that somehow solve the security issue? Are there any good resources out there for understanding how secure cookies work in this instance? | > using wp-login.php as a template.
is not a correct way to do that.
Source
You'd better use the wp_login_form() function in a custom template.
EDIT:
And if you want to add an option to reset password you could do this :
add_action( 'login_form_middle', 'add_lost_password_link' );
function add_lost_password_link() {
return '<a href="/wp-login.php?action=lostpassword">Lost Password?</a>';
}
Source | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "php, login, cookies"
} |
add different stylesheet file to edit themes file list
I am not sure if the title makes sense so feel free to suggest a different one. Anyways…
In Wordpress dashboard _Appearance -> Editor_ page I would like to load _app.css_ file located in current theme's _assets/css/_ directory.
How can I achieve this? | See this answer.
> The theme editor has support for files in a subdirectory \- but only if this is the main theme and only for PHP files. This seems to be an omission, I opened a ticket for it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "dashboard"
} |
Get categories related to particular category
I have assigned two different main categories to blog and portfolio.
the blog will show only categories related to main blog category and portfolio will also do the same.
with this code for portfolio
$cat_ids = get_all_category_ids();
foreach($cat_ids as $cat_id) {
$cat_name = get_cat_name($cat_id);
$cat_slug = strtolower($cat_name);
$cat_slug = str_replace(' ', '-', $cat_slug);
if(get_category($cat_id) ) {
echo '<li class="'.$cat_slug.'"><a href="#" rel="'.$cat_slug.'">'.$cat_name.'</a></li>';
}
} // foreach
i am getting all categories also blog.
i just want to show the categories related to 'portfolio' category on portfolio page. | You can use `get_categories()` to get all the sub-category of parent category.
$args = array('hide_empty'=> 0,
'child_of'=>'id_of_blog_category/id_of_portfolio_category');
$categories = get_categories($args);
foreach ($categories as $key => $value) {
echo '<li class="'.$value->slug.'"><a href="#" rel="'.$value->slug.'">'.$value->name.'</a></li>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
Get posts in a subcategory of a chosen parent
Taking on legacy data I have the following structure
-Top level category (category)
\-- Sub category (report)
\--- Post
I want to get all posts in a particular top level category.
**The problem is all the posts are only assigned to Sub Categories, not their top level categories.**
I've tried the following:
function getPostsInCategory($category) {
return get_pages(array(
'post_status' => 'publish',
'post_type' => 'post',
'child_of' => $category, // e.g '3'
'numberposts' => -1
));
}
I use `get_pages` instead of `get_posts` because it seems to support heirachy better.
How can I get all posts that are in a "report" that is a child of my chosen category? | You should use `get_posts` or (even better) custom `WP_Query` to query posts.
You can use `get_pages` to do this, but `get_pages` can't use `category` (or other taxonomies - just check it in WP sources) to filter results.
So your function should look like this:
function getPostsInCategory($category) {
return get_posts(array(
'post_status' => 'publish',
'category' => $category, // e.g '3' catgory is passed as 'cat' param of WP_Query, so it will display posts from children categories as well
'posts_per_page' => -1
));
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, taxonomy"
} |
Changing RSS feed URL structure
I am in the process of creating a wordpress website, and I just have one issue left - RSS feeds.
Currently, the website has a `.htaccess` file blocking access to `/category/*` pages. It was part of a requirement that the site is not obviously Wordpress, and `/category` is a decent indicator of that.
Each category is fronted by a page, which displays the category content - so `/category/news` becomes `/news`.
However, RSS feeds always seem to point to `/category/xxx/feed` \- is there a way to remove this `/category/` part? So people could view the RSS feed at ` ?
I've tried fiddling around with the `.htaccess` file, but it's the one area of building a web application I'm not 100% sure on. Every search has returned with results of how to point a feed to Feedburner instead, which is not what I am looking to do at all. | I found (in my opinion) the best and easiest way to do this, and thought I should leave it as an answer in case anybody stumbles upon this thread.
I downloaded and installed the WP No Category Base plugin and that did exactly what I needed.
Unfortunately, I never got around to trying the other answers (had to move on to a more urgent project), so I can't clarify if any of them work.
* * *
**Updated Link** : No Category Base (WPML) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, urls, htaccess, rss, feed"
} |
Infinite Scroll plugin on Ebuy theme
So Ebuy does not support infinite scroll, and my coding knowledge is minimal. I'm looking for some guidance as to how i can manually get in there and make infinite scroll work. Ive already got the plug in activated, but i am unsure as to what to put in the content selector, nav selector, next selector, item selector, and call back fields.
<
thats what it looks like now. it shows 10 items, then you have to click on "older entries". if anyone could help me set this up, id appreciate it! thanks | The page that you have mentioned above has the following markup
<div id="content">
<div class="box " id="post-302"></div>
<div class="box " id="post-298"></div>
<div class="box lastbox" id="post-296"></div>
<div class="box " id="post-293"></div>
<div class="box " id="post-265"></div>
<div class="box lastbox" id="post-259">
<div id="navigation">
<div class="alignleft"><a href=" Older Entries</a></div>
<div class="alignright"></div>
<div class="clear"></div>
</div>
</div>
Try these:
content selector -- #content
nav selector -- .alignleft
next selector -- .alignleft a
item selector -- .box | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Query from multiple category (and)
here is the request : get all post from category=11 (get 21 post), and then in the 21 post got from this category, refilter it, and show only post from category=10. So the request should be : cat=11&10\. i what post that are from BOTH category at the same time, because my category are job and active. i what the listing of all the job, and then show just the one that are ative in the system !
$$mycat = "11&10"
$showPostsInCategory->query('cat='. $mycat.'&posts_per_page=-1'); | Have you looked up the WP Codex on WP_Query for categories?
They provide an example here. Also your category variable should probably only have one `$`. The way you've written your custom query also looks wrong, are you using WP_Query?
`$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, query"
} |
register_theme_directory and broken deploys
I use `register_theme_directory()` in a mu-plugin to register a custom theme directory (located at `project_root/app/views/`, with site_root at `project_root/public/` and WordPress in a Git submodule at `project_root/public/wp/`. `WP_CONTENT_DIR` is at `project_root/public/content`).
I also use Capistrano to deploy my project.
Every time I deploy, the site breaks, and I get this message in my Dashboard:
> ERROR: The themes directory is either empty or doesn’t exist. Please check your installation.
When I navigate into the Appearance tab, my theme doesn't appear on the list until I refresh the page. After refreshing, I can see my theme, activate it, and everything works again.
Why might this be happening on every deploy? I am confused as to why WordPress would think the theme doesn't exist, when it definitely does. | There is a bug in `class-wp-upgrader.php`: WordPress is using the fixed path `WP_CONTENT_DIR . '/themes'` and doesn’t use `get_theme_root()`.
I have written a patch 7 months ago … which was _too late_ for WordPress 3.6 – the fix was delayed just today.
So use my patch, or jump in on Trac and explain why this is important. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "themes"
} |
Is it possible to add an action to the currently running action?
My question is very simple but I haven't found this answer yet. Here's an example:
class MyClass {
public function __construct(){
add_action('init', array($this, 'init'));
add_action('wp_footer', array($this, 'footer'));
}
public function init(){
add_action('init', array($this, 'register_scripts'));
}
public function register_scripts(){
wp_register_script('my-script', plugins_url('/script.js', __FILE__));
}
public function footer(){
echo('<div class="style-me">Rawr this is my plugin.</div>');
}
}
This is how my code looks and it's failing. It displays the div but the javascript does not get applied. So I wondered if my problem was running the `init()` function in the init action and then adding `register_scripts()` to the init action but I'm already in that action. Is this possible? | You have to use a later (higher) priority. So use `current_filter()` to get the current hook and priority, add 1 to that priority, and register the next action:
add_action( 'init', 'func_1' );
function func_1()
{
global $wp_filter;
$hook = current_filter();
add_action( $hook, 'func_2', key( $wp_filter[ $hook ] ) + 1 );
}
function func_2()
{
echo 'hi!';
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugins, plugin development, hooks, actions, wp register script"
} |
How can I get this code to only output one link?
This is the code I'm using to output the child categories of my posts as links.
<?php
$mycats = array(106, 107);
foreach (get_the_category() as $childcat) {
foreach ($mycats as $mycat) {
if (cat_is_ancestor_of($mycat, $childcat)) {
echo '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>';
}
}
}
?>
My questions is, how can I get it to only output _one_ link, when the post is in more than one child category? I tried adding a break command after the last line, but that didn't work. Help appreciated. | You need to `break` both `foreach` loops not just one, so add `break 2;` after the `echo`.
$mycats = array(106, 107);
foreach (get_the_category() as $childcat) {
foreach ($mycats as $mycat) {
if (cat_is_ancestor_of($mycat, $childcat)) {
echo '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>';
break 2;
}
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
Is there a 'rake routes' for wordpress?
Is there an equivalent to 'rake routes' in php/wordpress that would spit out all the available wordpress url paths available? | var_dump( $GLOBALS['wp_rewrite'] );
this is as close as you'll get.
Anyway, there're plugins like the "MonkeyMan Rewrite Analyzer" and toschos T5 Rewrite plugins that will allow you other nice things too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "url rewriting, redirect, urls, routing"
} |
301 redirect for wordpress permarlink
on `.httaccess`, we use like this.
RedirectMatch 301 ^/food/(.*)$ http//:domain.com/food-for-healthy/$1
It works good. but we have a problem with 1 old link. we used to have a multi-site and the name is "food". it changed to "food-for-healthy"
Therefore we have changed like these.
RedirectMatch 301 ^/food/(.*)$ http//:domain.com/food-for-healthy/$1
and as you know,
http//:domain.com/food/
and
http//:domain.com/food
are same.
The problem is `http//:domain.com/food` which needs to go to `http//:domain.com/food-for-healty/`
I have tried several things but it gets redirect error.
RedirectMatch 301 /food http//:domain.com/food-for-healthy
this gets a redirect error. how can I change it to work properly? | You may try this...
RedirectMatch 301 ^/food$ http//:domain.com/food-for-healthy/
As per the syntax for RedirectMatch, the URL part can not be a regex. So, to achieve that you may use RewriteRule. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect"
} |
Site returns a 500 Internal server error
I have a serious problem with my WordPress theme. When I try to log in from Firefox, I will be logged in successfully but after that I try to log in with chrome or IE then I get 500 Internal server error. What am i doing wrong?
I tried error reporting E_ALL, debug to true but no success.
!enter image description here | _Repeating what I said in the comments so this question can have an accepted answer._
It is very likely this is a theme problem. Disable your active theme. If you can't log in to the wp-admin portion of the site you will need to do this either via FTP or in the Database. Often times it is a theme or htaccess that causes this sorta issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
Automatically post to Google+ on new post
Is there a way to automatically post to Google+ whenever there is a blog post on WordPress?
I found very conflicting information if that is possible or not. Ideally this should be free of course. | Google does not currently have a public API to allow posting to G+ from anywhere other than their web interface. The scripts that currently do so are using the "mobile" interface to do so, and as such are fragile at best. Additionally, they don't work with 2-step verification (which you should enable on your Google account for security reasons).
Therefore at this time, there is no safe way to automate posting to Google+. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "google"
} |
How do I modify the url of uploaded media content?
I have just moved hosts, and with the move I've also changed the setup that I have for media uploads.
I used to host my media on a subdomain called media.detailsofmylife.net, but now that I have switched over, I want to go back to the traditional detailsofmylife.net/wp-content/uploads/ style. I have already backed up and relocated the content so it should be ready to go.
For example, yesterday, an image used to located here:
<
but now it is located here:
<
Could someone please help me with the necessary SQL statement to correct all of the old url references to the new format? | Use a plugin like Deploy Helper. Essentially, it allows you to swap out all instances of one URL with another, and will also handle serialized data.
Just enter the old URL as `media.detailsofmylife.net/uploads` and the new one as `www.detailsofmylife.net/wp-content/uploads`.
Make sure you also reset your custom upload paths. If you'd defined constants like `WP_CONTENT_URL` or `UPLOADS` in your `wp-config.php`, remove them. Similarly, delete any possible settings in the database by loading `wp-admin/options.php` in your browser & emptying the values for `upload_path` & `upload_url_path`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "uploads, media"
} |
How does wordpress distinguish a plugin's main php file from other php files?
If my plugin has multiple php files in its plugin folder, how does WordPress know which is the main php file ? | WordPress has no convention for naming of main file. It scans whole plugins directory (see `get_plugins()` ) and looks for plugin header (with `get_plugin_data()`)in every PHP file on appropriate directory levels.
This is only performed when you actually need full list of plugins. Thing like active plugins are calculated and stored separately so that for it there is no need for search every load.
Note that this has curious side effect of technically allowing more than one main plugin file in plugin folder. All kinds of bad idea, don't go there. :) | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "plugins, plugin development"
} |
read more, even if excerpt not trimmed
I am using the excerpt field (Not the tag, because the excerpt also serves as a lead paragraph). I altered the "more"-link to be an arrow >.
function fabs_excerpt_more( $more ) {
return ' <a class="more" href="'. get_permalink( get_the_ID() ) . '">></a>';
}
add_filter( 'excerpt_more', 'fabs_excerpt_more' );
But it only appears, if the excerpt is trimmed down. I also tried this:
function fabs_excerpt_more($output) {
global $post;
return $output . '<a class="more" href="'. get_permalink($post->ID) . '">></a>';
}
add_filter( 'the_excerpt', 'fabs_excerpt_more' );
In that case the > appears for every excerpt, but after the closing p-tag. Is there a way to let it appear directly after the last word? | Try a simple string replacement. The following is untested:
function fabs_excerpt_more($output) {
global $post;
$output = str_replace('</p>', '<a class="more" href="'. get_permalink($post->ID) . '">></a></p>', $output);
return $output;
}
add_filter( 'excerpt_more', 'fabs_excerpt_more' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "hooks, excerpt, read more"
} |
WordPress Comment spam issue
I'm Trying to completely disable WordPress Comments. I have manually disabled comments via the WordPress back-end setting and I also created a new blank file called "no-comments-please.php" and then I added the below to my functions.php. Yet the comments show up in their numbers.
add_filter( 'comments_template', 'remove_comments_template_on_pages', 11 );
function remove_comments_template_on_pages( $file ) {
if ( is_page() )
$file = STYLESHEETPATH . '/no-comments-please.php';
return $file;
} | You might as well go the whole nine yards & use Disable Comments. In addition to a complete lock down, the plugin will remove any comment related sections in the admin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, comments"
} |
Need to execute a cron job
I need a cron job to execute the following url
>
The problem is that it requires to be logged in as admin, what are my options? I've tried a few plugins but they use hooks instead of just executing a url and the cron jobs provided by the control panel does not log in to the website. | Your option using WP internals would be to use the HTTP API along with `wp schedule event`
Create a scheduled event, something like:
register_activation_hook(__FILE__, 'my_schedule');
add_action('execute_my_url', 'do_this_daily');
function my_schedule() {
$timestamp = //some time you want it to run
wp_schedule_event($timestamp, 'daily', 'execute_my_url');
}
function do_this_daily() {
wp_remote_get( '../ =myvideoblog/mvb_main.php&action=processfeed&updatefeed=67', $args);
}
This is a simple example please refer to the codex for additional techniques and/or arguments.
* HTTP API
* wp schedule event
It's important to note WP cron only triggers when someone visits your WordPress site, fora true stateless cron you would need to use something at the server level or a better wrapper. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "login, cron, wp cron, authentication"
} |
Display all existing members
How would I (using a loop) pull in all of the existing users? I'm trying to loop through these users and then pull in meta data for each one. | You can use `get_users()`.
$args = array(
'fields' => 'all_with_meta',
);
$users = get_users( $args );
foreach( $users as $user ) {
// your display code here
var_dump( $user ); // so you can see what's in $user
}
`all_with_meta` will get the user and all the associated meta, if I'm reading the Codex page right.
**Update:** After testing the code, I find that `'number' => -1` returns nothing at all, so I removed it from the code.
### Reference
* `get_users()` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, users, user meta, profiles"
} |
current_time('timestamp') seems to be different from the real current time
Does current_time('timestamp') have an issue?
I am trying to get the current_time('timestamp'), and instead of giving me my **current time** :
Jun 26 2013 14:30
It gives me:
Jun 26 2013 21:30
I tried to check the seconds, and it gives me:
1372282238
Which is correct for the time given, but not for the **real current time**. What's happening? | It's a WP non-code programming thinking error.
Under General Settings > Timezone
It should be **set to your own timezone**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, timestamp"
} |
Where are custom field values stored in the database
I am using the advanced custom fields plugin for posts. I would like to know where custom fields are stored. I checked the `wp_posts` table. However, I could not find the posts with custom fields. I would like to know in which table are they stored in database. | From the codex for custom fields:
> The PostMeta information is stored in a new table, $wpdb->postmeta. This table has four fields:
>
> 'meta_id' - A unique id for each entry.
> 'post_id' - The ID of the post for this metadata.
> 'meta_key' - The name of the 'key'.
> 'meta_value' - The value associated with the key.
This of course assumings that ACF uses the default WordPress stucture and not a custom database. | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 18,
"tags": "custom field, advanced custom fields"
} |
How to add nofollow on all external links without plugin?
I have tried many plugins, which are doing the thing I want, but they are blocking my other plugins (1 in particular, which is indispensable for my site). Anyhow; how can I add a nofollow on all my outgoing anchors? Can someone help me out please? | This is how I would do it :
1/ create a filter to access the post content before it's displayed on page. See <
2/ Inside your fonction called (ie : my_the_content_filter in the example from the Codex) adapt this code : <
Cheers ! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins, permalinks, links, seo, nofollow"
} |
Counting posts by certain author with custom taxonomy
I'm using this code to display the last three posts of a custom taxonomy ('special') by a certain author:
<?php query_posts( array( 'taxo' => 'special', 'showposts' => 3, 'author' => 2 ) ); ?>
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endwhile; endif; ?><p>
Now I want WordPress to count also the total amount of posts this user made with this taxonomy and display the number, anyone knows how this would work?
Thanks in advance. | $args = array(
'taxonomy' => 'special',
'posts_per_page' => -1,
'author' => 2
);
$author_category_posts = new WP_Query($args);
$count_of_posts_by_author = $author_category_posts->post_count;
You can fetch the number of posts made by that author in specific taxonomy. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "taxonomy, count"
} |
Update a Wordpress post or page takes 60+ seconds
Since updating to Wordpress 3.5 I've had my updates of pages and posts become excessively slow. I've been timing them and they take 40-80 seconds to update.
I've spent the last 2 hours reading and trying everything I can find in the Wordpress.org forums yet nothing works.
I use maxcdn and CloudFlare for the frontside but the backside is unbearable.
I am on a MU install using 3.5.2 and I have disabled and tested each plugin. Seems to be a Wordpress issue and I'm looking for a workaround.
I'm on dual core VPS with 3GB of ram. | There's a plugin called Debug Bar which you can find at < Don't leave this enabled in production! But it will tattle on slow MySQL queries.
You might also wish to try using WP Clean Up. < This flushes out stale entries in your database, and does a little bit of table reorg/optimization. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "mysql"
} |
Three step order form, how to go to next step
I have an order.php that is in fact a custom page template. This template loads the first step of my order form via:
<?php include('order/order-step-one.php'); ?>
Now in this order-step-one.php my Next-button (post method) has to send the user to /order/order-step-two.php
Currently this does not work. I need to find a way to include order-step-two in the original order.php via the submit button in order-step-one. How do I achieve this? | In your `order.php` you will need something like this:
$step = (isset($_POST['step'])) ? $_POST['step'] : 'one';
switch ($step) {
case 'one':
// do step one
break;
case 'two' :
// do step two
break;
case 'three' :
// do step three
break;
}
Your form, of course, has to send the appropriate arguments. I used `POST`, which seems most appropriate for this kind of thing, but the same would be true for `GET`.
This makes everything process on your one page which WordPress knows about and that will greatly simplify things. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "page template, forms, include"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.