INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Children Shortcodes? I started creating WordPress plugins a few weeks ago, and I would like to know if it's possible to somehow "embed" shortcodes in some others. Basically what I want to do is create a table or a list, based on a set of items entered by the user of the plugin. Is it possible to have something like : [data] [item1] something [/item1] [item2] something else[/item2] [item3] something else[/item3] [/data] In short, I want to create something based on the elements contained in the _itemX_ "children" shortcodes. Is there any way to do something like that? Thanks
This is possible, but you can only nest one level down, after that the shortcode regexp parser flips out. So your example would be okay, but [item1] would not be able to contain even more nested shortcodes. To enable nesting, just go ahead and do: add_shortcode('data', function($attributes, $content='') { return do_shortcode($content); } Relevant article: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, shortcode, children" }
Error showing in current page id in wordpress admin I am trying to remove a metabox ID from a page ID in the admin screen. So I have coded the following: function ag_remove_cmb_metaboxes() { global $post; $id = $post->ID; if ($id == 21) { ?> <script type="text/javascript"> jQuery(document).ready(function($){ jQuery('#test_metabox_img') .hide(); }); </script> <?php } } add_action( 'admin_head', 'ag_remove_cmb_metaboxes' ); It is working fine but an error is showing in the widget.php page. Error code is: > Notice: Trying to get property of non-object in E:\xampp\htdocs\speechcare\wp-content\themes\cutedoctor\core\helpers.php on line 56 Can anyone please explain why this error is showing and what I am doing wrong? Thanks in advance.
While front–end of the site always has a post context (you are either looking at one or archive of posts), admin side doesn't. So plenty of admin screens won't have `$post` global set to anything. You should be checking if it's meaningful (for example by `if ( ! empty( $post ) )`) before trying to access it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "metabox, wp admin" }
Wordpress search issue with searching html tags I am working on a wordpress site and I am using wordpress native search. When we search for a string like "example" it searches inside html tags. ie if there is any html tag like `<a href=" in the page or post then the search result will show that particular page or post. I dont want to search inside html tags. I already tried using the plugin Search Exclude HTML Tags But it uses MySql stored function which is not working for me. I think it may be issue with the permission of my mysql user. Is there any alternate way to fix this. Thanks Pramod
I created a tiny plugin for this :) and fixed the issue. < Just one or 2 lines of code. Worked in most cases.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "search" }
User gets access denied to css files and js files even though user is logged in We are using wordpress as a intranet, we have the AD Integration plugin. Everything is working fine except for one user. Now there is no difference in settings on his machine or user profile or AD profile to any other user. But for some reason when he logs in he gets access denied to all the CSS files and JS files. I know he has logged in successfully because I use console.log to display the username when logged in as well as other details such as full name and job title. The details are retrieved from the wordpress function for current_user so I know he is logged in. Has anyone else had issues with style sheets etc being denied even though the user is logged in?!
In most typical WordPress configurations the load of CSS/JS assets is _not_ actually processed by WordPress core. Otherwise the performance would be _horrible_. Web servers do fantastic work at serving static files like that though, so WP's configuration (`.htaccess` or other, depending on server) just passes all such files to them. It's not clear from your description: * if that user can access files when _not_ logged in * if _specific_ files cannot be accessed or definitely _all_ files WP admin uses PHP for concatenation of assets, which does tend to cause issues now then. You can try setting `SCRIPT_DEBUG` constant to `true` in configuration to disable it (as well as minified versions) and see if that makes a difference. But for completely static assets this is unlikely to be caused by WordPress core in general. Check server logs for clues, especially if you are running security and/or firewall modules on it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, user access" }
How to use PHP code with wordpress page new user to WP. I am dynamically creating HTML tables with SQL data in my PHP. WordPress pages do not allow PHP code, and I've been hounded by individuals not to use a PHP plugin due to security reasons. Now if i just needed to run a PHP file i would simply include it inside of my custom page-template. Since the code needs to be displayed inside the "content container" (which is dynamically loaded) I don't fully understand where to place my code. <?php get_template_part( 'content', 'page' ); ?> I've noticed this code above is calling the content container for that page. Should i be loading a different page here? or should i be directly modifying the page data inside the DB to reflect my php? will this work? whats the best thing to do in my situation?
The best way to create dynamic data outputs really depends on the what, why, and how. For example, if you're creating a theme that creates its own custom post type, say, to store information about the head honchos that run the business behind the site, then just create a "single-$CPTNAME.php" template that has the code that you want. Another method of doing this would be to create a custom template, and simply select that for a given page. See the WordPress Page Templates documentation for more information on how to create the custom templates and make them selectable in the WordPress admin UI.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, customization, pages" }
How to overwrite orderby with add_query_var So I would like to have an archive that displays its posts in a random order. <?php $query = new WP_Query($query_string."&orderby=rand"); ?> But also then if the user chooses they can order the posts differently by clicking a button. <?php $sort_date = add_query_arg(array('orderby'=>'date','order'=>'asc')); $sort_name = add_query_arg(array('orderby'=>'title','order'=>'asc')); ?> <div class="sort"> Sort by: <a href="<?php echo $sort_date; ?>">Date Listed</a> | <a href="<?php echo $sort_name; ?>">Name</a> </div> These 2 things work separately but when I try and use them together the archive just keeps display the posts randomly. How can I get these 2 to work together?
So I finally figured it out. Using `pre_get_posts` and the `$_GET` global var to check if any query args have been added works a treat. I used the follow code to get the desired results. function my_pre_get_posts($query) { if( $query->is_main_query() && is_archive() && !isset($_GET['orderby']) && // checks for query args !is_admin() ) { $query->set('orderby','rand'); } add_action('pre_get_posts', 'my_pre_get_posts');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query, loop, query" }
How to get only 1 role from user I have this code that will display all the roles for that particular user, but I only need to display 1 role from the user. I have installed bbpress so the code below will display out 2 roles. $user = new WP_User( 1 ); if ( !empty( $user->roles ) && is_array( $user->roles ) ) { foreach ( $user->roles as $role ) echo $role; } Result: Administrator Participant How to display only the first role?
Try this: if ( !empty( $user->roles ) && is_array( $user->roles ) ) { $first_role = array_shift($user->roles); echo $first_role; } Function `array_shift` obtains the first element of the `$user->roles` array.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user roles" }
Display pages in alphabetical order I think I am missing something in my `functions.php` because my pages in the admin are displayed randomly. How can you display the pages in admin alphabetically? Thanks!
Filter `pre_get_posts` is used for modifying the query from theme or plugin. This hook is called after the query variable object is created, but before the actual query is run. Codex documentation of `pre_get_posts` Although this filter is very handy and useful, we need to be very careful using it. We should very careful about targeting the query. This filter is applied for both front end and back end admin panel. WordPress provides several conditional function which can be used to target the specific page. * is_main_query() * is_admin() * is_home() * is_post_type_archive() * and many more See here for more conditional tags Example, if you want to target only home page then you can use like this: function my_custom_function( $query ) { if ( $query->is_home() && $query->is_main_query() && !is_admin() ) { //change query parameter here for home page } } add_action( 'pre_get_posts', 'my_custom_function' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages" }
How to retrieve the date on which a post was moved to trash? I need to retrieve a list of posts that are in trash based on the date on which they were trashed. The following code allows me to retrieve posts that are in trash, but how to filter them by date? $options = array( 'post_status' => 'trash', 'post_type' => 'post', 'nopaging' => TRUE ); $wp_query = new WP_Query(); $posts = $wp_query->query( $options );
When post is trashed, WP creates a meta field named `_wp_trash_meta_time` and it saves trashed time in that field. You can use that field to get trash time. **Edit:** Example: $args = array( 'post_status' => 'trash', 'post_type' => 'post', 'nopaging' => TRUE, 'meta_query' => array( array( 'key' => '_wp_trash_meta_time', 'value' => array( strtotime("last week"), date('U') ), 'compare' => 'BETWEEN', ), ), ); Using this, you can get trashed posts which are trashed in last week.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "wp query, trash" }
Determing number the query ran by core wordpress I wanted to find out, how many queries does wordpress core run, and how many queries the theme run. Is there any way to get they number of both of them separately ? As i run `echo get_num_queries(); queries in timer_stop(1);` It gives me total of queries, but i want to have the number separate, of how many does theme run, and wordpress core alone.
You can use Query Monitor plugin for that Not quite sure if it distinguish between both but it's a great plugin for query monitoring and debugging.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, query" }
woocommerce-how can i get all products by their groups! i have a wordpress site that uses woocommerce as an online shop plugin. what is want is listing all products in my woocommerce site grouped by their categories, how can i do this? i want the list sorted ASC and i want all empty categories hidden! thanks in advanced!
i think this is what you need: $args = array( 'orderby' => 'name', 'hide_empty' => 1 ); $category_terms = get_terms( 'product_cat', $args ); foreach($category_terms as $cat_term){ echo $cat_term->name; } btw: woocommerce is offtopic here!
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "woocommerce offtopic" }
WP Query Exclude and Start by Menu Order Offset I have a set of posts in a custom post type that I have given menu order attributes to. I am hoping to use `wp_query` to query the first 3 by menu order, then the next 3 by menu order. For example - If I have a list of posts given the menu order attribute of 1,2,3 - $args = array( 'post_type' => 'my-post-type', 'posts_per_page' => 3, 'order_by' => 'menu_order', 'order' => 'ASC' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); How can I perform another query like this but start on the 4th post based on its menu order so I get 4,5,6? I figure I can use `post__not_in` and put their specific IDs, but I'd like to keep this dynamic and address the `menu_order` only.
You can use offset to number of post to displace or pass over. Like this. $args = array( 'post_type' => 'my-post-type', 'posts_per_page' => 3, 'order_by' => 'menu_order', 'offset' => '3', 'order' => 'ASC' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query" }
adding image to post thumbnail from another server i have a image gallery site, each post in site have thumbnail and image in post, now i want get _file server_ for uploaded image. how can i add thumb image from another server? or how can i change the destination image uploader to file server? or any other solution. tnx 4 adv.
I was writing a guide but then I found a tutorial for this. Follow this tutorial to setup subdomain for uploaded files. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, uploads, post thumbnails, thumbnails" }
How to set multiple `orderby` in query argument? I am trying to fetch pages by multiple ordering. `menu_order` in descending and `title` in ascending. Following is the argument: $args = array( 'post_type' => 'page', 'posts_per_page' => 20, 'orderby' => array( 'menu_order' => 'DESC', 'title' => 'ASC' ), ); But it is not ordering as I expecting and gives following warning. `Warning: urldecode() expects parameter 1 to be string, array given in /var/www/html/staging.dev/public_html/wp-includes/query.php on line 2634` I found a ticket in trac regarding multiple `orderby`. I studied the discussion and followed as in the discussion but could not solve the issue. Ticket Link
Advanced ordering feature is now added in the new version of WordPress. I came to know this after release of WordPress 4.0. Check this announcement for more detail. **Example:** $q = new WP_Query( array( 'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' ) ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, order, menu order" }
Which Filter Do I Use To Modify The Subject Of The Retrieve Password Notification Email? I am looking for the filter that enables me to modify the subject of the "Retrieve Password" notification Email. If you know which filter to use, please let me know.
I think you're looking for the `retrieve_password_title` filter. For example: add_filter( 'retrieve_password_title', function( $title ) { $title = __( 'WPSE Custom Password Reset' ); return $title; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, email, password" }
options.php problem - data not saved I've created a custom menu page with some fields. I want to store these settings to use elsewhere. The form with the fields should save and POST data using `action="options.php"` but every time I hit save on the form it sends me back to the settings page, and does not save the data. I'm registering the settings in my functions.php function register_settings() { register_setting('settings-group','phonenumber'); register_setting('settings-group','primaryemail'); register_setting('settings-group','secondemail'); } This is the form action <form method="post" action="options.php"> Here is the full code which is in functions.php <
Add <?php settings_fields( 'settings-group' ); ?> <?php do_settings_sections( 'settings-group' ); ?> immediately after the `<form>` tag Your code is registering the settings group, setting up the DB to store the information, but it is/was missing the callback to allow WordPress to actually act on that information or store it. The code I provided tells WordPress what to access, and what to do with the form.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "functions, options" }
How to make this change without changing the core? I couldn't find a way to change this in an upgrade friendly way, and I know I mustn't touch the core! I need to change the value 'number' to 10 in `wp-includes/default-widgets.php` wp_tag_cloud( apply_filters('widget_tag_cloud_args', array('taxonomy' => $current_taxonomy, 'number' => 10) ) ); How can I do this without changing the core?
As you see there is the `apply_filters()` call, with the `$tag` parameter, which is the name of the hook, set to `widget_tag_cloud_args`. As starting point for getting into hooks, filters and actions I'd suggest you read the codex page about the Plugin API. You can use the hook to change the arguments, e.g. like this: add_filter( 'widget_tag_cloud_args', 'wspe160041_change_tag_cloud_number_arg' ); function wspe160041_change_tag_cloud_number_arg( $args ) { $args[ 'number' ] = 10; return $args; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "widgets, core modifications" }
Network - My sites are unavailable I'm asking you your help because I created a network websites : * example.com/site1/ * example.com/site2/ The installation was done and the tab "My Sites" is available with both websites. I applied the same Alpine theme to the websites. However, I don't know if i must to upload some file in the directories /site1 and /site2 to the FTP server. The directories are empty. If i open the url < I got this : !a busy cat On the site1 Dashboard, a page is created and configured to be displayed by default as a static page : !a busy cat Thank you very much for your advices (and sorry for my poor english!). Best regards, Lionel
You have site1 and site2 folders on your server, so Apache is serving those hence the file listing. Multisite however is trying to serve those sites using URL rewriting, so deleting those folders should fix the issue
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
Where is the old post permalink slug stored? I published an article with permalink slug: Then after publishing, I changed the permalink slug to `writing-lorem`. Now, whenever I visit `/writing`, it redirects to `/writing-lorem`. I want to use the `writing` slug for a new category but can't, it changes to `writing-2`. To attempt to remove all records of the `writing` slug, I looked in the DB for the `post_name` column under that post, but the value was the new slug `writing-lorem`. Then I search for other posts with the `writing` value, none found. Where exactly is that slug stored and how can I remove it so that I can use it for the category?
We determined that the slug was not stored in `postmeta` meta_key `_wp_old_slug`. In a final attempt to find where this slug is stored. I performed a search for the exact phrase of `writing` and found a few results. The one of interest was in `wp_terms`. I deleted that entry and then changed the slug of the category to `/writing` and it is working. The strange part was that there were no records within `wp_terms` that connected the post to the slug. Maybe someone is knowledgeable about this table...
stackexchange-wordpress
{ "answer_score": 4, "question_score": 11, "tags": "posts, permalinks, database, slug" }
How to make a cronjob type plugin Hi i am new on wordpress and has been given a task to make such a script that will fetch posts by categories and shoot email to subscribers. The table structure for subscriber is below Subscriber Id - primary key Subscriber email - varchar Category Id - int Now the task is to fetch post for last week for each category that exists in above table an send a newsletter to the respective subscribers each monday automatically. I have an idea how to fetch post i will probably do it with get_post() method but i'm not sure how will i do it. Should i made a plugin? If yes, then can a plugin file be run like a cronjob ? Or if there is any other good approach please advice . Thanks Raheel
Yes, you can make a plugin. Following is the way to add cron job functionality in WordPress plugin. < < However, please note that this does not provide a real (system based) cron. It requires at least someone to visit your site, so that the functions keep on executing periodically.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, wp cron" }
Auto-crop width, not height I need images to be auto-cropped if they are too wide only. Basically like this: !Crop-visualization I'm using it for a fullscreen slider, where too wide images gets stretched. Cropping obviously is the best of two evils.
Wordpress cant do it alone. You need a script called Timthumb.php to do it. This is really simple to use. Check it out: < And the best: wordpress will not store multiple versions of your images when crop. It will be done by the script on demand.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, cropping" }
Redirect to Page URL for non-members My membership plug in won't let me re-direct custom post type archive / taxonomy URLs to a non-member page if the user requesting access is not logged in or not a member. So, I am trying a hack to check if user is Level A, B, C etc and if not the template page redirects to a no access page. I'm using the code below to check for access levels. What would be the best way to insert a page redirect? <?php if(mgm_user_is(array('level1','level2' ))) { echo 'REDIRECT TO NON-MEMBER PAGE'; } else { echo 'GIVES ACCESS TO PAGE SEARCHED FOR'; } ?>
You can use use wp_redirect for that. Here is a simple code, it redirects non-users to website homepage. You can redirect them to a error page or on signup page. <?php if( mgm_user_is( array('level1', 'level2' ) ) ) { wp_redirect( home_url() ); exit; } else { // show content } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp redirect" }
onclick open window I am using AS-PDF plugin in WordPress. In this plugin, For opening new window, I would like to add onclick events in it like that function as_pdf_link( $strContent ){ global $wp_query; $strHtml = ' <div id="aspdf"> <a target="_new" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/as-pdf/generate.php?post=' . $wp_query->post->ID .'"onclick="open(this.href, this.target, 'width=600, height=450, top=200, left=250'); return false;"> <span>' . stripslashes( get_option( 'as_pdf_linktext' ) ) . '</span> </a> </div> '; return $strContent . $strHtml; } But It doesn't work. So, please guide me how to do. Thank in advance.
Earlier it was giving you error. Try this. I have fixed errors in PHP syntax. function as_pdf_link( $strContent ){ global $wp_query; $strHtml = ' <div id="aspdf"> <a target="_new" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/as-pdf/generate.php?post=' . $wp_query->post->ID . '" onclick="open(this.href, this.target, \'width=600, height=450, top=200, left=250\'); return false;"> <span>' . stripslashes( get_option( 'as_pdf_linktext' ) ) . '</span> </a> </div> '; return $strContent . $strHtml; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins" }
Redirect page to default subpage On a site that I'm working on I have a particular page that has four subpages, which act like process steps. I want the parent page to always redirect to the first of these as a default, should the user type in or click on a url that only points to the parent page. Is there a way to accomplish this without the use of mod_rewrite? Thanks in advance.
You can try something like this. This will check if a page has child pages and if it does then it will redirect the first page in array ordered by menu order. // get child pages $child_page = get_pages( "child_of=" . $post->ID . "&sort_column=menu_order" ); if ( $child_page ) { // get id of first child page $firstchild = $child_page[0]; wp_redirect( get_permalink( $firstchild->ID ) ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "pages, redirect, child pages, customization" }
Create a front page template and separate page for posts? I'm building a WordPress theme. I need two type of pages, one is home page which will display on www.example.com. I also need a list of all my posts on www.example.com/blog/, but I need both in one WordPress theme. Is there the right way to use home.php or front-page.php? If no then please suggest me the right way to solve my problem. If yes then please suggest me how can I see all my blog post list on www.example.com/blog/
Use the WordPress Reading settings for your posts page named blog and create a static front-page.php file for your front page in your theme.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "homepage, blog, frontpage, blog page" }
Which built-in Wordpress files are safe to edit? I begin to work with Wordpress, I'm developing a theme with many functionnalities into it, and I'm good with that. My question does not have to do with theme development, but more with general knowledge about Wordpress. I would like to know which files are safe to edit in a standard Wordpress installation : files that will not be overwritten when we perform an update of Wordpress for instance. I know of `wp-config.php`, but are all others at the root safe too ? I ask this because I want to add filters in my Wordpress website and those filters will be independant of a plugin or a theme. Currently I added them in `wp-settings.php` but I found nowhere if this file is safe to edit.
_Consider **everything** that comes with a vanilla WordPress installation a core file._ Core files will be overwritten on updates, so _it's **not** safe to edit them_. E.g. `wp-config.php` isn't a core file, because the vanilla installation comes only with the sample version of that file.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "filters, wp config, customization, settings api" }
Wordpress address URL and bloginfo I have updated my Wordpress Address (URL) and Site Address (URL) to be https:// in the General Settings of Wordpress as I have added a secruity certificate to the hosting. Should the css url automatically update to reflect the new address if I'm using <link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); ?>" /> in the header code. The url is now https:// but the css url is still pointint to http://
You will need to use `site_url($path_to_style_sheet, 'https')` instead of `bloginfo()`. The `home_url()` method also supports https.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, urls, https, bloginfo" }
Heartbeat API: How to access data already enqueued? I'm having problems when trying to access data that I've queued using the Heartbeat API. I'm queuing data using `wp.heartbeat.enqueue()`. For example: var data = { my_key: 'value' }; wp.heartbeat.enqueue( 'my_handle', data, false ); Then later on in my script, I'd like to access the data I've queued. For example: $( document ).on( 'click', '#button', function() { // Here, I want to access the data I've enqueued. }); I've tried doing the following but that doesn't work: $( document ).on( 'click', '#button', function() { var my_data = wp.heartbeat.getQueuedItem( 'my_handle' ); alert( my_data.data.my_key ); }); Hoping someone can suggest where I'm going wrong?
I found the solution to my problem was to change `my_data.data.my_key` to `my_data.my_key`. For example: $( document ).on( 'click', '#button', function() { var my_data = wp.heartbeat.getQueuedItem( 'my_handle' ); alert( my_data.my_key ); }); The queued data can be easily accessed now.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "jquery, javascript, heartbeat api" }
Display future posts in archive I'm using the following code to display an archive of posts. <?php // Get years that have posts $years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY year DESC" ); // For each year, do the following foreach ( $years as $year ) { // Get all posts for the year $posts_this_year = $wpdb->get_results( "SELECT * FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' AND post_status = 'future' AND YEAR(post_date) = '" . $year->year . "' ORDER BY post_date DESC" ); foreach ( $posts_this_year as $post ) { // echoing miscellaneous stuff } } ?> There it says `post_status = 'publish'`. How can I add future posts to my archive? I tried adding `AND post_status = 'future'` to both `$wpdb->get_results` entries but it doesn't work.
You need to use "OR" instead of "AND", <?php // Get years that have posts $years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND (post_status = 'publish' or post_status = 'future') GROUP BY year DESC" ); // For each year, do the following foreach ( $years as $year ) { // Get all posts for the year $posts_this_year = $wpdb->get_results( "SELECT * FROM wp_posts WHERE post_type = 'post' AND (post_status = 'publish' OR post_status = 'future') AND YEAR(post_date) = '" . $year->year . "' ORDER BY post_date DESC" ); foreach ( $posts_this_year as $post ) { // echoing miscellaneous stuff } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, wpdb" }
Allow shortcode for custom widget The following code allows shortcode parsing for 'text' widget: add_filter('widget_text', 'do_shortcode'); How to make a similar one for a custom widget? I tried the following one but it didn't work: add_filter('widget_CUSTOM_WIDGET_NAME', 'do_shortcode');
You can try the following: /** * Only allow shortcodes for a widget with a given title. * * @see */ function wpse_widget_shortcode( $text, $instance ) { // Only allow shortcodes for the widget with the following title: $title = 'Some Title'; remove_filter( current_filter(), __FUNCTION__ ); if( isset( $instance['title'] ) && mb_strtolower( $title ) === $instance['title'] ) $text = do_shortcode( $text ); return $text; } add_filter( 'widget_text', 'wpse_widget_shortcode', 99, 2 ); where we target the given widget by it's title.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "widgets, shortcode" }
change $src from wp_register_script in plugins/themes I have a lot of plugins using external scripts from googleapis - these are throttled/blocked in China and it causes a lot of problems. Without rewriting the lines in all the plugins/themes and break my upgrade path, is there a way we can do it in my themes function.php file so I rewrite all the $src urls to local urls?
Well of course you can. All you need to find is what handle they are using for those scripts. let's say they are uing plugin-script handle. Then you deregister and register script again with your URL. Like this. function wcs_scripts_styles() { wp_deregister_script( 'plugin-script' ); wp_register_script( 'plugin-script', get_stylesheet_uri(). '/js/jquery.script.js', array( 'jquery' ), NULL, true ); } add_action( 'wp_enqueue_scripts', 'wcs_scripts_styles' ); This will replace script location to script hosted in you theme js folder.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "scripts" }
Timthumb not working with WordPress 4.0 I just updated WordPress to the latest version, 4.0, and I had a bad surprise - timthumb stopped working. the thumbnails are not generated. I cleared theme's cache folder, and checked to see if chmod is 755 - it is. timthumb is also updated to the latest version. this is how I call the thumbnail <img src="<?php bloginfo('stylesheet_directory'); ?>/timthumb.php?src=<?php get_image_url(); ?>&amp;h=170&amp;w=170&amp;zc=1" alt="<?php the_title(); ?>"/> What else can I do? thank you
solved. seems that the problem was with a file added in wp-content - for security reasons, I added a .htaccess file to wp-content folder, and that was blocking timthumb. In case others have problems, remember not to limit access to wp-content.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "thumbnails, timthumb" }
Is there any way to tell when wp_postmeta has been updated? I have a website for a client, where users can vote up or down certain things on a leaderboard. The up vote is stored within wp_postmeta as a field. What I'd like to be able to do is see what the league table looked like at a certain date & time, but as far as I can see there is no date/time stamp within that table to show when it was last updated. Am I missing something, or is there no way of telling when that field was amended? thanks Rob
You are right the `wp_postmeta` table: !enter image description here does not save any kind of time stamp. Unlike for example the `wp_posts` table with `post_date`, `post_modified` and such. So you have to implement a mechanism to keep track of the points in time when votes happened yourself.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, post meta" }
Add term list as class I am trying to add a list of terms as a class for custom post types. <?php while($portfolio->have_posts()) : $portfolio->the_post(); ?> <?php $categories = get_the_terms($post->ID, 'project_type'); foreach($categories as $category){ return $category->name; } ?> <div class='portfolio-tile <?php echo $category ;?>'> <?php the_post_thumbnail('medium' ); ?> </div> <?php endwhile; ?> </div> <?php wp_reset_query(); ?>
I found that the best way to handle this problem was to leverage the post_class function and add the loop through the function.php file. this is the code in the function.php file: function term_class($classes){ global $post; $taxonomies = array('project_type'); $terms = get_the_terms( $post->ID , $taxonomies); foreach ($terms as $term) { $classes[] = $term->name; } return $classes; } add_filter( 'post_class', 'term_class' ); add_filter( 'body_class', 'term_class' ); Then I just added the post_class() function the custom posts template. Thanks for all the help everyone.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy" }
Wordpress plugin shortcode not working I have a shortcode defined in a plugin as follows: // [tag1] -> Some Longer Text function shortcode_example1() { return 'Some Longer Text'; } add_shortcode('tag1', 'shortcode_example1'); Now within a wordpress page I am trying to access the plugin as follows: [tag1] However, the shortcode is not run and the output is just "[tag1]". Can you help? Thanks for your help.
Thanks for your responses. After further investigation, I found that the plugin file where my shortcode was defined was showing up as "inactive". Once I moved my shortcode definitions into an active file, then everything began to work. I hope this is useful for anybody who runs into this in the future. Thanks again!
stackexchange-wordpress
{ "answer_score": -5, "question_score": 9, "tags": "shortcode" }
A truely custom login page? I don't want to use a plugin for this one and i would like to know how i can use a custom form for WP login. I made a form with bootstrap and i added the form action and two hidden fields but it doesn't work <form name="loginform" id="loginform" class="form-signin login_form" action="<?php echo esc_url( wp_login_url() ); ?>" method="post"> ....... <input type="hidden" name="redirect_to" value=" //echo $_SERVER["REQUEST_URI"]; ?>" /> <input type="hidden" name="testcookie" value="1" /> Or should i let this go and alter wp-login.php with hook and filters??? Any tips?
As @Tomas Cot says, this page has everything you're looking for: < Specifically, this section is what you're looking for: **Make a Custom Login Page** > So far you've seen how to customize WordPress' built-in login page. You can also create your own custom login Page by using the wp_login_form function in one of your WordPress Theme's Page Templates: <?php wp_login_form(); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "customization, login, wp login form" }
All links in WP blog redirect to main non-WP site I worked on a Drupal site for a client, but he wanted to keep his blog on WP, so I manually created a 'blog' folder on the root of the Drupal site and moved all the WP content there. I uploaded the database and change the wp-config.php settings accordingly. The main Drupal site (example.com) works fine, and when I click on the blog link I'm taken to the front page of the blog like it's supposed to, but inside the blog, (example.com/blog), any other link I click will show a 'page not found' message as if I was looking for non existing content on the main site. I'm not very familiar with WP. Is it because I installed manually? what configuration am I missing? EDIT: I tried define('WP_HOME',' define('WP_SITEURL',' on wp-config.php, but that didn't work.
make a backup of your SQL database for the site and try running these queries manually on the database through php myadmin. change the URLs to match your site < As always, be careful when running queries on the database UPDATE wp_options SET option_value = replace(option_value, ' ' WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, ' UPDATE wp_posts SET post_content = replace(post_content, ' ' UPDATE wp_postmeta SET meta_value = replace(meta_value,'
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "installation, wp redirect" }
Use one template only for custom post type archives? I'm currently using `archive.php` as a generic listing for categories, tags, authors, etc. However, my custom post types have a very customized archive page that's completely different from `archive.php`. I'm wondering if there's a way to create one archive file that acts as a generic template for **only** my custom post types. If it was included in the Template Hierarchy, it would likely be called `archive-post-type.php` or `post-type.php`. I know I can use includes or `get_template_part`, but it's really just the same archive file across multiple post types, so I'd rather just create one file for all of them. Ideally, this CPT archive template could still be overridden by `archive-$posttype.php`. If I utilized `archive.php` instead for the custom post types, I'd have the same problem in reverse, since `category.php`, `tag.php`, `date.php`, etc. would all be the same template, yet still different from `archive.php`.
add_filter( 'template_include', 'wpsites_cpt_archive_page_template', 99 ); function wpsites_cpt_archive_page_template( $template ) { if ( is_post_type_archive() ) { $new_template = locate_template( array( 'your-cpt-template.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; } Try this in your functions file. You can add your post types to this line like this: if ( is_post_type_archive(array( first-post-type, second-post-type ) ) ) { Uses `is_post_type_archive` & `template_include`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "templates, archives, custom post type archives, template hierarchy" }
how do you use Wp-cli on Shared Hosting? I Have Godaddy Deluxe linux hosting it is shared server, so I don’t have the root password of the machine. I can create, move and delete files via SSH in my home folder but not in the root directories like /opt /etc. curl -O php wp-cli.phar --info chmod +x wp-cli.phar sudo mv wp-cli.phar /usr/local/bin/wp I am not able to execute the `sudo` command. Can anyone gives me alternate way for installing it?
the default instructions assume you have root and are intended to provide the most convenient use by placing the phar package in your path alternative 1: remove the sudo, change `/usr/local/bin/wp` to `/path/to/your/installation/wp`, and instead of calling the commands with `wp command <parameters>` use `./wp command <parameters>` alternative 2: remove the sude, change `/usr/local/bin/wp` to `/any/other/path/wp` and instead of calling commands with `wp command <parameters>` use `/any/other/path/wp command <parameters>`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "shared hosting, wp cli" }
Make slug as ID Number for custom post types I want to make the slug for each of my custom post types to be the post ID number. How do I do this? None of my posts accept post title, content, or anything else - they require different data which was easier to display as a meta box). To illustrate: I have a CPT ('eduation'). When I submit the post into the database, it has an ID of, say, 15. When I visit mysite.com/edu/15 ('edu' being the post slug that I have set), I see the details from this post in my site. I know I could simply change the permalinks, but I want those to stay as they are; I just want to change the ones for these custom post types. Sorry if the question is confusing. It probably is really simple to answer, but I really don't know what the answer is.
Here's a way how to change the slug: add_action('wp_insert_post', 'change_slug'); function change_slug( $post_id ) { // Making sure this runs only when a 'eduation' post type is created $slug = 'eduation'; if ( $slug != $_POST['post_type'] ) { return; } wp_update_post( array( 'ID' => $post_id, 'post_name' => $post_id // slug )); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, slug, id" }
Adding content to custom taxonomy category pages I can't figure out or find an answer on how to enable the description in the custom taxonomy category pages. Under description field it says: "The description is not prominent by default; however, some themes may show it.". I've managed to enable it to normal category pages by adding this code to archive.php <?php echo category_description(); ?> But it's still disabled on taxonomy pages. Any help will be appreciated. **Problem solved** I find out that my theme has taxonomy.php where this code <?php echo term_description(); ?> needs to be added to make the description visible on custom taxonomy page. Thanks to @PieterGoosen for helping me out.
To display the description from a taxonomy term, you can use `echo term_description( $term_id, $taxonomy );` where `$term_id` is the term ID of the current term and `$taxonomy` is the taxonomy the term belongs to. For general use on your taxonomy page, you can just use `echo term_description();`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy" }
Displaying content of single post How I can display content for a single post? My code: if (is_single()){ get_header(); get_sidebar('left-article'); render_article(); get_footer(); } In `render_article` I call `single_post_title()` to get title of post. However I don't know how to get time and contents of the post as I can't find any function like `single_post_content()` or `single_post_time()`.
1. Create a file named single.php. This will automatically get all you single posts. For more information about WordPress' template hierarchy, read the Codex 2. Inside single.php, run the default loop and get header.php, sidebar.php and footer.php <?php get_header(); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php the_title(); ?> <?php the_content(); ?> <?php echo get_the_date(); ?> <?php endwhile; ?> <?php endif; ?> <?php get_sidebar(); ?> <?php get_footer(); ?>
stackexchange-wordpress
{ "answer_score": 13, "question_score": 5, "tags": "posts" }
E-mail Update - Validation i want to know what is wrong with this code: if ( !empty( $_POST['email'] ) ){ if (!is_email(esc_attr( $_POST['email'] ))) $error[] = __('The Email you entered is not valid. please try again.', 'profile'); elseif(email_exists(esc_attr( $_POST['email'] )) != $current_user->ID ) $error[] = __('This email is already used by another user. try a different one.', 'profile'); else{ wp_update_user( array ('ID' => $current_user->ID, 'user_email' => esc_attr( $_POST['email'] ))); } } This is not working with me, i try several changes on it but without success. It keeps warning me the "This email is already used by another user." But it is not! Is like this code is not validating well. PS: I got this code from here: How to edit a user profile on the front end?
Well, you comparing the results of the `email_exists` function with `$current_user->ID`. If email exists, `email_exists()` return the ID of the user using that email or false if the email doesn't exists. Imaging you are checking a email not being using, `email_exists()` return false and this `if` will validate: elseif(email_exists(esc_attr( $_POST['email'] ) ) != $current_user->ID ) Do you see the error? You should modify the above line with something like: elseif( email_exists(esc_attr( $_POST['email'] ) ) && email_exists(esc_attr( $_POST['email'] )) != $current_user->ID )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user meta" }
How to Javascript/jQuery I am trying to turn an HTML 5 template into a Wordpress theme. The jQuery/Javascript combo seems not to be working, what should I do? (I just used `<?php echo get_template_directory_uri(); ?>` so the .js files are correctly linked)
Just paste this in your functions.php file. It will automatically add jQuery in your theme. function wcs_scripts_styles() { wp_enqueue_script( 'jquery' ); } add_action( 'wp_enqueue_scripts', 'wcs_scripts_styles' ); WordPress automatically include jquery from it's location. You do not need to upload jquery on your theme. additionally you can also add more scripts lile this. function wcs_scripts_styles() { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'new-script', get_template_directory_uri().'/js/new-script.js', 'jquery', NULL, true ); } add_action( 'wp_enqueue_scripts', 'wcs_scripts_styles' ); In this code `new-script.js` is in theme\your-theme\js\ folder. You can similarly add more js files like that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "jquery, javascript" }
Query outputting YouTube url rather than embedded video I am having an issue with a query outputting the YouTube url rather than the video itself. The post I am querying has a Youtube url in the content area. Of course, when viewing the post, you don’t see the url, you see the video, as it’s supposed to be. When using get_the_content to display this post on another page, it’s outputting the Youtube url rather than embedding the video automatically. If I use the_content, then it outputs the video, but it does so before the other html. Here’s my query, if that helps: <
The problem is that as you are calling the function directly, there are filters that arent being called, you can fix this by calling the `apply_filters` function using `the_content` filter, like this. apply_filters( 'the_content', $content ); Where `$content` is the result of `get_the_content()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
Using List Table Filters for ALL Custom Post Types Is there a way to create sortable columns for admin tables across ALL post types? I am working on a project with 7 Custom Post Types, and wondering if there is a better approach than using multiple _manage_edit-{Post-Type-Here}_sortable_columns_ filters for each post type.
You're going to have to use the filters for each post type anyway. If you plan to leverage a bunch of dynamic filters that all call for all 7 post type slugs you could stick them in an array and loop through the filters with a foreach. Saves a little bit of code at least. $post_types = array( 'ptype_one', 'ptype_two', 'ptype_three', 'ptype_four', 'ptype_five', 'ptype_six', 'ptype_seven' ); foreach ( $post_types as $type ) { add_filter( "manage_edit-{$type}_sortable_columns", "your_callback" ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp admin, wp list table" }
Hide some portion on single.php base on author I would like to hide some portion in view post base on author. My requirement is that I have an job board theme and user can post the job. So there is "How to Apply" section in detail page. Now, I want to auto post from other job site feed by using a author called "Aggregator". He has a role called "Aggregator". So I want to hide "How To Apply" section, if post author role is "Aggregator". May I know How to get and check post author role? Thanks, Alex
if( !in_array('Aggregator', get_the_author_meta('roles')) ){ //If user is not aggrigator display the info } That will get the authors roles as an array for the current post. You can pass a post id along with the 'roles' to get the data from another post. Also note that your Aggrigator role is possibly set-up in word press in lower-case so make the if statement reflect this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom post types, user roles" }
Cannot filter categories by parent category I'm trying to get all direct child categories in category hierarchy. What I've tried: $args = array( 'child_of' => get_query_var("cat") ); $categories = get_categories($args); foreach($categories as $category) { $catID = $category->cat_ID; $test = "cat_ID: " . $category->cat_ID . " " . "parent: " . $category->parent . ", "; echo $test; } In case`get_query_var("cat") == 14` I get the following result: > cat_ID: 35 parent: 14, cat_ID: 34 parent: 14, cat_ID: 36 parent: 34, cat_ID: 37 parent: 34, which is not what I want because this displays child's child categories. So I tried $args = array( 'parent' => strval(get_query_var("cat")) ); which results in > cat_ID: 35 parent: 14, instead of what I expected > cat_ID: 35 parent: 14, cat_ID: 34 parent: 14, So what's going wrong?
To get direct descendants (i.e. children only) of the category, you need to make use of the `parent` parameter in `get_categories()` The reason why you might not see your other category is that it does not have any posts assigned to it. To display empty categories, you need to set the `hide_empty` parameter to `0` Otherwise I do not see any problems with your code. You should also turn on debugging to check if you maybe have some kind of error if the above does not work
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
WP Query orderby meta key natural sort? I have this code: $args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'meta_key' => 'custom key', 'orderby' => 'meta_value', 'order' => 'ASC', 'no_found_rows' => true, 'cache_results' => false, 'include_children' => false, 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'id', 'terms' => array($cat_id) ) ) ); $loop = new WP_Query($args); When the custom key is like FA3 FA1 FA10 the wp query orderby paramaters sorts this as FA1 FA10 FA3 **when I want a nsort-algoritm:** FA1 FA3 FA10 Is there any way of acheiving this with `WP_Query`? (Or is the only option to create an array and sort that array with `nsort()`)
No, not as a straight WP_Query. This is because of several factors, with the main one being that mySQL doesn't natively have a natural sort for alphanumeric columns. WordPress does support a "meta_value_num" for the orderby parameter, which causes it to cast the values to numeric to perform the sort, and this works when you're putting wholly numeric data in the meta_value's, but since you have a mixed set of text and numbers, you can't use that. You can add a filter to the `posts_orderby` and rewrite the orderby clause directly to make it whatever you like. If your data is always going to start with "FA", then you could make your filter return something like this: `LENGTH(meta_value) ASC, meta_value ASC` That first sorts by the length, then by the value. So shorter items come first, giving you a semi-natural sort.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "wp query, sort" }
What is the purpose of logging out after Wordpress upgrade? I had recently noticed when testing Wordpress 4.0 upgrade, that it logged out of the site and went to the login screen, with a message saying to log back in to enjoy the new improved Wordpress. What is the reason for this logout? I don't remember seeing this previously, and when a programmatically-called Wordpress upgrade occurs the user isn't logged out and it works fine.
4.0 made a change to the structure of the authentication cookie and added a "token" feild to it. I assume that you were logged out because your older style cookie didn't match the new format.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "login, upgrade" }
A good hook to check authorization and redirect? It seems strange to put a redirect in a template page, because so much of the page has already been built by the time you reach a custom page template. I'm wondering what is a good action hook to use where I can test whether the user's logged in, and whether they're on a particular page/category/etc and `wp_redirect` them if necessary?
I'm guessing the built-in `template_redirect` action is the best for this... :D <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, redirect, actions, wp redirect, privileges" }
Get category ID after wp_insert_term I'm using `wp_insert_term` to create categories, after the category is created I'd like to get its ID: `$cat_id = wp_insert_term($name, 'category', array('slug' => $slug) );` ...however when I try to print `$cat_id` I get `Array` instead of the actual ID. I guess I have to state which part of the array I need, but I don't really know what the variable for the ID would be?
It should be a key of `term_id`, so `echo` out `$cat_id['term_id']` and you should get the new terms ID.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "terms" }
wp-content/db.php : where is this file? At the top of the source file `wp-includes/wp-db.php` I can find the following comment: /** * WordPress Database Access Abstraction Object * * It is possible to replace this class with your own * by setting the $wpdb global variable in wp-content/db.php * file to your class. The wpdb class will still be included, * so you can extend it or simply use your own. I was wondering how replacing the wpdb class with a different class would work but I cannot find any file under wp-content/db.php. Is there an error in the documentation? Thanks.
You would create your own `dp.php` file in the `wp-content` directory; if you define `$wpdb` in there, it will replace WordPress's default `$wpdb` object. It's not listed on the Pluggable Functions list (not a big surprise, as `$wpdb` is a class, not a function), but it seems similar in concept. Also, if you haven't read it yet, I'd recommend you peruse the WPDB Class documentation.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wpdb" }
add_image_size() width not actually working I've been attempting to add an image size to my code, for an image that needs to be 708px wide. Height can be variable. I've added the code this way: add_image_size( 'full-blog-width', 708 ); add_filter( 'image_size_names_choose', 'my_custom_sizes' ); function my_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'full-blog-width' => __( 'Full Blog Width' ), ) ); } However, when I go to add the images in the media library, the width seems to max out at 474px with the height varied based on proportions. I've attempted hard cropping, but that doesn't seem to affect anything but the ratio in the end. Best I can tell, this 474 number comes from the is the width of the blog post container. Does the media library set a maximum size for the images based off the blog post CSS? Is there a way to override this?
> After playing around a little more, the image does look like it's being resized by wordpress on upload to the 708 width, however, when inserted by the media library, the image is automatically scaled down to 474px which is the width of the text column. This is correct. Themes define a global variable called "$content_width" which tells WordPress the width of the main displayable content area. WordPress will automatically put images into a container with this width, so as to not overflow the content area. The resizing of images on upload is independent of this process. The image will be whatever sizes are defined for it, but it will scale into the space provided for it by the content width.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Make single widget area top level in 4.0 Customize Panel So I have a widget area that, in v4.0, is burried in a dropdown within the secondary Widgets panel on the Customize panel page. Because it's the only widget area it feels rather silly being burried so deeply, so I'm wondering if there's a way to override the nesting and make that widget area dropdown a top-level section like it was in v3.x? It looks like this was brought up by the Core team here, but didn't gain any traction. Does anyone know how I might be able to do this?
Got it. Admittedly, this feels hacky but seems to do the job just fine. In my existing `customize_register` hook I set the following: // Retreive the widget section in the Theme Customizer // We need to cast the return of get_section to an object // "the_widgets_section" in get_section is the ID of the registered widget area $widget_area = (object) $wp_customize->get_section( 'sidebar-widgets-the_widgets_section' ) // The value of panel will be 'widgets', so we set it back to '' (top level panel) $widget_area->panel = ''; // If you're so inclined, we can change the title of it as well. $widget_area->title = __( 'My Widgets', 'textdomain' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, theme customizer" }
Is there any way to recover deleted menu from database sql backup i accidently deleted my main menu but i have a .sql database backup file and i want to recover my menu from this file. Is it possible? Thanks.
I've resolved the problem with explained here : < But i would like to warn the people that will try this solution, you have to have a database backup of WordPress system which has Menu that you would like to revert 1. BackUp your WP database to your PC (bacause, you will use this for reverting back your system to current site) 2. Restore your database that contains correct menu 3. Install WordPress Menu Exporter plugin (i've used on WP 4.0) 4. Export your Menu 5. Restore your database which you backed-up in 1st step (bacause it is your updated/current site) 6. Delete your current menu (otherwise all menus will be exist twice) 7. Import your menu with Wordpress Importer It worked for me...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, database" }
Warning: urlencode() expects parameter 1 to be string, array given in and not getting the preffered output > Warning: urlencode() expects parameter 1 to be string, array given in `D:\xamppp\htdocs\sample\wp-includes\formatting.php` on line 3690 When I try to give the `category_name` in the `query_post`, <?php $args=query_posts( array( 'posts_per_page' => -1, 'category_name' =>array('Breaking News Stories', 'Call-out', 'Featured Story', 'Standard Stories') )); ?> I'm having the above warning in `formatting.php` file. line 3690 has the below code: <?php function wp_basename( $path, $suffix = '' ) { return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) ); } ?>
First of all, never use `query_posts`. Rather use `WP_Query` to construct your custom query which is the prefered way You are also using the `category_name` parameter wrong. If you look at the `WP_Query` documentation, it states > **category_name (string)** \- use category slug (NOT name). Go and have a look at the examples given in the docomentation under the category parameters **EDIT** You need to do someting like this 'category_name' => 'SLUG OF Breaking News Stories, SLUG OF Call-out, SLUG OF Featured Story, SLUG OF Standard Stories'
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "query posts, errors" }
wpquery properties last_query and last_result : should these be public or private? I've come across the following lines of code in `wp-includes/wp-db.php`: /** * Last query made * * @since 0.71 * @access private * @var array */ var $last_query; /** * Results of the last query made * * @since 0.71 * @access private * @var array|null */ var $last_result; I wonder whether, since variables declared with var are public by default, as can be seen here, whether there is an error in the documentation, and whether var in this code snipped should be changed to private or public. Thanks.
As you can guess from version number this code is _ancient_. So ancient in fact that `var` keyword is from **PHP 4** and is deprecated in PHP 5 (considered synonym of `public` for backwards compatibility). So inline doc hints it is private because back then there was no actual property visibility in PHP language. So _conceptually_ it probably would have been protected in modern code (then it would probably need getters, because these two properties are highly useful for debug). _Practically_ however these will _eternally_ be de–facto public, because changing them to private/protected would mean breaking backwards compatibility, which WordPress is dead set against.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
Updating options into the wp database performance I have a question about the performance of my plugin. On the settings page of my plugin I have about 20 options the user can change (checkboxes, dropdown and normal text inputs). Currently I just update all options on submitting the form. Is it better for performance to first check if an option is updated before I really update the option? So that it doesn't write to the database if the option isn't changed?
`update_option()` does this for you already: // If the new and old values are the same, no need to update. if ( $value === $old_value ) return false; No need to worry about it. :) Note that if you have _a lot_ of options, which are not autoloaded, this might cause excessive _read_ queries. This applies to general operation too, not just updates.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, database, options" }
Can't use orderby in WP_Query I can't get my posts to order by the date, descading. I've got the following code: $jobs = new WP_Query(array( 'posts_per_page' => 50, 'post_type' => 'job', 'post_status' => 'publish', 'orderby' => 'post_date', 'order' => 'DESC', 'cache_results' => false )); And this is the output of `$jobs->request`: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'job' AND ((wp_posts.post_status = 'publish')) AND post_date >= "2014-09-10" LIMIT 0, 50 Somehow the whole ordering section is missing, and there's 3 spaces instead. What happened?
Your `orderby` parameter value should be `date` and not `post_date`. Have a look at the orderby and order parameters in `WP_Query` I know the was a track ticket out about this subject, just can't remember where, but yes, I do agree that the value should be `post_date` and not `date`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query" }
Loading jQuery UI in the head I am trying to load jquery-ui-core and jquery-ui-slider in the head of my theme. Here is my code: function load_jquery_ui() { wp_enqueue_script( 'jquery-ui-slider' ); } add_action( 'wp_enqueue_scripts', 'load_jquery_ui' ); The jQuery UI loads in the footer. But because I have some inline scripting (due to php implementation in the JS) I need it to load in the head. Anyone that has any idea how?
Actually. This answer is the only correct answer. If you need jQuery for a certain script just add it as necessary in the jQuery array. wp_register_script( 'ytc-admin-scripts', YTC_URL . 'admin/admin-functions.js', array( 'jquery','jquery-ui-slider' ), '1.0');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, jquery, jquery ui" }
Multi-level ordering in Wordpress I have a collection of posts and first I want to order them by 'name' in ASC order and then order by 'date' in ASC order. How does one go about doing this?
Multiple `orderby` with different sort `order` values are possible as of WordPress 4.0, take a look at the codex page for `WP_Query` \- Order - Orderby Parameters. There is an related Make WordPress Core article too. The following example would comply to what you want: $query = new WP_Query( array( 'orderby' => array( 'name' => 'ASC', 'date' => 'ASC' ) ) );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "sort" }
Next 10 posts data of currently viewing post in blog page I am developing a theme and using WP_Query to fetch the content from the database, but now i wanted to implement a loop using a WP_query that will show me the next 10 posts with title links and featured images while on the single page of a post . for example < In this example , as you open the post named "13 Fun Ways To Make It Easier To Learn A New Language", In the sidebar , it shows the next 5 posts and in the bottom after the end of the current post content it shows us the latest posts after the current post you are currently on.
This will get you next 10 posts on single post template. <?php global $post; $current_post = $post; for ( $i = 1; $i <= 10; $i++ ) { $post = get_previous_post(); // this uses $post->ID setup_postdata($post); get_template_part( 'content', get_post_format() ); } $post = $current_post; // restore ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, query" }
How to Check if a Page Exists by URL? I need to display certain content depending on whether or not a page URL exists. I don't want to check by title, because certain pages will have the same title, and just different parent pages. **For example one page may be:** 1. ` 2. ` I just need to know if one of these URL exists or not.
You could make a list of paths to check... $page_paths = array( 'analysis/firstNamelastName', 'exercise/firstNamelastName' ); Then check if there's a page object for each of the page paths. foreach( $page_paths as $page_path ) { echo '<code>' . $page_path . '</code> ' . PHP_EOL; if( ! $page = get_page_by_path( $page_path ) ){ echo 'Does not exist.' . PHP_EOL; } else{ echo 'Exists and resolves to: <code>' . get_permalink( $page->ID ) . '</code>' . PHP_EOL; } } You can actually use `get_page_by_path();` for Post Types other than `page`. See the third parameter.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 9, "tags": "posts, permalinks, pages, urls, hierarchical" }
Warning: Creating default object... when altering Customize panels I'm trying to move my theme's [only] widget area outside of WP 4.0's nested "Widgets" panel by doing the following: $footer_widgets_section = $wp_customize->get_section( 'sidebar-widgets-footer_widgets' ); $footer_widgets_section->panel = ''; The key is to reset the panel to empty, rather than `widgets`. However, I'm getting a PHP warning: **`Warning: Creating default object from empty value in ...`** (the second line of my above code). Does anyone know how I can fix this?
Turns out `$wp_customize->get_section( 'sidebar-widgets-footer_widgets' )` was returning an Array, although a quick `print_r()` makes it seem as though it was an Object. Anyhow. Simple fix: cast it to an object. $footer_widgets_section = (object) $wp_customize->get_section( 'sidebar-widgets-footer_widgets' ); $footer_widgets_section->panel = '';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, themes, widgets, options" }
If statement to check for post_content I'm trying to write an if statement to check for post_content and if there is no post_content then to grab a textarea field content. Below is my code and with this, at this point it's only rendering "Array" to the page. Any help is greatly appreciated. Thank you! **CODE:** <?php foreach ($partners as $partner) { $a_description = get_post_meta($partner->ID, "a_description"); ?> <div class="partner-content"> <?php if ($partner->post_content && !$a_description) { ?> <?php echo $partner->post_content ?> <?php } else { ?> <?php echo get_post_meta($partner->ID, $a_description, true); ?> <?php } ?> </div> <?php } ?>
The following line is wrong <?php echo get_post_meta($partner->ID, $a_description, true); ?> If you look closely, you are actually passing get_post_meta($partner->ID, "a_description") to the `$key` parameter of `get_post_meta` as this is the value assigned to `$a_description` You should most probably change `$a_description` to just `a_description` **EDIT** This line <?php echo get_post_meta($partner->ID, $a_description, true); ?> should most probably be <?php echo get_post_meta($partner->ID, 'a_description', true); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "conditional content, post content" }
Template for specific post of custom post type I have the CPT "event". I have created single-event.php. I want one particular event to use a different template than single-event. I read elsewhere that this could be done by creating a single-event-[slug].php but I tried it and it does not work. WP uses single-event.php. (I can't find this in the WordPress documentation, so I'm thinking maybe I misunderstood?) Is there a way of doing this?
For the templates WordPress uses, please always refer to Template hierarchy scheme in the Codex. As you can see there, `single-{$posttype}-{$slug}.php` does not exist, there is only `single-{$posttype}.php`. To do what you want, have a look at the filter `'single_template'`: add_filter( 'single_template', function( $template ) { global $post; if ( $post->post_type === 'event' ) { $locate_template = locate_template( "single-event-{$post->post_name}.php" ); if ( ! empty( $locate_template ) ) { $template = $locate_template; } } return $template; } ); After adding this in your `functions.php`, you can create the file `single-event-{$slug}.php` and it will be loaded by WordPress.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "custom post types, templates, single, template hierarchy" }
How do I add and display a custom image field to a category? How do I add and display a custom image field to a category? I know I need to use the hook 'category_add_form_fields' however I am not quite sure how... I am relatively new to wordpress so any help is greatly appreciated!
I have used ACF - Advanced Custom Fields for this multiple times ( < ). The problem with taxonomy images & other custom fields is that the values are stored in wp_options table. In bigger sites this will populate the wp_options table a lot and is probably not the most efficient way to store data. You can use advanced techniques to avoid this, but if your site is relatively small, it's okay to use custom fields the way ACF and categories images -plugin (mentioned in answer by lacey tech solutions) do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, custom field" }
Display empty taxonomy terms with get_terms() I have a function setup as follows: <?php $terms = get_terms("wpsc_product_category"); if ( !empty( $terms ) && !is_wp_error( $terms ) ){ foreach ( $terms as $term ) { ?> <li class="calendar-filter-menu-item" data-filter=".<?php echo $term->slug; ?>"><?php echo $term->count; ?></li> <?php } } ?> Which displays the taxonomy `slug` and `count` for each taxonomy, only problem is it's not showing a taxonomy that has no posts in, only taxonomies with posts assigned to them are being show, is it possible to show empty taxonomies as well?
You can make use of the `hide_empty` argument of `get_terms()`. It's default value is set to `true`. Do it somewhat like this: $args = array( 'hide_empty' => false ); $terms = get_terms( 'wpsc_product_category', $args );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "categories, custom taxonomy, taxonomy, terms" }
Empty excerpt using wp_get_recent_posts I have this simple shortcode to display the last posts with it's title and except: add_shortcode('latest3', function(){ $recent_posts = wp_get_recent_posts( array( 'numberposts' => 3, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish' ), ARRAY_A); $output = '<h2>Latest posts</h2>'; foreach ( $recent_posts as $recent ) { $output .= '<h3>'.$recent["post_title"].'</h3>'; $output .= $recent["post_excerpt"]; } return $output; }); But for some reason the excerpt output is empty. `print_r($recents)` shows that there is indeed an array key called `post_excerpt` but is shown always empty.
The `post_excerpt` value is empty because you have no explicit excerpts for your posts. While `the_excerpt()` does generate an excerpt from the posts content if the post excerpt is empty, the function `wp_get_recent_posts()`, which is basically a wrapper for `get_posts()`, doesn't.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "excerpt, recent posts" }
Is it possible to override the ABSPATH constant In 4.0 `wp-config-sample.php` contains /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); but `ABSPATH` is defined in `wp-load.php` before including `wp-config.php` /** Define ABSPATH as this file's directory */ define( 'ABSPATH', dirname(__FILE__) . '/' ); error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR ); if ( file_exists( ABSPATH . 'wp-config.php') ) { /** The config file resides in ABSPATH */ require_once( ABSPATH . 'wp-config.php' ); I assume `wp-config-sample.php` is out of sync with the actual code, but did I miss something and there is some other way to override `ABSPATH`?
The official reply is that `ABSPATH` is more for backward compatibility with code which was written when plugins were including `wp-config.php` and overriding `WP_CONTENT_DIR` should be enough. < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp config" }
Export Users and their Advanced Custom Fields I've google it but i am still looking for a solution. Is there a plugin or method to export wordpress users with their advanced custom fields? I don't want to export ACFs structure but users' data.
Export Users to CSV plugin does support exporting user fields, out of the box. That should work. And, later if you intend to import them to another site, you can try WP All Import plugin, but be aware that this plugin isn't free.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, advanced custom fields, export" }
Plugin and theme script load order I'm building a plugin that adds scripts to the page using `wp_register_script` and `wp_enqueue_script`. However, when the page loads, it's loading the plugin scripts before the theme's scripts. This is causing some errors because the theme is loading jQuery, which needs to be loaded first. Is there a way of making the plugin script load last, so that the theme script is loading first in the page?
For scritps and using the wp_register_script() function, you can define the dependeny of jQuery in the $deps argument, which is documented as: > $deps: Array of the handles of all the registered scripts that this script depends on, that is, the scripts that must be loaded before this script. These scripts will automatically be enqueued when this script is enqueued with wp_enqueue_script(). Set false if there are no dependencies. Default: array() < Example: wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/js/my-jquery-custom.min.js', array('jquery'), '1.0', true);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, wp register script" }
Hide cart when empty Could someone help me with this syntax: At the moment I have a simple link to my shopping cart like this: <?php if ( is_woocommerce_activated() && isset( $woo_options['woocommerce_header_cart_link'] ) && 'true' == $woo_options['woocommerce_header_cart_link'] ) { ?> And I want to add the condition to show my mini-cart when contents are greater than 0. I found the code below, but I can't figure out where to put this condition in the line above. <!-- <?php if ( is_woocommerce_activated() && sizeof( $woocommerce->cart->cart_contents ) !== 0) { appply_mini_cart(); } ?> --> I would appreciate some guidance! Thanks
Just add another `AND` (`&&`) clause to the end of it. <?php if ( is_woocommerce_activated() && isset( $woo_options['woocommerce_header_cart_link'] ) && 'true' == $woo_options['woocommerce_header_cart_link'] && sizeof( $woocommerce->cart->cart_contents ) !== 0) {...} Probably best to take a look at some of the PHP tutorials or documentation around as you will be coming up against this type of syntax regularly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, themes, woocommerce offtopic" }
Increase Comment Author Gravatar Size On WordPress Default Comment Function I am new to WordPress theme development. I am designing a new theme and using less codes and file as I am starting from basic. I am adding comments and comment form in my `single.php` using `<?php comments_template(); ?>` only. This one line is showing my blog comments, comment navigation, comment form all things. But its showing my commenters gravatar in `32px` size that I want to increase. I know that if I will use `comments.php` then I can do it but **How To Increase Comment Author Gravatar Size?** in this circumstances.
The answer is that you can't do it without using `comments.php`. Since WordPress 2.7, `comments.php` is important to display full features and customizable comments rest if you still want to use `<?php comments_template(); ?>` then you can edit anything in it except CSS.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, comments, comment form, gravatar, comments template" }
How to get the posts published in last two days using WP_Query? I am trying to loop through all the post to get the top most shared posts on social network. I want to use the `date_query` parameter in the `WP_query` to get the posts of last two days , last 5 days, last 7 days and last 9 days. How can i implement it through using the `date_query` in `WP_Query` My `WP_query` is <?php $args = array( 'post_type' => 'post', 'order'=>'DESC', 'posts_per_page' => 1, 'date_query' => array( array( 'after' => '10 days ago', 'inclusive' => true, ), ), 'orderby'=>'meta_value', 'meta_key'=>'esml_socialcount_TOTAL' ); $the_query = new WP_Query($args); if($the_query->have_posts()) { while ($the_query->have_posts()){$the_query->the_post(); ?>
Here are two ideas for your `date_query` part: # 1) After `2 days ago`: If you need posts published after **current time, 2 days ago** : 'date_query' => array( array( 'after' => '2 days ago', // or '-2 days' 'inclusive' => true, ), ), then the corresponding SQL part is: post_date >= '2014-09-09 17:57:15' if the current date-time is `2014-09-11 17:57:15`. ## 2) After `midnight 2 days ago` : If you need posts published after **midnight, 2 days ago** : 'date_query' => array( array( 'after' => 'midnight 2 days ago', 'inclusive' => true, ), ), then the corresponding SQL part is: post_date >= '2014-09-09 00:00:00' if the current date-time is `2014-09-11 17:57:15`. You can than easily modify this to other day periods.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 2, "tags": "wp query, query, date time" }
Native "playlist" shortcode random playing... How? I'm using the beautiful shortcode "playlist" in my site but I want the random playing of my audio files. What I use is this: > [playlist tracklist="false" images="false" artists="false" ids="7691,7690,7688,7687,7686,7685,7684,7683,7682,7681,7680,7679,7678,7677,7676,7674,3978,3647,3408,1395,1217,1216,1214,1213,1211,1210,1209,1208,1207,1206,1181,975,899,668,663,642,641"] How to make random playing, maybe also with dad jQuery?
I removed all that duplicated and unnecessary stuff, take a look at otto's or kaiser's answers for the very simple solution. * Trac ticket: #29629. * Codex entry for Playlist Shortcode.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "shortcode" }
Page not found error shown while installing wordpress on IIS server I am installing a wordpress folder on a windows server, but it shows page not found. I am unable to even see the first page of installation. This is the site address < Can anyone tell what the issue can be??
If you've uploaded all the Wordpress files, then it appears your web site isn't setup to process .php files. **Ask your web host to enable PHP for your site.** It would appear you've uploaded the files, as I see < and /readme.html, and looking deeper /newsite/wp-admin/css/about.css Assuming the Windows server has PHP installed and configured, and IIS is setup to process PHP requests in general, your site will need to have a handler mapping for PHP added. Otherwise you'll get `HTTP Error 404 - File or directory not found` if you try opening any .php files. If this is your own Windows server, there are detailed instructions on what you need to do for IIS 7+ at < or older IIS 5.1/6 at <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "installation, iis" }
what to backup (for partial restore)?? My site has hacked three times, and as forced by host provider, now there is no option in front of me, except restoring a healthy backup for around 3 weeks ago. (Hacker had created a backdoor in my site, and was using my site for sending mass spam emails, and i couldn't find that backdoor. I could only remove bad files which was uploaded by hacker). Before restoring that old backup (for 3 weeks ago), what i must to backup - or download- to add posts created during these 3 weeks. I mean, if restore backup of 3 weeks ago, i lose all posts created during this 3 weeks. what must i do to get my site to current state with all posts, pictures, ... Thanks in advance (and sorry for bad english)
To backup only posts,pages and related media files for 3 week. You need to do the following:- 1. Backup Database of website for post/page text. 2. Backup wp-content\uploads folder for media. Then you can delete all files and restore old files.Once all old files uploaded then you can upload wp-content\uploads folder of current site. PS: check uploads and folders in it for any backdoor code. **Edit** Once restoration is done install Anti-Malware WordPress plugin and scan for any malware files in them. It is better plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "backup" }
At what point during a typical request does the $wpdb object become available? I've wrote some custom SQL queries inside a class method and noticed they seem to work if I hook the method to the `wp` action. If I hook to the `plugins_loaded` action, they don't seem to work. **My question:** At what point during a typical request does the `$wpdb` object become available? Refs: * < * <
Please, post your code because the problem is not the one you guessed. Actually, `$wpdb` is available very early: it is inited by the function `require_wp_db()` located in the file `wp_settings.php` at line #79. The hook `'plugins_loaded'` is fired in the same `wp_settings.php` file, but at line #237, so pretty after `$wpdb` is available.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, actions, wpdb" }
How to Display the tag content of Custom Post? I have a custom post called "Portfolio" whith the taxonomies: \- Categories \- Tags (tag clouds) I want to show the Tag content inside the custom post. Thanks.
in the loop, insert **the_tags()** function, like this: <?php while(have_posts()) : the_post(); ?> <div class="your_content_div"> <?php the_content();?> </div> <div class="tagssss"> <?php the_tags();?> </div> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, tags" }
Is there anyway to use relative link instead of absolute link? I have working on `xx.xyz.com` then my project is move on `xyz.com` In which I have gave in project the previous link is as below > .xyz.com/?page_id=634 And now my link is as belows > xyz.com/?page_id=634 I have tried to put link relative like > ../?page_id=634 but its not working. Any suggestion regarding this?
You should be using home_url() ( or something similar ) in your links for theme files when linking to pages. This will allow the domain to change and not affect your hardcoded links - assuming the ID's are the same of course. <a href="<?php echo home_url();?>/?page_id=634">Link</a> Good luck!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "links" }
getting image alt text via ACF plugin in WordPress I am using the ACF plugin in my WP 3.3.1 application and I use the `the_field` method in many places across the site. One place in particular I use it is in a slideshow/carousel as below: `<img alt="" src="<?php the_field('slideshow_image'); ?>" />` I am trying to pull in the image alt text, which I have stored in `wp_postmeta` under the `_wp_attachment_image_alt` metakey...however, i'm not sure how to access this. Calling `the_field` with "image_alt" does not work and there is limited documentation.
You need to set your ACF field to return the image object instead of the URL. You can then use the following code to retrieve the image and alt text: <?php $slideshow_image = get_field('slideshow_image'); // Check for alt text - if there isn't any, use the image title $alt = ($slideshow_image['alt']?$slideshow_image['alt']:$slideshow_image['title']); // Return full size image $url = $slideshow_image['url']; ?> <img src="<?php echo $url; ?>" alt="<?php echo $alt; ?>" /> If you want to return the image at a different size, you can use the sizes array instead of the url: // Return image thumbnail $url = $slideshow_image['sizes']['thumbnail']; Documentation here under Customized display: < EDIT: This solution works for ACF 3.3.7 and above only. Another method is to return the image/attachment ID, then use `wp_get_attachment_image()` to return the full image HTML. Documentation here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, images, post meta, html, seo" }
How to make changes on Wordpress site locally on live site? I would like to set up a System where I can clone a live website and work on it locally and then when I'm satisfied and the changes are approved, I can send or sync those changes with the live site. I'm currently watching gitHub tutorials, but I'm not sure if I'm on the right track.
To make changes in live site with local install you need to setup a synchronization system. which synchronize static files and database files. You can use Git for version control. Here is a great article for Sync A Local and A Remote WordPress Blog using version control.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "version control, workflow" }
controlling whether upload is attached to post or not I'm using the new (3.5+) media upload API to open a media modal dialog from a post meta box, and select a file from the media library (as per < I need to control whether or not files uploaded through this dialog are attached to the current post or not. I'm looking through media-views.js and can't see anything to control this. Any ideas?
Solved, thanks to this post by Mike Jolley (see 'Passing data to the uploader script').
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, attachments, media, media library" }
Where is the sticky post option? So I finally need to include sticky posts in a theme but it looks like the feature is gone. When I create a new post, and click "visiblity", the sticky option is missing. I checked a couple other sites sites (and the defualt twenty fourteen theme) and it looks like they're all gone. Is that an option I need to enable in my theme now? Also - I see that custom post types can not be "stickied" is there a plugin which will give me that feature? !enter image description here
So it looks like the problem is with wordpress capabilities. One of them, likely the "edit_posts" capability is what gives uses access to the sticky post feature. Im not sure which one, I just gave my user role ALL capabilities and it began working again.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, theme development, sticky post" }
Multisite Tables the same as Single Install? Are the tables created for each individual site/blog on Multisite the same as single? Can I do an SQL dump for each MS table and import it to a single install?
There're some special tables Codex Link in Multisite. In short: No you can't. But you can degrade to a single site install and then import them there. If in doubt, simply add a new local multisite install, import the posts there, downgrade to single site and then export/import again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, mysql" }
wp_kses_post only removes <script> tags, but not their content Is there any way to remove the `<script>` tags including their contents? wp_kses_post seems to only remove the tags, while their content remains visible on the page. Thank you
KSES is designed to prevent execution of undesired and potentially dangerous tags, not preventing display of the innerHTML. Blocking the content would require \--1 Either a custom function that used some kind of string manipulation or xmlDOM manipulation to remove content; or \--2 A function that blocked posts that contain the tag with a message why the post failed and instructions for using HTML codes to render script tag when using it in tutorials rather than as an execution tag. Number 1 may produce performance issues with its higher overhead. If optimizing performance is an issue or if the site involves heavy posting by multiple users, then #2 is likely a more feasible solution.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "wp kses" }
How to add a checkbox inside the "Publish post" widget? I'm building post to email plugin and I need to add a checkbox to the publish post widget like this one: !enter image description here My idea is to add a checkbox that says "Send this by email", and get that info inside the publish_post listener: add_action('publish_post', function($post_id) { // Was the checkbox checked? } How can this be done?
Hook into `post_submitbox_misc_actions` and print the checkbox: add_action( 'post_submitbox_misc_actions', function() { ?> <div class="misc-pub-section"> <label><input type="checkbox"> click me</label> </div> <?php }); Wrap the code in a `<div class="misc-pub-section">`, otherwise the spacing looks a little bit weird. Examples: language selector, noindex checkbox, public preview checkbox.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "actions, publish" }
Using wp_register_style to load CSS in footer? I realise you can enqueue JS in the footer using `wp_register_script` as there is a `$in_footer` parameter for doing so. However, there isn't one for `wp_register_style` it seems. Is there a way to enqueue CSS in the footer in the same way, or do I have to manually hardcode the file path in my footer.php file?
Technically styles should only be output in head and outputting them elsewhere is invalid HTML (browsers are however very lax about it and don't care much). So in best interest of standards WordPress wouldn't do something like that. Right? Right!? It does without bit of remorse actually. There is `print_late_styles()` function, running in footer that will output any queued styles that hadn't appeared in the header. So while there is no explicit way to enqueue style for footer (like for scripts), simply adding them into queue after header had passed will make them appear there. Still not too good of an idea, but it does work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "footer, wp register script, wp register style" }
How to use an associative array in post__in with WP_Query? I have stored user favorite posts in the `user_meta` table of WordPress. The data is stored in a format, for example `a:1:{s:8:"post-134";s:3:"134";s:8:"post-136";s:3:"136";}`. How can I get this in the form of an array like `array( 134, 136 )` so that I can use it in the query below. $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $query = new WP_Query( array( 'paged' => $paged, 'post_type' => 'post', 'post__in' => I WANT AN ARRAY HERE ) ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); get_template_part( 'content', 'fav' ) endwhile; wp_pagenavi(); wp_reset_postdata(); else : ?><div class="alert alert-warning">You have not faved any post.</div><?php endif;
Take a look at PHP's `array_values` function. Alternatively, you could typecast. Note that if the array is in serialized form as you have put it above, you will have to unserialize it first, in either case. $numerical_array = array_values( unserialize( 'a:1:{s:8:"post-134";s:3:"134";s:8:"post-136";s:3:"136";}' ) ); or $numerical_array = (array) unserialize( 'a:1:{s:8:"post-134";s:3:"134";s:8:"post-136";s:3:"136";}' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, wp query, user meta" }
Change standard post format metabox I added a meta box to my theme (WordPress admin) for video, image, gallery and chat, but I can't add a meta box for the standard post. When I add post type support for "Standard", the standard post format in admin is duplicated. When selecting the 2nd "Standard" from the list, a meta box is added, but it should do that for the 1st "Standard" and not show it twice. !enter image description here
The problem you are having here is that `standard` is **not** a post format. `standard` is just assigned to posts that does not have a post format assigned to it. You can also check in your db in `wp_terms`, there is no `post-format-standard` term. You can also do the following to print out a list of all registered post formats $terms = get_terms('post_format','hide_empty=0'); ?><pre><?php var_dump($terms); ?></pre><?php This is actually one flaw in the post format system. I don't know if this was done on purpose. Unfortunately, you can't add new post formats. So you can't register a `standard` post format. You will need to go and rethink your setup when adding a meta box for posts that does not have a post format assigned to it
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post formats" }
Plugin can't be activated I'm developing a WordPress plugin, but the last changes caused the plugin to stop working. It tells me that I can't activate the plugin because it caused a fatal error. On localhost all is working fine, but after sending to the server, on activation it displays the following: > Can't use function return value in write context in /data/web/virtuals/72282/virtual/www/wp-content/plugins/wp-songbook/inc/wpsongs-shortcs.php on line 83 I really don't understand the context of this message, because the code of this line is: $ytlink=(isset(get_post_meta(get_the_ID(),'songbook_video_link')))?get_post_meta(get_the_ID(),'songbook_video_link'):false; Can anyone tell me what's happened?
The root of the problem is that `isset` expects a variable to be passed to it. Also, I'm assuming that you expect the `get_post_meta()` to return a scalar value and not an array, so I added the third parameter set to true. // 3rd param: $single. Value of true means get scalar value, not an array. $ytlink = get_post_meta( get_the_ID(), 'songbook_video_link', true ); // Will ensure that $ytlink is boolean false, and not an empty string. $ytlink = ( ! empty( $ytlink ) ) ? $ytlink : false;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, post meta, errors, activation" }
How to map my php files as the files for pages How do I map my php files (like a file that is supposed to be the page "blog" and it contains all the html and php) to the actual page the html is supposed to be marking up many thanks note: I would prefer to do this using page name instead of I.D.
Use page templates, an overview can be found here: < Edit for those afraid of dying links: A page template file should be placed in the theme folder, with any name you like. In its header, it should have <?php /* * Template Name: My Custom Page * Description: A Page Template with a darker design. */ // Code to display Page goes here... In admin menu, each page will have the option to be assigned the template `My Custom Page` and this file will be used to show the page's content. As a starting point, you could copy code from page.php or if that doesn't exist, index.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, pages" }
Why isn't my link attribute getting my css? <link rel="stylesheet" type="text/css" href="style.css" /> That is the line I am using. The `style.css` file is in the same directory as the file I am running that from. Tt specifically just won’t work on my wordpress page. I am running the page via a HTML file that I am using as the template for that page. It IS getting that file because it does display the HTML elements. Just wont style them with my stylesheet. Why?
<link href="<?php bloginfo('stylesheet_url');?>"rel="stylesheet" type="text/css"/> Just Copy and Paste above code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, pages, css, page template" }
How to enable http (not just https) in wordpress? My wp-config.php file contains define('FORCE_SSL_ADMIN', false); but all my permalinks are https: by default. !enter image description here I want the site to be accessible by http. What do I need to change please?
Changed the wordpress address and siteurl in Dashboard > Settings > General
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, ssl, https" }
Google is unable to crawl Robots.txt file of my website and please help me Today I got a mail from Google webmasters, that Google bots are unable to find robots.txt file of my website. I also tried to locate the file by < but the file isn't there. Instead the message is displayed as below. "User-agent: * Disallow: /wp-admin/ Sitemap: < Please help me, I need to find where is robots.txt file located in wordpress? How to make it again crawled by Google? Or if I need to create a new robots.txt file then how to do that? And what should I do of the previous robot.txt file??
> Today I got a mail from Google webmasters, that Google bots are unable to find robots.txt file of my website. This is not actually a problem (from crawling perspective at least, it might be for excluding things from crawling, which the file primarily used for). The `robots.txt` is neither mandatory on necessary for your site to be crawled. > I also tried to locate the file by < but the file isn't there. Instead the message is displayed as below. This actually _is_ `robots.txt`. :) That is what rules in it look like. If your installation doesn't have physical `robots.txt` file than WordPress will be serving virtual one, using `do_robots()` to generate it. It is hard to say why Google wasn't to access the file (since you seemingly are able to). It might have been temporary issue that will clear itself, otherwise you might want to contact hosting and inquire if something might be interfering with Google bot accessing your site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "google, robots.txt, customization" }
Show comment pop up links as text only I'm trying to show `comments_popup_links()` function as a text only,not as a link. Is it possible to prevent it from being a link. Below snippet creates links to the comment, but I don't want it to be links. <?php comments_popup_link( 'No comments', '1 comment', '% comments'); ?>
For that matter, don't use comments_popup_link(). Use comments_number() instead. This has the same function but not linked. <?php comments_number( 'no responses', 'one response', '% responses' ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "comments" }
Removing URL and adding container around image in the featured image metabox I want to remove the url and add a container(div) around the image in the featured image metabox. Wordpress output <p class="hide-if-no-js"> <a title="Set featured image" href="URL" id="set-post-thumbnail" class="thickbox">IMAGE</a> </p> at default. I want the output to be <p class="hide-if-no-js"><div>IMAGE</div></p> Can I do this using the `admin_post_thumbnail_html` hook? How should I do this?
I am not sure why you want to do this, but you can accomplish it with preg_replace(). Try adding this to your theme's functions.php: add_filter( 'admin_post_thumbnail_html', 'remove_featured_image_link' ); function remove_featured_image_link($content) { $content_edit = preg_replace('/<a .*?class="(.*?thickbox.*?)">(.*?)<\/a>/','<div>$2</div>',$content); return $content_edit; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, post thumbnails" }
Add variable in between do_shortcode I'm using redux frmaework for my theme option panel. & I'm using meta slider for my homepage. I used this shortcode in my frontpage template to show the slider: <?php echo do_shortcode('[metaslider id=21]'); ?> but I want to change the id from my option panel, so I don't have to edit my template each time I replaced the slider with a new one. I've created a field for that in my redux config page. Now I can use this code: <?php echo $redux_demo['mslider-id']; ?> but I don't know how can I add this to my first code. I want to replace the id number "21", with this 2nd code.
I would rather pass the variable to the `id` attribute inside the shortcode. You can even decide to remove the `id` attribute inside the shortcode and make it a static value that you pass to your custom query For examples and more info about how shortcodes operate, check out the Shortcode API
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode" }