INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
append PHP function to the_content I'm using the Jetpack plugin for related items and social sharing. Both of these options filter the_content and append themselves to the end of it. The problem is that I'm using custom navigation in my posts which I output by using this code above and after `the_content` in my `single.php`. <div class="navigare"> <?php multipagebar(); ?> <div class="dropdown"> <?php TA_content_jump(1); ?> </div> </div> I know that to append something to the_content I can use a filter: add_filter('the_content', function($content) { return 'text-to-append' . $content; }); My question and problem is: how to append the navigation PHP functions so that they display before the related and social sharing items of Jetpack?
You will need to experiment with priority. add_filter( 'the_content', function($content) { return 'text-to-append' . $content; }, 10 // this is a priority number; 10 is default ); The "10" is the default priority. I don't know what number JetPack uses but your original code, without a priority, should run at "10" so I'd try "9", or "8". It should be possible to get your code to execute before JetPack's code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, filters, the content" }
Wordpress tags as twitter sharer URL hastags I want to share a wordpress post on twitter. I'm using this : <a href=" the_permalink() ?>&text=<?php the_title() ?>&via=<?php the_author() ?>&hashtags=<?php the_tags('', '') ?>" ></a> My problem is that `the_tags()` prints the tags inside the `<a>` tag. How can I use `the_tags('', '')` ( which separates the tags with comma as the hashtag needs to be ) for twitter hashtags ? I would appreciate any solutions without the use of a plugin
`get_the_tags()` with a little bit of processing will do it: $tags = get_the_tags(); $tag_list = wp_list_pluck($tags,'name'); $tag_list = implode(',',$tag_list); var_dump($tag_list); Reference: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags, twitter" }
Change header based on visitor choice I need to show a different header file ("header-tourist.php" and "header-agent-php") based on a choice the visitor will make. For example, I have 2 main buttons: `View site as Tourist` or `View site as Agent`. Based on this, I would like to show a different header throughout the whole site. What is the best way to approach this (global variables, sessions etc.) ?
I would approach this by setting sessions. So when the user makes a selection set a session which contains the users choice. Then in wp_head write an if statement that pulls the relevant template dependant upon the value of the session.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "headers, switch" }
Large Unwanted Space at the Bottom of Blog Posts I'm a bit stumped as the why there is such a large space at the bottom of the blog posts. I've tried removing the "more" tag, I've inspected the element multiple times, but just cant seem to get rid of it. Any suggestions? <
It's being caused by the style for `.clearfix:after`, which is doing a `clear: both;` (Screenshot of code) Adding the following to your CSS will resolve the issue: .post-content.clearfix:after { clear: left; } Screenshot of result
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, blog" }
How to remove the statusbar from the default wordpress editor? How to remove the letter P from the default wordpress editor? Previously i have removed that P but now the entire code changed from the `class-wp-editor.php` file. > !WordPress 3.9.1 WP_Editor
This ended up working for me, uses the tinyMCE init filter to remove the 'statusbar' entirely. /** Edit TinyMCE **/ function myformatTinyMCE($in) { $in['statusbar'] = false; return $in; } add_filter('tiny_mce_before_init', 'myformatTinyMCE' ); Even with CSS, I couldn't find a way to definitely remove the path but keep the status bar - here's the CSS option: function my_theme_add_editor_styles(){ ?> <style type="text/css"> .mce-path {display: none!important;} </style> <?php } add_action( 'admin_head', 'my_theme_add_editor_styles' ); **EDIT** Changed the hook from `init` to `admin_head` as `init` would cause widgets to auto close when you would drag them to the sidebar - strange occurrence.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "tinymce, wp editor" }
Let Posts be stored in another table I am trying to develop a plugin that creates a new table in the Wordpress database and I want to store there some kind of posts I create. I am trying to understand how to "clone" the Wordpress Posts/Add New/Categories/Tags and store the posts not in wp_posts, but in another table (eg.: wp_special_posts). At the moment I have the function that creates the table at the plugin activation, I created the page that grabs the information from the DB and display them using _WP_List_Table_ , but I do not have an idea on how, and if it is possible, to clone those sections. And help? Hint? **UPDATE** I want to create a product section with its own table, called _wp_product_instore_ , and I also want to use the standard _post-new.php_ interface, but put the posts in the _wp_product_instore_ table instead of _wp_posts_.
Use `save_post` action hook as shown below but write custom insert/update queries to save information in a different table. add_action('save_post', 'save_product_data'); function save_product_data($post_id) { //verify nonce and all other code... $title = $_POST['post_title']; //example variable $wpdb->query( $wpdb->prepare( " INSERT into wp_product_instore ( post_id, meta_key, meta_value ) values ( $post_id, 'post_title', $title )" )); //likewise you save all other variables for the post. } PS: This code hasn't been test run. Please modify to your need.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp list table" }
Blocking Plugin Css to load custom in template directory What is the most popular method to stop/block a plugin from loading their css styles ( located in the plugin directory) so that I can use the custom copy I made (located in my template directory). I ask this because I have one css document ( complied using sass,scss and grunt) that a visitor of my website loads. I want to add the plugin css to that document ( and to use the sass variable functions). Many thanks.
You can dequeue a style, for do that you can use wp_dequeue_style() or wp_deregister_style() To use both of them, first u need to find the **handler** of the style you want. Go to the plugin's folder you wanna remove the css and search for wp_enqueue_style or the file name and locate the handler. wp_enqueue_style( 'my-plugin-font-awesome', plugins_url('my-plugin/font-awesome.css') ); and i need to deregister or dequeue it add_action( 'wp_enqueue_scripts', 'my_fontawesome_deregister_styles', 100 ); function my_fontawesome_deregister_styles() { wp_dequeue_style( 'my-plugin-font-awesome' ); } or add_action( 'wp_enqueue_scripts', 'my_fontawesome_deregister_styles', 100 ); function my_fontawesome_deregister_styles() { wp_deregister_style( 'my-plugin-font-awesome' ); } OBS: the priority must be higher than the plugin's wp_enqueue_scripts()
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, themes, css" }
Why am I getting a white screen without a slash at the end of the address? I am currently building a custom Wordpress theme for my rugby team. I just noticed something and I can't work out whether this has been happening for a while and I have only just noticed it or it is a new thing. It would appear that any page address without a slash at the end of the address renders a white screen of death. For example (url)/fixtures/ works fine but (url)/fixtures Gives me a WSOD
I solved my own problem by debugging all the different functions.php includes. One of the files had some whitespace at the beginning.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "theme development, urls" }
Post list display year wise It's possible wordpress single category post display year wise for example: **2014** Post1 Post2 Post3 **2013** Post4 post5 **2012** Post6 Post7 Thanks
I don't like recommending a plugin, but this plugin does exactly what you need, and it is the easiest way to go. Just before I start, I would like to state that I don't have any affiliation regarding the plugin or its authors, nor am I marketing or trying to market the plugin in any way. OK, that out of the way, you should download and install the Simple Yearly Archive plugin. I quote from the plugin page > Simple Yearly Archive is a rather neat and simple WordPress plugin that allows you to display your archives in a year-based list. It works mostly like the usual WP archive, but displays all published posts seperated by their year of publication. That said, it’s also possible to restrict the output to certain categories, and much more The how-to-use page can be found here.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts" }
Should I store my Facebook access tokens? I've built a custom login page for a Wordpress site which uses Facebook for authentication. Is there any reason to store the Facebook access token in my WP database, or does it make more sense to use a PHP session? Are there any benefits to storing these values on my server?
There are a number of explanations here: < The time it takes for your server to talk with facebook does contribute to a good amount of slowdown. So it depends on how intensely you plan to use the api. In that case, storing the key and other fb related user data can cut that cross-talk considerably. If you are just using facebook as a login authenticator I don't think you need to bother. Cheers.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, facebook, session" }
How to count the length of a post title? Let's say that I have an entry titled **Crime & Punishment** I tried to count the number of characters of my entry titles using the following line: echo strlen( get_the_title() ); I expected the code would give me 18 characters for **Crime & Punishment**, but the result turned out to be 23 characters. The code above didn't give me my desired result since it reads the symbols within the title as a _HTML code_. Is there any workaround for such case?
There are actually two problems: 1. The `&` is encoded as `&amp;`, so you have to use `html_entity_decode()` first. 2. Multi-byte characters need more than one byte, and `strlen()` will fail with them. Don’t use strlen(). So use something like this: $title = html_entity_decode( get_the_title(), ENT_XML1, 'UTF-8' ); $length = mb_strlen( $title, 'utf-8' );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "php, title" }
Function Error after WP Upgrade to 3.9.1 Following the update to WP 3.9.1 and MySQL I am getting the following error on a site: > Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method dc_jqverticalmegamenu::header() should not be called statically in /home/xyzsite/public_html/wp-includes/plugin.php on line 470 The reference is to this plugin. A quick search shows about 82 pages out there with the same error, but no reference to a solution. I would appreciate some guidance on resolving this.
You should contact the plugin author, because plugin support is generally off topic on this site. But ... I got curious, peeked into the plugin code and found this line: add_action( 'wp_head', array('dc_jqverticalmegamenu', 'header') ); where the `header()` method is assumed _static_ , but it's not: function header(){ // ... } That's why this strict notice pops up. The plugin creates an instance of the class through: // Initialize the plugin. $dcjqverticalmegamenu = new dc_jqverticalmegamenu(); so you should instead try: add_action( 'wp_head', array( $this, 'header') ); and similar for the other static calls.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, errors" }
Can I protect a type of content site-wide with a single password? I am developing a theme for a client who has a catalog of products. Each product has a spec sheet that he wants to make available to logged-in users. It's not a real security issue, just a means to simplify the page for casual visitors. Right now he emails clients a password and keeps track of logins based on which password he gave out. He'd like to continue doing that. So I'd like to come up with a way of: * logging a user in with a single field * using `is_user_logged_in()` and related inquiries to check whether to display links to the protected content * denying such visitors access to the Admin side completely Is this out of the scope of WP user roles? If not, any suggestions on how I could achieve this?
I would approach the situation like: 1. Create an user with subscriber role. 2. Add a meta field to the user profile. This will be the password like field you will verify the user against. 3. Use AJAX to verify the password(meta value) entered by the visitor and display product specification accordingly. You do not have to worry about WP user roles or visitors getting access to admin side. Hope this helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login, user roles, password" }
Check and dequeue if multiple stylesheets exists using wp_style_is? I need to dequeue styes for 3 plugins that load the same font stylesheet so i come up with the following function that of course not working: add_action('wp_enqueue_scripts', 'dequeue_by_handles', 999); function dequeue_by_handles() { $handle = array( 'fontawesome', 'font-awesome', 'font-awesome-style' ); if( wp_style_is( $handle, $list = 'enqueued' ) ) { wp_dequeue_style( $handle ); } } Please note that firstly I need to check if a stylesheet handle exist then dequeue it. Thank you.
I have not tested this, but I imagine it is because you are passing an array to the $handle variable in your `wp_style_is()` function and not a string. Maybe try looping through the array so you pass it a single string to check against each time. Something Like this... add_action('wp_enqueue_scripts', 'dequeue_by_handles', 999); function dequeue_by_handles() { $handles = array( 'fontawesome', 'font-awesome', 'font-awesome-style' ); foreach ($handles as $handle) { if ( wp_style_is( $handle, $list = 'enqueued' ) ) { wp_dequeue_style( $handle ); } } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "css" }
Wordpress loop for multiple custom post types I want to loop through 3 custom post types + posts and display the latest post from each. This is what I have so far. This only takes the four most recent posts but not one only from each post type. Many thanks in advance <?php $args = array( 'post_type' =>. array('post','mixes','artists','releases'), 'posts_per_page' => '4', ); query_posts( $args ); while ( have_posts() ) : the_post(); ?> do stuff here <?php endwhile; ?>
That way won't work as you have found out it will grab just the 4 posts from the loop. To do this you need to do a search of each post type, something like below will work: $terms = array('post', 'mixes', 'artists', 'releases'); if ( !empty( $terms ) && !is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $my_query = new WP_Query('posts_per_page=1&post_type='.$term); while ($my_query->have_posts()) : $my_query->the_post(); echo '<h2>'.$term.'</h2>'; echo '<ul>'; echo '<li>'.get_the_title().'</li>'; echo '</ul>'; endwhile; wp_reset_query(); } } That should do the following: Post Type 1 \- post title Post Type 2 \- post title Post Type 3 \- post title Post Type 4 \- post title
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, loop" }
Password protect media attachment - share across guests I'd like to show certain content to people with a password, specifically links to media files like this: <?php if($currentuserid == foobar): ?> <a href="PROTECTED/CONTENT.pdf">LINK</a> <?php endif; ?> If I were to create a user with ID `foobar`, and then give its password to several people, would it cause any problems if they all decided to use it at once? I would only want to use their logged-in status to show/hide certain content - they would not be accessing the admin side.
When logging into WordPress with a user account, WordPress checks your credentials against those stored in the database. If they are correct, it then sets a session variable in your browser and you are able to view all areas that check against this session variable to gain access to. Sessions are set on a per browser basis so it does not matter how many browsers are accessing the site as they will each have this session created on their own browser if their credentials successfully authenticate. You would only run into problems if for example multiple users were trying to write to the database at the same time for example but in your case there is no admin access so for viewing purposes only, not problem. Hope this explanation makes sense :-)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "login, attachments, media, user access, password" }
Use phpbb user database for Wordpress I've got a phpbb forum and recently I've added a Wordpress website to my domain. I want my phpbb users to be able to login to my Wordpress page using the same username and password they have on my phpbb forum. I've tried to get the connection working. But I can't. So does anyone have a solution for this?
How about trying the WP-United plugin? It seems to do what you want: > **User integration:** including single sign-on, synchronised profiles and avatars, and user management. Works with external registration modules such as social login plugins. Users in phpBB get accounts in WordPress and vice versa. Completely controllable and customisable by setting permissions for who can integrate and at what level, using a unique drag-and-drop interface. From its reviews: > Thankfully this plugin lets me synchronise phpBB accounts with WordPress so that users that register on my forum can make use of the aforementioned WordPress features without having to make a separate account for that. Here are a couple other plugins that might be worth a look, too: * phpBB Unified Login * PHPBB Single Sign On Tip for the future: This page is your best friend.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "users, login, forum" }
wordpress add field to post_class I need to add a custom field to my article post but not sure how to add an additional class to it. Currently the classes get pulled through like this `<?php post_class($classes); ?>`. However I need to add a custom field to this as well. To demonstrate ive added a class= but this doesnt work as class= is being added twice. <?php post_class($classes); ?> class="<?php the_field( "size" ); ?> So i need post_class and the_field to work together.
I would first store your field value in a variable after your loop just before the posts HTML tags start: <?php $size = the_field( "size" ); ?> And then add this variable to the post class function: <?php post_class($size); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, post class" }
Hide H1 Title using the_title filter I am trying to hide the pages H1 header IF a custom field specifies this. On a page back end I have added a custom field: Name = hide_title Value = true I then want to hide only the H1 using a filter. The following code does not work but is the result of my noodling around. Can anyone suggest a fix for this code or an alternate way of approaching this. I do not want to amend the core template files. Thanks // Hide H1 Title add_filter('the_title', 'hide_title', 10, 2); function hide_title($title, $id) { global $post; $key = 'hide_title'; $meta = get_post_meta($post->ID, $key, true); if ($meta = 'true') $title['post_title'] = ''; return $title; }
Depending on the way your theme uses `the_title`, hooking into the `the_title` filter may or may not hide the title h1. What theme are you using? The `the_title` filter passes two arguments: the title (string) and the post ID. Therefore, treating the title as an array (it looks like you're assuming `$title` is an array of post data, trying to set `$title['post_title']`. To have `the_title` return an empty string if the custom field "hide_title" is not empty, the following would suffice: add_filter( 'the_title', 'wpse145940_hide_hidden_title', 10, 2 ); function wpse145940_hide_hidden_title( $title, $postid ) { if ( get_post_meta( $postid, 'hide_title', true ) ) { $title = ''; } return $title; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, hooks, title, post meta, get the title" }
Custom category link in wp_list_categories() I simply want the link to be `/catname` instead of `/category/catname` for all the links listed using the `wp_list_categories()` function. Any ideas for this?
Okay, I've found the answer. This is not possible. So I had to build the permalink manually this way: <ul class="list-items categories"> <?php $category_ids = get_all_category_ids(); $args = array( 'orderby' => 'slug', 'parent' => 0 ); $categories = get_categories( $args ); foreach ( $categories as $category ) { echo '<li><a href="' . $category->slug . '" rel="bookmark">' . $category->name . '</a> </li>'; } ?> </ul>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "categories" }
How to use wp_footer() on a 404 page? I am designing my 404 error page, for which I created a separate header and of course I need a separate footer. As for the latter, instead of creating a new one, would be enough for me to ensure the`wp_footer();` to be just before the closing body? Or is there something in the `get_footer()` function that makes it necessary?
`get_footer()` will bring footer.php, so including `wp_footer()` before the `</body>` will be more than enough in this case.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "404 error, footer" }
Displaying a custom taxonomy term's name & description How can I display a term's name & description for a custom taxonomy within The Loop (single post page template)? Currently I can show its name like this: the_terms( $post->ID , 'director', 'director: '); but can't get the description **EDIT** I dont want to use extra php coding like: $directors = get_the_terms($post->ID ,'director'); foreach($directors as $director){ $director_name = $director->name; $director_desc = $director->description; }
Have a look at `get term()`. This return the name and description for a term. Here is the axamples given in the codex > Gives you term name: e.g. Term Name Example > > $name = $term->name; > > Gives you term description: e.g. This is my new cool custom term. > > $desc = $term->description;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom taxonomy, description" }
How To Style Links in Content Area With <span> Tag Automatically? This is like a suicide mission for me. I have to avoid CSS because I want to build a website that will help me to create HTML templates for email campaigns. Email readers can't read CSS, so CSS is not a solution for me. When I put in WP content editor this: <a target="_blank" href=" Anchor text</a> I want to see something like this on the front-end: <a target="_blank" href=" style="font-family:Arial,Verdana;font-size:12px;font-weight:12px;color:#337D98;"><strong>My Anchor text</strong></span></a> Does anybody have an idea how to solve this?
If you decided to go that route, this should work. Just add this to your themes functions.php file: // Add Shortcode function link_inline_styling( $atts , $content = null ) { // Attributes extract( shortcode_atts( array( 'url' => '', 'target' => '', ), $atts ) ); // Code return '<a href="'.$url.'" target="'.$target.'" ><span style="font-family:Arial,Verdana;font-size:12px;font-weight:12px;color:#337D98;"><strong>'.$content.'</strong></span></a>'; } add_shortcode( 'link', 'link_inline_styling' ); and then in your content area you can use the shortcode like this: [link url=" target="_blank"]My Anchor text[/link] The output will be this: <a href=" target="_blank" ><span style="font-family:Arial,Verdana;font-size:12px;font-weight:12px;color:#337D98;"><strong>My Anchor text</strong></span></a>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, css, html email" }
How to Display Details page of future (scheduled) posts My question here is to display all the single detail page of future scheduled posts. It is returning 404 page. How can this be done in wordpress? What I have used so far is $args = array( 'posts_per_page' => 10, 'category__in' => $category->term_id, 'orderby' => 'post_date', 'meta_key' => 'starttime', 'order' => 'ASC', 'post_type' => 'post', 'post_status' => array('publish','future'), ); $loop1 = new WP_Query( $args ); From this code I get published, and scheduled posts. The permalink of the published post is working fine. But it is not working for scheduled posts, and redirecting to 404 page error.
After some research this worked for me: add_filter('the_posts', 'show_future_posts'); function show_future_posts($posts) { global $wp_query, $wpdb; if(is_single() && $wp_query->post_count == 0) { $posts = $wpdb->get_results($wp_query->request); } return $posts; } Hopefully it will work for others who are in same problem.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "scheduled posts" }
Plugin options not appearing on options page using tabbed navigation I've modified the plugin options page for my plugin to use tabs, using the existing WordPress system for this. However, The actual options are not appearing on the screen - just the tabs and the "Save Changes" button. Here is the code for the options page. What am I missing?
I figured out the problem. I was referencing the wrong page ID in my add_settings_section() call.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, plugin options" }
Developer plugin to echo template names/filepaths I am looking for a Wordpress plugin that prints file template names, maybe with a designating border. Magento has "template hints", as you can see in this screenshot: !magento If there is not such a plugin and someone would like to develop it with me, let's do that, too!
I use a plugin called Query Monitor, that does a whole bunch of stuff, including showing the page's template. It's in the WordPress Repo.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, templates" }
Duplicating Complete Wordpress Install for Development and then Redeployment? What is the best way to duplicate an entire Wordpress site, including database, themes, plugins and all associated settings to another URL for development purposes, and then redeploying it back to the main site? The site in question is a large Wordpress install — Wordpress 3.5 to be specific — with thousands of posts and a large audience. I have seen various plugins which purport to do this, but what is the best way to duplicate for development and then, in a month or two, redeploy back? I am committed to keeping the development database up to date manually with the existing database once the split occurs – I don't envision using the same database on two installs or whatever. Thanks.
The environment I work in has a development, staging and production server. We set up a Git repository and don't track the wp-config file. We always copy the DB down, production -> staging -> development, and not the other way around. Only thing you have to do when you pull commits after your create plugins, update plugins or modify URL stuff is activate, deactivate/reactivate and flush the permalinks.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "database, duplicates" }
wordpress testimonials I have add a testimonial plugin to show the all featured testimonial on my wordpress home, and category pages. But on category page testimonial slider not working properly. I have also check the JS issue, nothing have to find. Please give me specified answer. Thanks in advance. Please specify me where I need to put the testimonials JS.
Seperate the testimonial JS from the default JS code. There may be a JS conflict. Check for the js folder located at theme/yourtheme/js Try creating a seperate js file instead of editing in core js file
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom taxonomy, customization" }
Get template part vs locate template function I'm in single.php where I'm trying to get related-posts.php template. The problem is that when using get template part the related-posts.php isn't getting custom taxonomy name from single.php in `wp_Query`. The solution is getting the wp post terms once again in related-posts.php in order to use `get_template_part`. But technically it shouldn't be required since parent (single.php) is already having it. But when I use locate template function it works fine. I feel that this method would be slower than `get_template_part`. What should I do?
First of all note that `get_template_part` internally uses `locate_template`, so your feeling that the latter is slower is wrong. If you look at the code, `get_template_part` is little more than a wrapper for `locate_template`, so if one work and the other not, there are 2 possibilities: * you are using `get_template_part` wrong * there's some hook on `"get_template_part_{$slug}"` action that prevent it works However, if `locate_template` works, use it: it's not slower, to be honest it can be pretty faster if there are functions hooked on `"get_template_part_{$slug}"` that slow down execution.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "templates, get template part" }
How to change permalink on post click on post listing page I have a posts listing page, my requirement is that I want to change the url on the click of the post and expand the post to full detail. I am not sure if this can be done without refresh. Any ideas how this can be done?
you need to using jquery function functionality <script> var current_main = window.location.pathname; var current= document.URL; //var lastElement = current.substr(current.lastIndexOf('/') + 1); var main_url = currentq+"?"+thechosenone+"="+thechosenone; var main = history.pushState(current,"", main_url ); </script> by using this you can able to append the url's with specified get methods. I hope this will help you
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, permalinks" }
Uploaded Images not re-sized to ( Thumbnail, Medium, and Large ) size I have a WordPress site that was working perfect before moving to a new server, The problem is when I upload any image it uses the original size in all places in my website ( means no re-size for the image - Thumbnail, Medium, and Large), I use FTP to access the Upload folder and I found the original image only without (Thumbnail, Medium, and Large size). I checked my Media Setting and its okay without any problem, I hope someone could help.
You need to have the GD PHP5 Library installed. Alternatively the image crop sizes are all bigger than the images you are trying to upload. WordPress skips over these if that is the case. First check if you have GD installed and version. You can create a test.php file with this code below. Upload to your server and browse to the file via your browser to view the result. <?php // Display your GD library info $gdInfoArray = gd_info(); $version = $gdInfoArray["GD Version"]; echo "Your GD version is:".$version; echo "<hr />"; foreach ($gdInfoArray as $key => $value) { echo "$key | $value<br />"; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Trying to hide subcategories which have categories without posts On custom archive pages, I want to show subcategories that **_don't_** have their own posts but have sub-subcategories that **_do_** have posts. And if a child category does not have posts, I want to hide its parent too. Here is part of the code I'm using: if(is_category() && $has_category_children){ //$has_category_children is true if the current category has subcategories. $args = array( 'hide_empty' => 1, 'hierarchical' => 0, 'parent' => $term->term_id, ); $categories = get_categories($args); foreach ($categories as $cat) { echo $cat->category_nicename; } } What is the right approach to achieving this?
I ended up ensuring that all parent and grandparent categories are selected for a particular article, instead of just the child category. That solved my problem. Now, sub-categories that have sub-sub-categories with posts are not treated as "empty".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, categories" }
How would I go about adding custom header images per category? I am using WooCommerce along with the Neighborhood theme. I am trying to figure it out but I need some guidance if anyone can offer it.
You can do it by adding some code or by installing a plugin. You can add the following code inside your loop: if (in_category('news')) { get_header('news'); } else { get_header(); } This code checks if the current post belongs to a category that's called news, and if that's true, then it will use header-news.php instead of header.php. You will have to create header-news.php inside your theme and add your custom header image in it. Or you can install the following plugin which allows you to add a custom header to pages, posts, categories, or tags: Unique Headers
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, customization, header image" }
how can get database name in wordpress? I want to get WordPress database name. I have also try to get database name from $wpdb but failed. When print the $wpdb it give an object array but i don't know how to get database name from object array.
To get the db name using `$wpdb`: global $wpdb; echo $wpdb->dbname; It will return database name as a string.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "database" }
get meta fields and taxonomy of any post type I have created 6 different custom post type, each having different post meta and taxonomies associated with it. I am displaying all different custom post types in a dropdown using `get_post_types()` function, Now, onchange of dropdown, I want to display associated meta fields and taxonomy. I know that this information is not saved in DB unless a post is created, so is it possible to read this information like WordPress is reading or please suggest me if this is possible or not.
If I understand correctly you want to get the taxonomies associated with a custom post type object, not with a specific single post. To do that you can use get_object_taxonomies(). For example, to get the names of the associated taxonomies to "my-custom-post-type": $taxonomies = get_object_taxonomies( 'my-custom-post-type', 'names' ); foreach( $taxonomies as $taxname ) { echo $taxname; } I think you can not do the same for meta fields because meta fields are associated with a specific single post not with a post type object. You will have to hardcode the relationship between metafields and custom post type.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, post meta" }
Add role and edit page capabilities i've create a new user role and i want this user can edit page and use custom post type. For custom post type i've resolve but for the page not function. On backend the user can only see the page but can't edit. Where wrong? /* aggiungi ruolo */ add_role('brokers', 'Brokers', array( 'read' => true, // True allows that capability 'edit_pages' => true, ));
The `edit_pages` capability only allows a user to edit his own unpublished pages. It does neither allow to edit others pages (this would require the `edit_others_pages` capability) nor does it allow to publish or edit published pages (capabilities: `publish_pages` and `edit_published_pages`). I’d strongly recommend having a look on this wonderful table: < listing up all avaliable native WordPress capabilities against the roles they belong to.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, capabilities, user roles" }
Encoding Issue while using French in WordPress I just migrated some content from another CMS [SPIP] into WordPress and I am seeing weird characters like ' Unité dans la diversité ', this is supposed to come in french but its not . Please let me know what can be done to convert this content into Unicode. Praveen
I ran the Following bash script for the conversion from non unicode to utf-8 #!/bin/bash -e DB_HOST="localhost" DB_USER="username" DB_PASSWORD="paassword" DB_NAME="dbname" mysqldump -h "$DB_HOST" -u "$DB_USER" - p"$DB_PASSWORD" --opt --quote-names -- skip-set-charset --default-character-set=latin1 "$DB_NAME" > /tmp/temp.sql; mysql -h "$DB_HOST" -u "$DB_USER" - p"$DB_PASSWORD" --default-character- set=utf8 "$DB_NAME" < /tmp/temp.sql; This did the job. I opened the DB in sublime text and the french characters were rendered correctly. More information on this at <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "encoding" }
can't edit widgets after moving from subfolder to root I had some issues with migration: childtheme that was ranamed and working was automatically renamed back + a lot of wrong absolute apps from even older version on site... Now, after I fixed everithing and changed site url to root, front end is working fine but backend has some UI issues; dropmenues/submenues not working and widget ares are not expanding so widgets can't be edited. Any suggestions? EDIT: It seams like only widgets are affected... AJAX?
If anyone will ever have these issues, here are some solutions: 1. deactivate WP UI plugin - but if you still want to use it, try to modify wp_register_script( 'wpui-script-before', site_url( '?wpui-script=before' ), **___something___** ); to wp_register_script( 'wpui-script-before', home_url( '?wpui-script=before' ), _____something_____ ); in: /wp-content/plugins/wp-ui/wp-ui.php /wp-content/plugins/wp-ui/admin/wpUI-options.php /wp-content/plugins/wp-ui/inc/widgets.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, dashboard, migration, widget text" }
Display different Images depending on the current day I need to create a grid layout with images, which change daily. So i could build a pool of images in advance for a whole month and the page shows automatically the appropriate image every day. The image could be named after the date or could be connected to this information on another way. How do i achieve this in wordpress? I'd appreciate your input.
You can put all the related images in a specific directory. Let's say the directory is `grid_images` and all the images have `jpg` extension. Then when you want to show the image, you can get the current day of the month and pull the image accordingly. $image = PATH_TO_GRID_IMAGES_DIRECTORY . date( 'j' ) . '.jpg'; Once you have the image variable you can use this as per your need. **Note:** The images should be named as `1.jpg`, `2.jpg`, .... , `31.jpg`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Change height of Add New Post input box The textarea box on the Add New Post page is too high for my application. I'd like to change it to 260px high. However the style is embedded. What's the best way to change it, without altering the original file?
**EDIT VIA COMMENTS** <?php function add_styles() { ?> <style type="text/css"> .wp-editor-container { clear: both; height: 246px !important; } </style> <?php } add_action('wp_head', 'add_styles');
stackexchange-wordpress
{ "answer_score": -3, "question_score": 0, "tags": "wp admin, css" }
Display unused categories in dropdown I have created a front end post with a form and I would like to have several categories for the user to choose between. But the problem is that the dropdown category only show those categories that are in use. I need it to show all categories even if they are not in use. The code I'm using is following: wp_dropdown_categories( 'show_option_none=Kategori&tab_index=4&taxo. nomy=register_vote_category' );
`wp_dropdown_categories()` has a parameter specially to hide or to show empty categories. > **hide_empty** > > (boolean) (optional) Show (0/False) or hide (1/True) category with no posts. > > Default: 1/True You can simply just hide_empty=0 to your arguments
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories" }
WordPress 302 Redirect to Holding Page Once again struggling with htaccess. I've successfully redirected the home page to my holding page with the following rule but it's not applying to child pages for some reason (mydomain.com/child-page). # MAINTENANCE-PAGE REDIRECT <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_URI} !/holding [NC] RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|eot|svg|ttf|woff|css) [NC] RewriteRule ^(.*)$ /holding [R=302,L] </IfModule> What am I doing wrong? I know it must be to do with the '^(.*)$' bit but I can;t seem to find the correct syntax.
I would place the redirect inside WordPress. It lends you more control, and you don't need to worry about WP conflicting with your own `.htaccess` rewrites anymore. function wpse_147377_redirect_to_holding() { if ( ! is_page( 'holding' ) ) { wp_redirect( site_url( 'holding' ) ); exit; } } add_action( 'template_redirect', 'wpse_147377_redirect_to_holding' ); Place it in a "Must Use" plugin (`wp-content/mu-plugins/my-plugin.php`), a regular plugin, or your theme's `functions.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, htaccess" }
get categories the post was in and just been removed from I have a function hooked to the save_post hook. this function is mostly concerned with the categories that the post is in. My function does the following: function post_save_hook($post_id){ $categories = get_the_category($post_id); foreach($categories as $category){ //Handle this category } } Say I have a category called `featured`, and a post was published under this category. then the same post was edited and removed from the `featured` category, in this case my function won't detect this change. So what I want is to know if this post was in some category and removed from it.
`save_post` runs too late to do what you are trying to do. That hook fires after the post and related meta data are stored. The category has already been removed at that point, and WordPress keeps no record. You will need to hook into the save process earlier, perhaps `pre_post_update`: add_action( 'pre_post_update', function($post_ID,$data) { var_dump($post_ID,$data); var_dump(get_the_category($post_ID)); die; }, 10,2 ); Proof of concept code only, obviously.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, hooks, save post" }
How to instantly delete posts/pages permanently? For development purpose I need to constantly fill and unfill a Wordpress instance with dummy content. Deleting everything in two steps is quite annoying, so I'm wondering if there's a way to cut the long way around to trash when deleting posts. Please help.
Considering this site is WordPress Development, I'm assuming you would like to know how to (force) delete posts programmatically. wp_delete_post(257, true); // `true` indicated you would like to force delete (skip trash) More on `wp_delete_post()` function
stackexchange-wordpress
{ "answer_score": 9, "question_score": 2, "tags": "customization" }
How to count posts of a category and of a category limited by a tag I have two urls, and I want to know how many posts will be displayed there, when I click them. The goal is to show the visitor in the navigation of those urls, how many postings are found there. As far as I can analyze those urls I would say it's about a category and then about a category and a tag. But pleas tell me if I am wrong. Here are the two Urls, which actually end up in a blog-roll page (pseudo code): and while `category` is the string `"category"` Is my question somehow clear? Do I have to use `count_posts()` function?
You could run a new instantiation of WP_Query. $query = new WP_Query([ 'category_name' => '<category_slug>', 'tag' => '<tag_slug>', 'fields' => 'ids', // To minimize the query, since we just need a count ]); More on `WP_Query` Then all you need to do is reference `(integer) $query->found_posts`. Hope that helps. I don't think there is a better way unfortunately.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development" }
Can I access Posts of custom-fields via URL? Is there a way to access all posts where the value of a given custom field is concurrent? like you can access all posts of a category like this: so I would like to have a form like
If you are asking if there is _native_ way then the answer is no. While simpler and older representation of meta queries using `meta_key` and `meta_value` would technically fit into URL, they are not registered as public query variables. Even _considering_ registering them as such would be too dangerous in a blanket way, because that might cause all sorts of private information become accessible. However, if you are asking if this is _doable_ , then answer is that it's completely is. You would need to create custom rewrite rule to respond at such URL and limit the processing to specific (and publicly safe) custom fields.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, permalinks" }
how to customize rss feed tags using hooks? My RSS feed is displaying an XML tag which I either want removed, or emptied. The tag in the XML looks like so: `<wfw:commentRss>remove/this/uri</wfw:commentRss>` I have never used hooks before but I know this can be done using them.. Any points in the right direction?
Removing the tag altogether would be inconvenient since it's hardcoded in `feed-rss2.php` template file. You could replace the calling function in `do_feed_rss2` hook, but still would need to fork whole template. It is, however, easy to cancel out content there. `get_post_comments_feed_link()` passes output through the filter, so something like this should do it (not tested): add_action( 'do_feed_rss2', function() { add_filter( 'post_comments_feed_link', '__return_empty_string' ); }, 9);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "filters, hooks" }
Remove child category from URL I am moving a custom website with a WP blog to WP in one install The old URL was: domain.co.uk/blog/post-name The New URL is currently (while using a Category URL rewrite of /%category%/%postname%/ ) domain.co.uk/blog/category/post-name Is there a way to remove the child category from the URL so it will be the same as the the old URL (so I don't need to 301 redirect all the old url's) The client still wants the posts to be categorised hence the need for the custom permalink
You can use the `post_link_category` filter to remove child categories from permalinks: function wpse147453_remove_child_categories_from_permalinks( $category ) { while ( $category->parent ) { $category = get_term( $category->parent, 'category' ); } return $category; } add_filter( 'post_link_category', 'wpse147453_remove_child_categories_from_permalinks' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "url rewriting" }
Does Google detect files in the Wordpress plugin directory Will Google detect files in the Wordpress plugin directory? Example: /wp-content/plugins/random-image-gallery-with-fancy-zoom/js/ /wp-content/plugins/revslider/rs-plugin/videojs/demo.html I put blank index.php's on the folder and directory, and a meta noindex in the HTML. Will this keep Google from indexing it?
It will, but why not go further and add a robots.txt? # Google Image User-agent: Googlebot-Image Disallow: Allow: /* # Google AdSense User-agent: Mediapartners-Google Disallow: # digg mirror User-agent: duggmirror Disallow: / # global User-agent: * Disallow: /cgi-bin/ Disallow: /wp-admin/ Disallow: /wp-includes/ Disallow: /wp-content/plugins/ Disallow: /wp-content/cache/ Disallow: /wp-content/themes/ Disallow: /trackback/ Disallow: /feed/ Disallow: /comments/ Disallow: /category/*/* Disallow: */trackback/ Disallow: */feed/ Disallow: */comments/ Disallow: /*? Allow: /wp-content/uploads/
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, seo" }
Are term IDs unique even between multiple custom taxonomies I can't find the answer for this question on either Wordpress or here, nor via Google searches, so I'm throwing this out to the community. If you have two taxonomies, and you add 1 term to each taxonomy, will the first term added in taxonomy_1 have a term ID of 1 and the second term added to taxonomy_2 have a term ID of 2?
The short answer is no. If you have a look at terms, taxonomies and categories, all of them is stores in the database in the `wp_terms` table. Every one of these are assigned a numerical value that is unique to that term/category/taxonomy. This don't just apply to "objects" added to `wp_terms`, but to anything added to a specific table in the db. So nothing added to a specific table will ever have the same ID These ID's are assigned according to the "object's" place in the specific table, in numerical order. So if the last item in that specific table is number 16, the next item that is added will be number 17, hence ID 17 will be assigned to that "object". The next "object" added will then automatically be ID 18 and so forth So, to conclude, ID's are assigned to their place in a table, and not according to their relation to another "object"
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, terms" }
Retrieve Menu name for nav_menu_item Given a `nav_menu_item` object, how would I determine the name of the Menu it is associated with? I have a couple menus defined in my theme, as well as, a `nav_menu_css_class` filter. Inside the filter, I only want to add classes to one of the menus. If I can dynamically pull the menu name using the `$item` variable I can make sure I'm only acting on a specific menu.
The third argument passed to the filter are the `$args` used for `wp_nav_menu`: function wpse_147499_nav_menu_css_class( $classes, $item, $args ) { print_r( $args ); exit; } add_filter( 'nav_menu_css_class', 'wpse_147499_nav_menu_css_class', 10, 3 ); ...which gives you: stdClass Object ( [menu] => [container] => [container_class] => [container_id] => [menu_class] => [menu_id] => [echo] => 1 [fallback_cb] => [before] => [after] => [link_before] => [link_after] => [items_wrap] => [depth] => 0 [walker] => [theme_location] => ) Obviously the values of these vary, and never assume that one will always be non-empty - but hopefully you should be able to differentiate between menus.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus" }
wp_insert_posts Fatal error: Maximum function nesting level of '100' reached, aborting! I'm having a weird problem I have written the code as below: add_action('save_post', 'save_post_func'); function save_post_func(){ include_once(ABSPATH . WPINC . '/feed.php'); $rss = fetch_feed($url); if (!is_wp_error($rss)) { //ini_set('xdebug.max_nesting_level', 1000); <-- Doesn't work $maxitems = $rss->get_item_quantity(5); $rss_items = $rss->get_items(0, $maxitems); foreach ($rss_items as $item) { // count($rss_items) = 5 ??? wp_insert_post(array('post_title' => 'a')); // inserts > 100 records ??? } } } Displays this error: > Fatal error: Maximum function nesting level of '100' reached, aborting! Any help? Where is the problem all seems ok...
Fixed the problem I've added this line before the insertion of the posts. remove_action('save_post', __FUNCTION__); final code: add_action('save_post', 'save_post_func'); function save_post_func(){ remove_action('save_post', __FUNCTION__); include_once(ABSPATH . WPINC . '/feed.php'); $rss = fetch_feed($url); if (!is_wp_error($rss)) { $maxitems = $rss->get_item_quantity(5); $rss_items = $rss->get_items(0, $maxitems); foreach ($rss_items as $item) { wp_insert_post(array('post_title' => 'a')); } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, wp insert post, save post" }
Filter on widget-title does not work with custom links I added a filter to my widget titles and it looks like the filter doesn't apply on links, which are created with the links-sidebar. It does work perfectly on the blogroll or search widget Here's a Screenshot, to illustrate what I mean. add_filter('widget_title', 'new_title', 99); function new_title($title) { $title = 'text'; return $title; } I disabled all plugins and tried the same the default wordpress themes and got the same results.
The "Links" widget uses `wp_list_bookmarks`, which outputs a nested list similar to: <li> <h2>[category]</h2> <ul class="xoxo blogroll"> [links] </ul> </li> You can override `[category]` using the `link_category` filter: function wpse_147543_link_category( $title ) { $title = 'title'; return $title; } add_filter( 'link_category', 'wpse_147543_link_category' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, widgets" }
Accessing Variables Used In a Plugin Using PHPStorm + XDebug I'm currently attempting to use XDebug 2.2.1 and PHPStorm 7.1 to debug my WordPress plugin. So far, I've successfully installed XDebug and breakpoints are working fine. However, I'm unable to access any of the variables being used in the functions in which I'm breaking. For instance, I break in this code: function generateGoalCard($sub) { $goalID = $this->CodeLibrary->convertStringToInt($sub->goalID); $userID = $this->CodeLibrary->convertStringToInt($sub->userID); print('goalID: '); // BREAK POINT HERE // Other unimportant code ... } Below is a screenshot of the debugging window at the above break point. As you can see, `$goalID` and `$userID` are not accessible. How can I gain access to my plugin's variables? !enter image description here Here's the screenshot in DropBox.
My current understanding is that the problem was caused by the fact that my project only encompassed a plugin directory while the page I was debugging was generated by many php files outside the project directory. The fix took just two changes to PHPStorm preferences: 1. Go to `PHPStorm > Preferences > Project Settings > PHP > Debug` and disable `Force break at the first line when no path mapping specified`. 2. Go to `PHPStorm > Preferences > Project Settings > PHP > Servers` and disable `Use path mappings (select if the server is remote or symlinks are used`. With those two changes, it all seems to be working perfectly fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development, debug" }
Active DB queries in Wordpress? I just make some researches regarding to wordpress DB queries and I just wonder if I miss something a normal `SELECT` query for example in Codeigniter with active records would look like if I assume I init my DB instance in both of the cases inside of a Class as `$this->db` $data = $this->db->get('wp_mytable'); $data->result(); **Wordpress way** $data = $this->db->get_results('SELECT * FROM wp_mytable'); and if I would use a condition than would look like $this->db->select('*'); $this->db->from('wp_mytable'); $this->db->where('id', 1); $this->db->result(); I find this handy if I would use more than one `WHERE` as array but I do not see this kind of query types in wordpress wiki or I do not search in the right place?
`wpdb` doesn't include such kind of API, mostly since it descended from ezSQL which didn't either (as far as I remember). While there are _some_ helpers for insert/update stuff, most of query abstraction happens in `WP_Query` since that's where bulk of complicated querying is typically going on.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "mysql, wpdb" }
Remove from "Wordpress" when reciving email (Should I remove filter?) I am getting "Wordpress" when I sending my email using wp_mail. So to remove "Wordpress" from my e-mail I am using filter like so: //Remove "Wordpress" when receiving email function remove_from_wordpress($email){ $wpfrom = get_option('blogname'); return $wpfrom; } add_filter('wp_mail_from_name', 'remove_from_wordpress'); It works great and now I am getting site name instead. My question: Is this a proper way to do it? Because I am concerned that my filter will maybe break some other plugins. If that is the case how can I avoid that? Thank you.
Yes, `wp_mail_from_name` filter is a correct way to change the "From" name in emails sent by WordPress. It should not cause any issues with other plugins.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp mail" }
When to use _e and __ for the translation? What is difference between `_e()` and `__()` functions for the translation? In what cases `e()` and `__ ()`should be used?
If you want to `echo` the translated string, then you will be using `_e` and when you just want to have the translated string, then you will be using `__`. **Example:** _e('this is a message', 'twentyfourteen'); is same as echo __('this is a message', 'twentyfourteen');
stackexchange-wordpress
{ "answer_score": 46, "question_score": 25, "tags": "theme development, translation" }
unregister_sidebar in child theme not working I'm woking on a chid theme for Ohsik. I'm trying to unregister a sidebar, but nothing is working Here's my function.php child theme code: function unregister_footer_sidebar() { unregister_sidebar( 'sidebar-2' ); } add_action( 'widgets_init','unregister_footer_sidebar',11); add_action( 'widgets_init', 'ohsik_widgets_init',12); What am I doing wrong? Any suggestions to solve the problem?
This line is your problem add_action( 'widgets_init', 'ohsik_widgets_init', 12); You are deregistering your sidebar correctly. For some reason you are registering it, or something. I don't see the need or use for this. The other possibility that I'm thinking of for using this code is that somewhere you are registering your own custom sidebars. If that is the case, you are most probably reusing the ID of the sidebar you have deregistered. Try changing the ID to 12 of your new sidebar. You can not reuse ID's. All ID's needs to be unique
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, sidebar, child theme" }
Which hook if user profile information is updated? I'm looking for the hook that fires when a user's information are updated. Specifically, I want to update a post with the value of a custom profile field (in my example `info`) everytime that user's profile is updated. I tried the `profile_update` hook, but it doesn't seem to fire: add_action( 'profile_update', 'add_info_to_post' ); function add_info_to_post( $user_id ) { $info=get_user_meta($user_id,'info',true); //get all items of that user $args=array( 'author' => $user_id, 'post_type' => 'item', ); $items=get_posts($args); foreach ($items as $item){ update_post_meta($item->ID,'user_info',$info); } } Any suggestions how to make this work? EDIT: Maybe I should mention that I access the users' profile pages through the backend..
From Codex: Plugin API - Action Reference - profile_update: > **Note:** This hook is not used on user edit/profile pages. To hook into the admin's user edit pages, use the hook edit_user_profile_update which is located in `/wp-includes/user-edit.php` instead. From Codex: Plugin API - Action Reference - edit_user_profile_update: > This hook only triggers when a user is viewing another user's profile page (not their own). If you want to apply your hook to ALL profile pages (including the current user) then you also need to use the personal_options_update hook.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 7, "tags": "hooks, profiles" }
Show One Category on Post How do i go about making the code only show one category? <?php $categories = get_the_category(); foreach($categories as $key => $category) { $url = get_term_link((int)$category->term_id,'category'); $categories[$key] = "<dt><h1>{$category->name}</h1> </dt>" . "<dd>{$category->category_description}</dd>"; } echo "<dl>\n" . implode("\n",$categories) . "\n</dl>"; ?> The Reason why am asking is that I have two category(s) on some of the posts but i only want to show one of them. Is there way to add it to the code above so it only shows one thanks.
Thank you for your question. Try using the following code. <?php $categories = get_the_category(); if($categories[0]) { $url = get_term_link((int)$categories[0]->term_id,'category'); $temp = "<dt><h1>{$categories[0]->name}</h1> </dt><dd>{$categories[0]->category_description}</dd>"; echo "<dl>\n" . $temp . "\n</dl>"; } ?> Best Regards, Vinod Dalvi
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, categories, customization" }
How to tell which Plugin is displaying? I'm editing a Wordpress website for a client that was written by someone else. I'm noticing that a video and button are displayed on the home page. I used the Reveal-Template plugin to figure out which template was displaying but I can't seem to figure out which plugin is being used to display the video and button. I'm sure it's a plugin too because I changed the video yesterday. The problem I'm trying to fix is that I want to put a link on the button but currently, it only gets set by a drop down menu. This means I'll need to go and edit the plugin being used to allow for a URL instead of just internal pages. If I could figure out which plugin it is, I would go edit that code. Does anyone have a good way of figuring this out? I'm very new to Wordpress development so I apologize if this is a really basic question. Thanks in advance for your help!
It can be less than trivial to match output to a source code responsible in WordPress. The typical cases are following: 1. The output is produced by template file directly. The locating template responsible is often about just searching for full or partial text match. From the other side template files can be identified among all files being loaded. 2. Output is produced by function call in template file. This is not far from previous case, but can be slightly trickier since code definitions is now in separate place from code execution. 3. Output is produced by function call, hooked to an action/filter. This can be nightmarish to unwrap, especially in cases of things getting nested. In a nutshell good search tool is always a solid start. After that it's matter of what you typically work with and what tools are fitting for that. Personally I find `Query Monitor` plugin striking good balance in providing debug information but not _too much_ information.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, pages" }
Is it possible to make one of two custom fields in Custom Post Type UI Required but not the other? I'm new to wordpress and I'm trying to make a field that either links to a page internally via a dropdown OR a text area for a URL. Obviously I don't want the button to have two destinations so I'd like to make them both required but only one can have a value at a given time. Is this possible in CPT UI?
You should use Advanced Custom Fields. If I understand what you want to do correctly, you can add a Select Field with Radio Buttons, and then build conditional Page Link and Text (for the URL) Fields that appear based on the Select Field button. You would then build an if/else statement in the code: <?php if(get_field('page_link') == "internal"): ?> <a href="<?php the_field('internal_page_link'); ?>">Page Link</a> <?php else: ?> <a href="<?php get_field('external_page_link'); ?>">Page Link</a> <?php endif; ?> You can set the two options up to be conditional based on the selected button from select field. Also note in this example, you should use `get_field` for the Text field. This will return it as a string and not output text to html.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, pages" }
Specify parent page template I don't want to define a template from admin because I have lot of page and so if I change it I might forget my selected template. So I want make that template in page. Here is my page structure > Mango (page) > > -Orange (parent page) > > \-- lime (parent page) For my mango and all parent pages I will use the same template, but I don't want to that by selecting one for each from admin. I want that defined in functions.php or page.php with `get_template_part` or any other way. For example, if lime/mango/orange or whatever which is under `mango` page, then `get_template_part` will use `mango` so that my template will be mango.php. Any suggestions to make this work? i am not sure is that make scene or not
All types of templates have filters to let you control what template is loaded. For pages there's `page_template`, where you can check the queried page against an ID, or see if the ID exists in an array of a page's ancestor IDs. function wpd_page_template_filter( $template ){ // the ID of Mango page $parent_page = 20; if( $parent_page == get_queried_object_id() || in_array( $parent_page, get_ancestors( get_queried_object_id(), 'page' ) ) ){ $template = locate_template( 'mango.php', false ); } return $template; } add_filter( 'page_template', 'wpd_page_template_filter' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, page template" }
How can I determine what mode the editor is in and when it changes? I need to determine if the page/post editor is in Visual or Text mode. I also need to determine when this changes. Does WordPress provide some kind of functionality for doing this? I am writing some JS that requires this information.
1. To determine what mode the editor is currently in, you can use the `getUserSetting('editor')` in JavaScript, which returns either "html" or "tinymce". 2. To determine when the editor mode is switched, you can use the jQuery `click` event handler on the `#content-tmce` and `#content-html` elements, which are the editor type switching buttons: jQuery( '#content-tmce' ).click( function() { // Visual editor selected } ); jQuery( '#content-html' ).click( function() { // Text editor selected } ); Bear in mind that these click events will always be triggered when you click on the buttons; when you click on the "Visual" button for example, the event will be triggered regardless whether the current mode is "Visual" or "Text". If you need to, you could easily tackle that by storing the previous state yourself.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "visual editor" }
Shared upload folder in wordpress multisite I have a wordpress multisite, where I would like all the images uploaded through the main site (mysite.com) to be accessible to `sub1.mysite.com` and `sub2.mysite.com`. All the images should be in one folder without subdirectory (e.g: `wp-content/uploads/image.jpg`). I tried the bellow function, but my images for subdomains are uploaded to `wp-content/uploads/sites/#blog_id/` function wpse_16722_upload_dir( $args ) { $newdir = '/'; $args['path'] = str_replace( $args['subdir'], '', $args['path'] ); //remove default subdir $args['url'] = str_replace( $args['subdir'], '', $args['url'] ); $args['subdir'] = $newdir; $args['path'] .= $newdir; $args['url'] .= $newdir; return $args; } add_filter( 'upload_dir', 'wpse_16722_upload_dir' );
This will force uploads for all sites to the `wp-content/uploads` directory. Sub-directories (like `year/month`) will still exist (if the setting is enabled). /** * Force all network uploads to reside in "wp-content/uploads", and by-pass * "files" URL rewrite for site-specific directories. * * @link * * @param array $dirs * @return array */ function wpse_147750_upload_dir( $dirs ) { $dirs['baseurl'] = network_site_url( '/wp-content/uploads' ); $dirs['basedir'] = ABSPATH . 'wp-content/uploads'; $dirs['path'] = $dirs['basedir'] . $dirs['subdir']; $dirs['url'] = $dirs['baseurl'] . $dirs['subdir']; return $dirs; } add_filter( 'upload_dir', 'wpse_147750_upload_dir' );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "multisite, uploads" }
Open Admin bar "Visit site" in a new window Is it possible to create a filter to make in sort that the link in the admin bar to open in a new window. I know that the right-click -> open in a new tab is a common use for us programmers but for the client who use it, it could be great to open in a new tab. !enter image description here Hope to find a solution without changing the core file "admin-bar.php" so it won't get overwrite on any WP's updates.
This is actually easily done. I just adapted the code from this answer add_action( 'admin_bar_menu', 'customize_my_wp_admin_bar', 80 ); function customize_my_wp_admin_bar( $wp_admin_bar ) { //Get a reference to the view-site node to modify. $node = $wp_admin_bar->get_node('view-site'); //Change target $node->meta['target'] = '_blank'; //Update Node. $wp_admin_bar->add_node($node); } To change any other item in the menu bar you just need to find the id of the item to change and adapt `get_node`. Look in `/wp-includes/admin-bar.php` for the id or have a look at the css classes of the output.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "admin bar" }
Hide meta box for everything BUT a certain custom post type I need to retain tag taxonomy for a single custom post type, but am struggling with it. Is there a way to remove this meta box for everything BUT? * * * `remove_meta_box('tagsdiv-post_tag', 'post', 'normal');` Will remove the tags from normal posts (desired), but it means they're also removed from ALL custom post types. I can remove the meta box for individual custom post types, like so: `remove_meta_box('tagsdiv-post_tag', 'cars', 'normal');` `remove_meta_box('tagsdiv-post_tag', 'hotels', 'normal');` etc. But that means I have to leave tags available on normal posts (undesired). So I guess I want something like this, to remove the meta box from everything apart from (e.g.) `airports`: `remove_meta_box('tagsdiv-post_tag', '!airports', 'normal');` Any ideas?
Why not just turn off the default tags capability then register a tags taxonomy specific to the custom post type? < register_taxonomy( 'my_custom_post_type_tags', 'my_custom_post_type', array( 'label' => __( 'Tags' ), 'rewrite' => false, 'hierarchical' => false, 'capabilities' => array( 'edit_terms' => 'manage_categories' ) ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, taxonomy" }
How to assign permissions for a CPT to a user I have a list of CPT's called resources. I want each resource to be assignable to any number of users. The assignment would preferably occur by an admin, logging in, nav'ing to that users email, and seeing a checkbox list of all available resources, they could then check a box next to resource A, and then the user has access to resource A. There will be like 150 resources so its not a short list. Any ideas?
This is something you can achieve with the Advanced Custom Fields plugin. The trick is to use the `ACF_LITE` mode, which would let you define a dynamic list of user profile fields from `functions.php`. You could iterate over each post type and display a checkbox for it. Then use the `edit_user_profile_update` hook to call `$user->add_cap('edit_[resource]')` or `$user->remove_cap('edit_[resource]')`, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, users" }
How can I hide my section title if there is no data in custom fields? I wrote this function with a foreach and I'm not able to figure out how to hide the section title if there are no custom fields in $lista. Where should I place the section title? function opening_hours_custom_fields() { /*Define custom fields in this case with Genesis*/ $lista = genesis_get_custom_field('_happy_day', $post->ID); /*Section title */ echo '<h3>Happy Day</h3>'; /* the rule to display items in foreach loop */ if( $lista ) { foreach( $lista as $key => $value ){ /* if value is nothing the display none */ if( $value != '') { echo "<li> $value </li>"; } } echo '</div>'; } }
I would first loop over `$lista` and generate a new array of data that only has non-empty values. Now you can check `$values` to ensure there is data and output your title: function opening_hours_custom_fields() { global $post; if ( $lista = genesis_get_custom_field( '_happy_day', $post->ID ) ) { $values = array(); foreach ( $lista as $value ) { if ( $value != '' ) $values[] = $value; } if ( $values ) { echo '<h3>Happy Day</h3>'; echo '<ul>'; foreach ( $values as $value ) echo "<li>$value</li>"; echo '</ul>'; } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, php, genesis theme framework" }
Getting two versions of CSS I was using `WP Super Cache` plugin to apply `style.css` file changes that I am doing all the time. But I found the following code which working much better: <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="all" /> The problem now that server having two CSS files named like that: `style.css?1402153121` which belong to code I have added, and another file named `style.css?ver=3.9.1` which has very old changes. I don't know if it a plugin issue or what! I have already deactivated the `WP Super Cache` plugin, but the file still existed. I am also using `cloudflare` plugin, I deactivated but nothing happened. So how to get rid of that file `style.css?ver=3.9.1`?
You should search your theme files for calls to `wp_enqueue_style()`, I bet that is what's adding an extra link to `style.css`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "server load" }
How do I grab specific posts (by post id) and display the title, featured image, and excerpt? I'm trying to help a friend get his site in order and he wants me to swap out the "services" posts on the front page with 4 specific posts. Thing is, I don't know the right way to do this dynamically. How do I call up the content of just the post id, the featured-image (with the right dimensions) and a short excerpt from the beginning of the post? Any suggestions would be greatly appreciated; thanks.
I have not tested this but based on your question, this should get you on track: <?php $id = 4; // The Page or post ID $page_data = get_post( $id ); $title = $page_data->post_title; $content = $page_data->post_content; $excerpt = substr($content, 0, 155); $featured_image = wp_get_attachment_url( get_post_thumbnail_id($id, 'thumbnail') ); ?> <div class="post"> <h1><?php echo $title; ?></h1> <div class="featured"><img src="<?php echo $featured_image; ?>" /></div> <p class="excerpt"><strong><?php echo $excerpt; ?></strong></p> <p class="content"><?php echo $content; ?></p> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "hooks, content" }
How To Rewrite WordPress Pages URL Only? I have my WordPress pages URL as `www.example.com/WP/sample-page` and I want to make it like `www.example.com/WP/p/sample-page.html` For this purpose I used a Plugin name " **Pages with extension** " and it worked but it only add .html in the end of my pages URL. I also want to add `/p/` before my pages URL so that it will become as I mentioned above. I dont want to use any extention for this purpose, Can `.htaccess` file do it? If yes then how?
As I shared above that I got `.html` in page by a Plugin. The rest of the problem is to add `/p/` before page name that I got also as **TheDeadMedic** mentioned above. I just created a page with URL `www.example.com/WP/p.html` and then created another desired page with URL `www.example.com/WP/sample-page.html` but add the second page as the child of first `www.example.com/WP/p.html` page. Then I open my desired page then I got the URL as I want `www.example.com/WP/p/sample-page.html` and I got my problem solved. Get All Steps In Pic By **wikiHow** at: How to Add a Subpage in Wordpress
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, url rewriting, urls, htaccess" }
How do I add a add_rewrite_rule without it redirecting? I have a custom post type called "locations". I have a location called "starbucks". I can view this by going to "/location/starbucks". I would like to add "coffee-shop" to the URL, so the path "/location/coffee-shop/starbucks" will load the "starbucks" page, while maintaining the URL in the browser. i have added this code to my functions.php function add_rewrite_rules() { add_rewrite_rule('^location/([^/]*)/([^/]*)/?','index.php?pagename=$matches[2]','top'); } add_action('init', 'add_rewrite_rules'); Which correctly loads the "starbucks" page, but it changes the URL to "/location/starbucks". How can I load the "starbucks" page, and keep my custom URL?
In your rewrite rule, `pagename` should in fact be the `query_var` of your custom post type. Unless you used `query_var => 'something_else'` in your `register_post_type` arguments, it'll be the same name as your custom post type: index.php?locations=$matches[2]
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "url rewriting, redirect, rewrite rules" }
SQL - Remove All The Users and Create A New User With Admin Role Via PhpMyAdmin It is very easy to remove all the users and add a new user with administrative role via wp admin panel. But the requirement is to achieve this through SQL. I can trunc `wp_users` and `wp_usermeta` table to remove all the users. But when I add an entry in `wp_users` with dummy data and then login through wp admin then it says incorrect login. Why? I shall be very thankful to you if you can tell me the proper way of removing all the users and adding a user with admin role.
You can edit and run the below SQL query in your database. Make sure there are no users with the existing ID you specify. If there are change all instances in all 3 tables, currently set to **4** to another number that does not yet exist. INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Matt Royal', '[email protected]', ' '2014-06-09 00:00:00', '', '0', 'Matt Royal'); INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}'); INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login, sql" }
De-registering a CSS file leaves it in the queue I'm trying to de-register a CSS file that it is systematically add from a plugin. The CSS file it is useless in all pages. So I have added a simple `wp_deregister_style` passing the name of the CSS class used for the registration purpose. As a matter of fact, the CSS file is no longer print, but looking at the `$wp_styles` variable I can still see the "item" in the queue array. Any idea on how to remove it?
To properly and completely remove a style, you need to deregister(`wp_deregister_style()`) and dequeue(`wp_dequeue_style()`) it. Dequeueing will remove the style from the array in the `$wp_styles` variable, deregistering the style will remove the stylesheet from being printed add_action( 'wp_enqueue_scripts', 'my_deregister_styles', 100 ); function my_deregister_styles() { wp_dequeue_style( 'genericons' ); wp_deregister_style( 'genericons' ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "css" }
Can I edit the database to change a login? I have WP installed on a server with a couple of other things. Naturally, phpMyAdmin is installed so I can edit my databases easily. Anyway, is it possible to, using phpMyAdmin to edit a row and change the username? AFAIK everything is based off an ID, so why does this matter that you can't change it? Will it bork anything if I change it?
Yes, you can edit this without anything breaking. There is nowhere in the dashboard to edit your username later so for many users who don't know or don't have access to the database this wont be possible for them, hence the warning when installing WordPress. For those comfortable working in MySQL, it will be under the wp_users table in your database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, login" }
Post of a specific category - not to be seen in paging previous/next post i have a specific post category, eg. id=x which is not shown in category list. These posts are password protected and should be visible only to those provided with the link. However current version still allows see posts from all categories using prev/next posts. What is the easiest way to ommit some of these category id=x from paging?
You should be able to exclude the category you don't want to show by adding $excluded_terms to your navigation links. So for example, if the category you don't want showing up is id 4 your link would look like: <?php next_post_link( '%link', 'Next Post', false, '4' );?> Same with `previous_post_link()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, pagination, categories" }
Add a static page that links to homepage My home page is a dynamic page and on my navbar I have different static pages I want to add one to link to the homepage as if I clicked the logo.
To add a link to the homepage in your navbar, you can use the following function to add a link to the home page in `wp_page_menu_args` function wpse01_home_link( $args ) { if ( 'main-menu' === $args -> theme_location){ if (! isset( $args['show_home'] ) ) $args['show_home'] = _x( 'Home', 'homepage' ); } return $args; } add_filter( 'wp_page_menu_args', 'wpse01_home_link' ); You can just rename `Home` to suite your needs
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, homepage, customization" }
Show category with link I am trying to show the category of posts with link to its page, so I used this code but I don't know What's wrong with it. It is only showing the category without link. <p class="subjectCat"><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; echo $category_link = get_category_link( $category_id ); } ?></a></p>
**EDIT** You should look at `get_the_category`. You are probably looking for something like this as from the codex <?php $categories = get_the_category(); $separator = ' '; $output = ''; if($categories){ foreach($categories as $category) { $output .= '<a href="'.get_category_link( $category ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator; } echo trim($output, $separator); } ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "categories" }
featured content: which area does this cover new to wp just wonder how to get content into the center of the theme note ive installed wp 3.9.1 choosed the theme 2014 with child-theme and run the plugin fourteen colors what makes me wonder : how can i get content to the center . i have the * Primary sidebar and * content-sidebar for the left and the right side-block question: what / which area is covered by the "featured-content"!?
Be default, the Twenty Fourteen theme's Featured Content looks for posts that are tagged with "featured". You can modify this behavior easily in the theme customizations menu at `.../wp-admin/customize.php`. This can be customized much further inside your child theme with a modified query, customized HTML or any other edit you'd like to make in the child theme templates.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, themes" }
wp_insert_post removes information when updating I'm using a front-end form and `wp_insert_post` to update posts from the front-end of a website - in order to do this I am using: 'ID' => get_the_ID(), to make sure it is updating the current post (the form appears on the posts page). I am using the below to edit the post content: 'post_content' => $_POST['postContent'], (this takes the result from a submitted form). However, on save the information is submitted in to the post but all other post data seems to be reset such as the title and post password. Is there any way to stop this happening? it seems like some very odd default functionality.
You are using the wrong function. `wp_insert_post()` is for creating posts. You need `wp_update_post()` if you want to update existing data.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp insert post" }
Uses Cases for the Calendar Widget So I've looked at several themes and visited several theme dev sites and i'm confused about the "purpose" of the WordPress Calendar Widget. So it states it is... > A calendar of your site’s Posts But really? Is that all it is used for? Surely there are more creative uses for this widget. Is anyone using it in any creative way? **Edit** The Question is - how you would modify the calendar widget to extend its functionality for custom purposes.
As it sits, the calendar widget pretty much does just what you've said—allows people to troll the archives. Of course, it can be modified for different uses. One site I worked on used the Future plugin to convert the WordPress calendar widget into a calendar of events by creating a post for each event whose "date published" field was set to the date the event had happened in the past or would happen in the future.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets" }
I can't change the background color of a specific page I'm trying with no luck to change the background color of just one page. I've tried adding > and then using the selector body.page-id-15 #content { background-color:#000000; } This doesn't work. Seems the only way I can change the background to that page is changing the background of #content. But...that changes all pages. I know this is possible and I've done it before. But not with this theme Any ideas? The link the page in question is here < Thanks
Looking at your pages source, it does not have post/page ID's being added to the page's body class so you referencing something in your CSS that doesn't exist. Try this rather (not sure what section you want changed): body.blog { background-color: red; } or body.blog #content { background-color: red; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
store custom WP table names in a global variable I was being creative and put this in one of the files loaded with my plugin. Are there implications with storing the table names this way? global $wpdb; if(!defined('DB_ARTISTS')) define('DB_ARTISTS', $wpdb->prefix . "artists"); if(!defined('DB_RELEASES')) define('DB_RELEASES', $wpdb->prefix . "releases"); EDIT: I had originally not included all of the information I had meant to. Tables and variables are prefixed with ABC ( `ABC_DB_ARTISTS` & `$wpdb->prefix . 'abc_artists'` ).
The `DB_` constant prefix in WordPress is generally considered reserved for `DB_NAME`, `DB_HOST`, `DB_USER` and `DB_PASS`. Using it for plugin-specific constants is, in my opinion, not a great idea. The only implication it might pose is if other plugins try to use the constants, but that's purely theoretical. The proper way to do this is to store the table names in the WPDB object stored in the global `$wpdb`. global $wpdb; if ( ! isset( $wpdb->myplugin_artists ) && ! isset( $wpdb->myplugin_releases ) ) { $wpdb->myplugin_artists = $wpdb->prefix . 'myplugin_artists'; $wpdb->myplugin_releases = $wpdb->prefix . 'myplugin_releases'; } It's important to use a proper prefix (in this case `myplugin_` for your plugin). For example, for Advanced Custom Fields, this is usually `acf_` (more on prefixing).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wpdb, globals" }
Only show content before more tag I am using the Siren Template. In homepage.php this code is used to display the portfolio content print_excerpt(200); But I to need show the content only before `<!--more-->` I have used this: the_content( $more_link_text, FALSE); but it is not working. It shows all the content
You can use the WordPress function `get_extended` to fetch the different parts of a string (the part before and the part after the `<!--more-->` tag). `get_extended` returns an array with three keys, of which the keys `main` and `extended` are important: `$arr['main']` contains the part before the more tag, and `$arr['extended']` the part after the more tag. This would yield something like: // Fetch post content $content = get_post_field( 'post_content', get_the_ID() ); // Get content parts $content_parts = get_extended( $content ); // Output part before <!--more--> tag echo $content_parts['main'];
stackexchange-wordpress
{ "answer_score": 26, "question_score": 10, "tags": "the content, read more" }
Alphabetize all but one category I have my categories set to sort alphabetically: <?php if (is_category()) { $posts = query_posts($query_string . '&orderby=title&order=asc'); } ?> I want to exclude one category so that it sorts by date. I tried this but it made all the cats come up blank: <?php if (is_category()) { $posts = query_posts($query_string . '&orderby=title&order=asc&exclude=15'); } ?> Any ideas?
Add an else to the condition along with adding the excluded category id in the `is_category()` call. You will also need to include/exclude that particular category depending on the condition that is true: NOTE: you probably want to avoid using `query_posts` and use `WP_Query()` Reference here <?php if (is_category(15)) { $posts = query_posts($query_string . '&orderby=date&order=asc&cat=15'); } else { if(is_category()) { $posts = query_posts($query_string . '&orderby=title&order=asc&cat=-15'); } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Hide the post count behind Post Views (Remove All, Published and Trashed) in Custom Post Type I need to hide/remove the numbers behind the Edit screen in the backend. All (30) | Published (22) | Draft (5) | Pending (2) | Trash (1) As I am running a multi author blog and each author has just access to its own posts, I dont want to publish the cumulated information of all authors. With the following code the views are completely unset, but I dont want to remove the whole functionality: function remove__views( $views ) { unset($views['all']); unset($views['publish']); unset($views['trash']); return $views; } add_action( 'views_edit-post', 'remove_views' ); add_action( 'views_edit-movie', 'remove_views' ); Has anybody an idea, how I can either hide/remove the numbers behind the edit screen or - at best - to show only the numbers related to each author?
There is, unfortunately, no "pretty" way to do this (i.e. without using string replacing or rewriting a big chunck of functionality). So, resorting to `preg_replace`... We'll need to filter the links, and it's good to see that you've already found the proper filters! Looping through the views and using a regular expression, we can remove the element containing the post count. Implementing this for posts, you'll need something like this: add_filter( 'views_edit-post', 'wpse149143_edit_posts_views' ); function wpse149143_edit_posts_views( $views ) { foreach ( $views as $index => $view ) { $views[ $index ] = preg_replace( '/ <span class="count">\([0-9]+\)<\/span>/', '', $view ); } return $views; }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "count, views" }
Show category post with excerpt text I want to show a post with post title and post content of 400/550 words with a read more link in my category page. I have already done this, but problem is, my post doesn't display the excerpt as it should. This in my code below. <?php while ( have_posts() ) : the_post(); ?> <div class="news"> <div class="grid-container"> <h2><a href="<?php the_permalink(); ?>" > <?php the_title(); ?> </a><span class="line"></span></h2> <?php the_post_thumbnail() ?> </a> <div class="newsevent"><?php echo substr(get_the_excerpt(), 0,400); ?></div> <a href="<?php the_permalink(); ?>" class="readmore">View</a> </div> <?php endwhile; ?> I suspect I need to change `<?php echo substr(get_the_excerpt(), 0,400); ?>`
1) Follow this post on Stackoverflow or the link given by @PieterGoosen. 2) You can also use `get_the_content()` instead of `get_the_excerpt()`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, excerpt" }
Why use wp_send_json() over echo json_encode()? When sending a JSON response back to an AJAX request, why use the WordPress function `wp_send_json()` and not `echo json_encode()`? What is the benefit of using the WordPress function `wp_send_json()` over `echo json_encode()`? Ref: `wp_send_json`
`wp_send_json()` handles all parts of returning content in an AJAX call. First off, it sets the content type of the returned content to `application/json` with the proper charset. Secondly, it automatically calls `wp_die()` after sending the JSON result, which is necessary in an AJAX call in WordPress. You could consider using `wp_send_json_success()` for successful requests and `wp_send_json_error()` for erroneous requests, thereby adhering to the WordPress standards for handling AJAX requests. These functions set a `success` (boolean) and `data` (any type) key in an array and encode that entire array, thereby allowing you easily check in a structured way whether the request was successful or whether something went wrong.
stackexchange-wordpress
{ "answer_score": 26, "question_score": 14, "tags": "ajax, json" }
Subdomain redirects to subdirectory Supposing I have folder called "support" inside root folder "/public_html". I've added a subdomain in my server's panel so that when going to "support.mydomain.com" it redirects to "mydomain.com/support" The problem is that redirection is reflected on the browser's address bar, and I want to make that subdomain work like "base domain". i.e "support.mydomain.com/folder-inside-support" Is it something to be with .htaccess file?
RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^(www\.)?example\.com RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ([a-z0-9-]+)/? [R=301,NC,L] Replace both instances of "example.com" with your domain name. Taken from: htaccess Subdomain Redirect
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "directory, subdomains" }
Redirect to Current Page after Login In my wordpress page, I add Login- logout item to the main menu using the code (in functions.php) below : add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2); function add_login_logout_link($items, $args) { ob_start(); wp_loginout('index.php'); $loginoutlink = ob_get_contents(); ob_end_clean(); $items .= '<li>'. $loginoutlink .'</li>'; return $items; } When login is performed using this button, It should redirect the current page where login is clicked. How can I do that? I think `wp_loginout('index.php')` needs to change because after login and logout I redirect to home page. What should I write to go previous page ?
`wp_loginout` accepts two arguments, `$redirect` (string) and `$echo` (boolean). You can specify the URL of the page to redirect to after logging in or out with the `$redirect` parameter. In your current code, `$redirect` is 'index.php'. You can get the full URL of the current page by using ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] yielding wp_loginout( ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); That should do the trick!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "redirect, login" }
Markdown everywhere? I just read this blog post which explains that Markdown support has been added to all Wordpress.com blogs as a feature. I administer my own WordPress installation and am currently running (as far as I know) the latest version of WordPress, 3.8.X, I believe. Is Markdown support built into WordPress standalone? I'm in the midst of migration so it's not so easy to check. Will I be able to write, edit, and allow my users to comment using Markdown fairly seamlessly? Being able to compose posts in Markdown will greatly encourage me to start writing more :)
No, and I'm not aware of any plans to introduce it into WordPress core. That functionality has been added by WordPress.com. There are numerous plug-ins which add this feature, to name but a few: * WP Markdown (I authored this) * Markdown on Save * JetPack
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "markdown" }
How to create .pot files with POedit? I've spent hours today on what seemed like something really simple, which is to create a .pot file for a Wordpress theme that I'm creating. I've read the Smashing Magazine article, the Tutsplus article and few others on how to use Poedit to create .pot files for a theme, and then create .mo and .po files, but sadly, I'm still stuck at the first step. I installed Poedit and I find that the UI is completely different than that is shown in all of the the tutorials and it seems like there is no more an option to create .pot file. Only thing that is available is to create .po and .mo files from an existing .pot file, which is not what I need now. So can someone please tell me how can I create .pot files using Poedit or with some other method, I would really appreciate it. Thanks!
You may try Eazy Po. * From file menu select “New from source code files..”. * In xgettext Command Manager window; Press “Browse folder” to select base source folder. * In Build pane press “Execute Command” button to generate Pot file.
stackexchange-wordpress
{ "answer_score": 20, "question_score": 50, "tags": "theme development, translation, localization" }
Is it wrong to use the English version of WordPress to server a site in a different language? I'm building an online store for an Indonesian market, so the front-end must be in Bahasa Indonesian. Will using the English version of WP, and a theme in English without .po files, introduce complications/errors/bad experience if the content is in Bahasa Indonesia? Ie. Incorrect language attributes. Or is it ok to use the English version of WP and fill it with content written in Bahasa Indonesia?
There is no technical problem in doing so, and there won't be any complications or errors. However, it could be that not all content on the site will be in Indonesian. Some strings in themes and in other places in the front-end are outputted by WordPress, and as all strings are in English in WordPress by default, some content on your website might be in English. Thus, if you don't rely on localization anywhere, there shouldn't be a bad user experience either. A better solution, however, might be to change the locale depending on whether the page being served is front-end or back-end: Different Language for Frontend and Backend.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "localization, language" }
URLs unchanged after migration I have my company's blog at < and now I've moved it to < but I have the URLs still pointing to the former address. I used the commonly recommended search and replace plugin to change the URLs in the backend. I also fired the following queries in phpmyadmin without any success. UPDATE wp_options SET option_value = replace(option_value, 'OLDURL', 'NEWURL') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'OLDURL','NEWURL'); UPDATE wp_posts SET post_content = replace(post_content, 'OLDURL', 'NEWURL'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'OLDURL','NEWURL'); What am I doing wrong here? This is the tried and tested technique I've used to migrate a lot many other sites prior to this.
The previous developer had hard coded update_option('siteurl',' update_option('home',' in functions.php which on being removed resolved the issue. Thanks everyone for churning in your suggestions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, migration" }
WP query exclude post within the last month / only show over 1 month old I need to create a landing page which only shows posts that are at least a month old. Everything I've read / tried with the date query so far seems aimed at including posts between the last month and now rather than excluding.. effectively I'm looking to exclude posts between todays date and today-1month. Any pointers appreciated.
The date query for `WP_Query` supports several options, including `before` and `after`. Using just `before`, you can fetch posts from _before_ a certain date (excluding posts from that date on): $args = array( 'date_query' => array( array( 'column' => 'post_date_gmt', 'before' => '1 month ago' ) ), 'posts_per_page' => -1, ); Furthermore, you can specify whether it should be inclusive (date specified is matched as well) or not, using the `inclusive` key, which defaults to `false`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp query, query posts" }
php include returns 1 as output with other outputs I have this code $return = include(TEMPLATEPATH . '/apex.php' ); $html .= $return; I using the above code to get a php for from a plugin from theme dir. but it returns 1 with the other wanted outputs. how to solve this I have seen the other question on stackoverflow but those hasn't work thanks in advance
First of all, this is not WordPress-specific, and does therefore not belong in WordPress.StackExchange. As it's so easy to answer, however... `include` is not a function, but it does return whatever you put in "return" inside the file that's included. You can use an output buffer to "catch" all output: ob_start(); include TEMPLATEPATH . '/apex.php'; $html .= ob_get_clean();
stackexchange-wordpress
{ "answer_score": 1, "question_score": -3, "tags": "plugins, plugin development, include" }
How do I / Is it possible to execute an external PHP file / function inside Wordpress? On my set-up, there is the regular website which consists of a header and content (both printed from separate PHP files located in `domain.com/includes/`) and a Wordpress blog based in a subdirectory (`domain.com/blog/`). I want to include domain.com/includes/header.php on the main Wordpress skin. I have tried `require_once`, `include`, specifying the `ABSPATH` in the `wp-config`, and various other techniques but none of them have worked for me. Printing the header.php contents to Wordpress skin is vital and there is no compromise for it in my workflow. I would greatly appreciate any advice as to how I can get this script working, whether it be through a plugin or some edit to the core files, without having to change the location of `domain.com/includes/header.php`. Thanks in advance.
Using the domain name in the path won't work; you're not trying to specify a URL, but a path to a file, be it relative or not. Using `include(ABSPATH . '../includes/header.php' )` should work. `/includes/header.php` doesn't work because the location of the `blog` folder doesn't is not the root folder (`/`), but most likely a few levels down.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, include" }
ID of Front-Page I like to get the ID of the selected front page. My page uses an Template for that page. I've read about `get_option('page_on_front')`, but this didn't work for me. Is there any function to get this ID?
This should do the trick. global $wp_query; $post = $wp_query->get_queried_object(); $post->ID; This'll give you the ID for each page you're on. `get_option( 'page_on_front' )` should've worked though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "id, frontpage" }
How to make javascript work on theme options page Gentlemen! I'm composing a theme options page for my WP theme. And I bumped into the problem of finding the proper way to introduce inline jQuery interactions to the page. Ideally for me in the situation will be inline jQ code <script type="text/javascript"> $(document).on({ ready: function(){ alert('Hey!'); } }) </script> But this code fails because I guess the admin options page is rendered before the jQuery is included so js generates expected error. The same code with no jQ identifiers works ok means I get alert window when introduce: <script type="text/javascript"> alert('Hey!'); </script> Question is how to properly introduce inline js containing jQ (or any other framework) syntax and make it work?
The problem with your code is, as we found out in the comments on the question, that you're using `$`, which is either undefined or has a conflict (in any case, it's not pointing to `jQuery`). Using `jQuery( document )` instead of `$( document )` should do the trick!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, jquery, theme options" }