INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
making available just some parts of theme option
I'm just starting to understand and learn about how Wordpress works. Now i'm trying to build a simple website (6 pages, gallery, slideshow) by using a downloaded from wordpress.org. The theme that I'm using has slideshow support in `Theme Options` section, but I'll like to hide the fact that i'm using that theme, or to replicate its functionality.
I'm thinking that maybe I can add a custom post type, but I'm too new to wp and I'm scared. Also, I was thinking that I can use some plugins like `members` in order to block some users access to the themes, but to allow access only to theme options section. With this plugin I can only hide access to entire Appearance section.
I'm looking forward for your advice.
ps: I don't know if it really matters or not, but the theme that I'm using is `thbusiness`. | It seems like you're actually asking three questions here; it's likely your question will be put on hold because of this. Why do you need to add a custom post type?
If you're interested in learning how to develop for WP you can skip the plugin for members and instead read the WP Codex entry on user roles and capabilities; this will let you limit who has access to the theme options pretty easily.
I had a quick peek at the theme files and it looks like it's using the Options Framework to add its options. If you look inside `options.php` you'll see that `$options` consists of a multi-dimensional array. The Options Framework is pretty easy to use; simply include the necessary files and then create your options as required. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, child theme, theme options"
} |
_e() function get text_string from function
Can I print the text sring to be translated from a function for example
_e('echo text_function();', 'my_theme'); | No you can't this way. See documentation :
$echo = text_function();
printf( __( 'My string is %s', 'my-text-domain' ), $echo ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "translation, localization"
} |
Let user to add input fields on theme option page
I'm creating a Theme Option page for my own wordpress theme and I've been trying to create something like this on my option page
It means my user(admin) can add any number of input fields (in this image, they're drop down elements)
I need to add this feature as a inbuilt option page, so plugins like ACF will not work for me in this case. I have to build this from scratch.
Thanks... | You can do this by adding the following class in your theme for admin options;
Custom-Metaboxes-and-Fields-for-WordPress
And you can call your repeatable fields with some thing like this;
array(
'name' => 'Name of field',
'id' => 'prefix_option_name',
'type' => 'text',
'default' => '',
'repeatable' => true,
),
For more details on how to use this class you can go through following documentation and example code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, custom field, theme options"
} |
WP_Query search custom posts meta date fields
I have a custom post type which stores dates in a meta field as
2014-02-22 22:38:00
I can use `WP_Query` to find posts created in a certain month / year
$args = array(
'post_type' => 'custom_post',
'post_status' => 'publish',
'date_query' => array(array(
'month' => $month,
'year'=> $year,
),),
);
$query = new WP_Query($args);
How can I extend this to search a date meta field? I know you have to add
'meta_query' => array(array(
'key' => $key,
'value' => $val,
...etc...
),),
Can I search for custom posts using a date field or do I have to manually filter once I get all the returned custom posts? | See the codex re Meta Query. For example, this would get all posts at least a day old:
$date = date('Y-m-d H:i:s',strtotime("-1 days")); // 1 day ago
meta_query' => array(
array(
'key' => 'name of your key',
'value' => $date,
'compare' => '<=',
'type' => 'DATETIME',
),
) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "custom post types, wp query"
} |
feed links for custom post type pages
I have a WP based site with a lot of pages based on custom post type. But I see a lot of 404-links in the Google Webmasters finished with /feed. It looks like default WP function, when WP adds /feed to any page and this should return history in RSS format. This is good. So my question is:
How I can make ".../feed" links working and show XML for comments on these special post type pages?
For example, my real page < returns 404, when < returns a page with comments. How I can make RSS link working and returning a page with XML with comments list?
Thanks. | Finally I found a bug in CPT UI plugin. There is no rewrite_rules apply at edit form submit stage. To have rewrite_rules finally applied, I have to show "edit post type" form (without submitting it) to have edited properties actually applied.
I've also described an issue in WP blog.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "custom post types, comments, feed"
} |
How can we know we are not in edit page
I want to enqueue a JS file only to my View Page screen(after pubishing page). Whenever I click on edit this page, i want to remove that JS.
How can we do this.
`if(is_page()){
wp_register_script( 'xxx', get_template_directory_uri() . '/includes/js/slider.js', array( 'jquery' ) );
wp_enqueue_script( 'xxx' );
}`
But I am not able to get the correct solution. | Use the following code in the functions.php file at your theme's folder
function my_enqueue($hook) {
if ( 'edit.php' == $hook ) {
return;
}
wp_register_script( 'xxx', get_template_directory_uri() . '/includes/js/slider.js', array( 'jquery' ) );
wp_enqueue_script( 'xxx' );
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
The admin_enqueue_scripts action hook can also be used to target a specific admin page. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions"
} |
Custom template for different post types
I'm struggling to get my head around the correct terminology for posts/templates etc which is making it difficult to find what I'm looking for in Google/on here.
Basically, I'd like a user to be able to select from a drop down in the new post page, and this will prepopulate the posts box with a "template" the author can then fill in.
For example, if they select "Review", it'll have a space for an image, some text, a link to something like Soundcloud, and then a Star rating at the bottom.
If they select "Top 50 albums", it'll populate with 50 boxes, all ready for the user to select album art, youtube link etc etc.
Is this something that natively exists in Wordpress? Is there a plug in for such functionality or can I write this from scratch?
Appreciate any help. | I'd recommend Custom Post Types : <
You can add appropriate meta boxes to each post type : <
You can define specific front end templates for each post type : <
Instead of a dropdown, you would have distinct menu items for each "thing" ( Review, Albums, etc ). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, templates, content"
} |
Programmatically choose language for translation
I have a multilanguage website (to do it I use both Polylang and Loco Translate).
My problem is that I want to send an email to our users, but I don't know in which language to send it until I retrive the record from the DB (so I can't simply set a different WP_LANGUAGE)
This is pseudocode for what I would like to do:
$wpdb->query($wpdb->prepare("SELECT userName,language FROM wp_order WHERE id =%s",$id_order));
$result = $wpdb->last_result;
if($result){
//SET LANGUAGE FOR TRANSLATION $result->language
$emailBody= "Hi".$result->name." "._("text to translate","pluginname");
/* ... generate email ... */
wp_mail($email, $subject, $body, $headers);
} | After looking at the l10n.php I found a way to switch the textdomain using the unload_textdomain function.
So I created a simple switch
function switch_textdomain( $domain, $newLocale){
/*
This will only change the textdomain, not the locale.
It will only affect what kind of language will be used for the _e(), _(), __() commands for the $domain
*/
unload_textdomain( $domain );
/*mofile Folder
this may have to be changed depending on what you want to switch*/
$path = get_template_directory();
$mofile = "{$path}/{$newLocale}.mo";
return load_textdomain( $domain, $mofile );
}
This will not actually change the locale, but will only change the textdomain for the specified domain (your theme, or plugin).
Since in my case I only needed the translation this is good enough for me. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation"
} |
Check if post has attachments (not image)
Need to do a check if post has attachments that are not images. I haven't seen this anywhere - thoughts? | Here's how to check if the post has an attachment other than image (or other mime types):
<?php $attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => 'image'
));
if ( $attachments ) { ?>
// do something
<?php } ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 6,
"tags": "attachments, images"
} |
Wordpress unescape text on mysql?
on database i have field `desc` with value `\'test\'` actually the input is `'test'`
when i gather the field for display it on table, it show `\'test'\` not `'test'`
anyone can know how to change the value become `'test'` ? | Use stripslashes to remove the slashes. For example:
echo stripslashes( $field ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, text"
} |
How to stop permalink redirects for a particular slug
I have a large number of posts that each represent a very specific type of data. Each post title is the SKU for the data & information. Folks have become pretty savvy on the URL structure and their shortcuts (redirects) are causing them to get incorrect data. Using the wrong data is NOT a good thing in this case.
**For example, if my actual slug is example.com/esm/010HHHH**
* example.com/010HHHH redirects to example.com/esm/010HHHH (Good)
* example.com/010 could redirect to any item that starts with 010 such as example.com/esm/010AAAA (Not Good)
The preferred behavior is to simply get a 404 error for any post that is not exact for any posts that have a slug of /esm.
I have successfully solved the issue by removing the canonical filter. However, I would like the "normal" canonical behavior for any other slugs.
remove_filter('template_redirect', 'redirect_canonical'); | This seems to be working. If the URL that WP wants to redirect to has "esm" in the url, it will simply return a 404. If not, it can go on its merry little way.
add_filter( 'redirect_canonical','custom_disable_redirect_canonical' );
function custom_disable_redirect_canonical( $redirect_url, $requested_url ) {
if ( preg_match("/esm/",$redirect_url) ) {
return FALSE;
} else {
return $redirect_url;
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "permalinks"
} |
How to protect login via SSL but not the rest of the dashboard
Is it possible to have a site's login pages protected via SSL but then have it revert back to http:// for the dashboard pages? I am finding that https:// in the dashboard slows down my experience. | It is probably possible, but if you do it the security impact is like not using ssl at all unless all you want to protect is your user and password and don't care much about protecting against actual hacking into the site.
While user and password are sent only as part of the login form, an equivalent authentication information generated from them is transferred with every request you make to the site in a cookie. Since they are always sent and needed to access the admin there is no much point if you encrypt the authentication information for one page but let them to be sent in free text to other pages.
Unless specifically looking to get your user and password, the hacker that tries to break into your site by monitoring your communication does not care if he got your user and password by intercepting the login info on the login page or by intercepting the cookies on a post edit page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ssl"
} |
URI rewriting: handling one page
Here's what I'd like to do: make Wordpress think that my _page_ called "`toto`" can be called from "`/toto`" but also from "`/toto/{alphanum char}`"
I dont want to make a special rewrite rule, because I dont want to touch the "`.htaccess`" file.
Is there a way to do this in Wordpress? | You HAVE TO add a rewrite rule to WordPress. That can be done withou touching .htaccess. For example:
add_action('init', 'cyb_rewrite_rule');
function cyb_rewrite_rule() {
add_rewrite_rule( 'toto/([^/]+)/?$', 'index.php?pagename=$matches[1]', 'top' );
}
If you need access to the second part of the URL as query var, you can do this:
add_action('init', 'cyb_rewrite_rule');
function cyb_rewrite_rule() {
add_rewrite_rule( 'toto/([^/]+)/?$', 'index.php?pagename=$matches[1]&secondpart=$matches[2]', 'top' );
}
add_filter('query_vars', 'cyb_add_vars');
function cyb_add_vars($vars) {
$vars[] = 'secondpart';
return $vars;
}
Now "secondpart" is available in the query vars pool and you can access to it using WordPress funcions. For example, imaging you have this URL: "mysite.com/toto/apple"
if( get_query_var( "secondpart" == "apple" ) ) {
//It matchs
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting"
} |
How are the HTML classes generated?
I've just created a "full-width" template page for my theme, allowing me to set the width of the site content to maximum if there are no sidebars active.
What I've noticed is that this gave me a HTML class ".full-width" to work with in CSS. How did this class get generated? It seems to be terrifically connected with the fact that I named my template "full-width.php" | By default WordPress adds lots of CSS classes in body tag automatically. These body classes are very useful for styling different sections/pages of site without needing to edit theme files unnecessarily.
For example WordPress add `home` CSS class on website front page and `blog` class on blog posts index page.
Similarly in your case, since you are using a custom page template for a page, WordPress added file name CSS class in body tag.
You can read more about `body_classes` in codex and a brief list of all CSS classes added by WordPress. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates, html"
} |
Multiple TinyMCE editors in dynamically generated textareas
I have text-areas dynamically populated in the admin section of my custom post type.
<div class="media_div">
<span>Media</span>
<input type="text"
class="meta_media"
name="media_desc[]"
value=""
/>
</div>
I then loop through the $_POSTS when saving the meta values, hence using `[]` in the name. The codex says only `lowercase` and `_` can be passed to wp-editor.
How can I use wp-editor for these dynamically generated text areas?
wp_editor($ID, 'media_desc[]'); | The second parameter to `wp_editor` is the value that the "id" attribute of the textarea element will have, and that is probably why there are such restrictions on it. By default it is also used for the "name" attribute but you can set it explicitly by using the `$settings` parameter to `wp_editor`
`wp_editor($ID, 'media_desc_n',array('textarea_name' => 'media_desc[n]'));` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, tinymce"
} |
Add bcc to contact from on wordpress
I found a script for making your own contact form in your wordpress site (without plugin) Now, I want to add more clients email accounts as a BCC or CC. how can I do that?
This is me code which define the email address:
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = '[email protected]';
}
Thanks | If your code uses `wp_mail` function to send emails, then you can specify multiple recipients using an array or a comma-separated string.
So your `$emailTo` will be..
$emailTo = array(
'[email protected]',
'[email protected]',
'[email protected]',
);
If your code does not use `wp_mail` function then you can define multiple instance of PHP mail function.
To BCC and CC with `wp_mail`, you must use the `$headers` argument. If it's not already defined in your `wp_mail` then here is a simple example.
$headers[] = 'From: Me Myself <[email protected]>';
$headers[] = 'Cc: John Q Codex <[email protected]>';
$headers[] = 'Cc: [email protected]';
Although adding email addresses with array (first code) will work just fine, and unless you have a good reason to use BCC/CC headers, you should use it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, php"
} |
List attachments of a page
I need to generate a list of attachments uploaded to a specific page (id=628). I thought this code was going to work, but it doesn't generate anything at all:
<?php
get_header(); ?>
<div id="container">
<div id="content" role="main">
<?php
$attachments =& get_children( array (
'post_parent' => 628,
'post_type' => 'attachment'
));
if ( empty($attachments) ) {
// no attachments here
} else {
foreach ( $attachments as $attachment_id => $attachment ) {
echo wp_get_attachment_link( $attachment_id );
}
}
?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Any idea how I can get it to work? | The problem was that the files wasn't attached to the post. To make it work I re-attached the files (Media Library > Attach). I also removed the `&` in `$attachments =& get_children( array (`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "attachments, archives"
} |
Querying with WP query using meta key price
Could somebody tell me what's wrong with my WP query please? I'm trying to order my posts by price and price is an ACF (a textbox which has a number in it)
$args = array (
'post_type' => 'product',
'post__in' => $post_ids,
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => 'tour_price',
'meta_query' => array(
array(
'key' => 'tour_price',
'compare' => '=',
'type' => 'NUMERIC',
)
),
); | `'meta_value_num'` \- Order by numeric meta value (available with Version 2.8). Also note that a `'meta_key=keyname'` must also be present in the query. This value allows for numerical sorting as noted above in `'meta_value'`.
Try to use like this :
$args = array (
'post_type' => 'product',
'post__in' => $post_ids,
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'meta_value_num',
'meta_key' => 'tour_price',
'meta_query' => array(
array(
'key' => 'tour_price',
'compare' => '=',
'type' => 'NUMERIC',
)
),
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, order"
} |
Is back-end access not required for an app to post to my blog?
I've recently installed a couple of apps (WordPress and BlogPad Pro) and I'm a bit surprised to see that they can indeed post to my blogs, even though I haven't given them the renamed login and wp-admin pages that I set up through iThemes Security.
My understanding was that posting could only happen "through" the back end of the blog; i.e. if you couldn't log into the blog through the login page, you couldn't post to the blog either. But evidently, with my username and password, these apps _can_ post to the blog.
How does the app know to get "around" the obscured login page to post to the blog? | Clients typically use XML-RPC Support.
If you take a look at your page source you will likely see endpoint declaration:
<link rel="EditURI" type="application/rsd+xml" title="RSD" href=" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href=" />
Apps are using this information and your credentials to access the site. In this way they can either discover location of admin or work without it altogether via XML-RPC. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "login, posting, third party applications"
} |
modifying title (in dashboard) for different widget instances
When I insert multiple instances of widget in a particular sidebar, they all appear by default collapsed and with the same title. E.g.:
!Multiple Widgets with the same title
In this case, the user can upload a different pic to each widget, and reorder them as they want. It's not very user friendly having to click to open each one to see if its the one that they want to remove/edit/change of place.
With the form() method of the widget we can change whatever is shown once opened, but the "<div class="widget-title">" and its corresponding "<h4>" are out of bounds.
Is there any filter or action that allows to edit what happens there and insert some instance specific information? E.g.: "Graphic Ad: Foobar". | I believe if you add 'title' field to the `form()` (and `update()`) method this will be displayed in the admin interface. Traditionally this would also be used in the `widget()` method, but is not required.
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = strip_tags($instance['title']);
?><p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p><?php
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, dashboard"
} |
Translations does not work with .pot file
I've created a theme at underscores.me and it seems it is multi-language ready.
There is a `.pot` file in the language folder, so I downloaded POEdit and translated the things in there (like `Posted on`, `Edit`, `1 Comment`, `x Comments` and so on)
Are the above posted words not from the theme but from Wordpress? If so, why it is in English although I have a German Wordpress installed (Backend is in German)?
So I saved it and also as a `.mo` file and uploaded both files on my server into the languages folder. But the translations are not working | When naming your `po` and `mo` files in a theme, you need to only make use of the language code to name these files. Any other convention will not work
For example, my blog is in Afrikaans and the localization language code is `af_AF`. My `mo` and `po` files are named accordingly, ie, `af_AF.po` and `af_AF.mo`
I'm not sure what the codes are for German, but change the filenames accordingly | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "multi language, translation"
} |
Find custom post type url by author
In my blog (multi authors) I have posts and a custom post type named (listing_type).
In the site an author can have only 1 listing and many blog posts, and I need to find the listing url published by that author.
Example:
single-listing.php lists all blog posts (post) by the author
each blog post must contain a link to the listing (listing_type) published by the same author.
The main problem is that the listing url varies and I don't have a clue on how can I do this, any help?
Thanks! | Query for post type `listing_type` and author ID within your loop:
$args = array(
'post_type' => 'listing_type',
'author' => get_the_author_meta( 'ID' )
);
$listing_post = new WP_Query( $args );
if( $listing_post->have_posts() ){
while( $listing_post->have_posts() ){
$listing_post->the_post();
the_permalink();
}
}
// reset $post global to original value
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, author, multi author"
} |
Dynamically add content to an existing widget area
I have an existing widget area / sidebar. Rather than adding content to it via Appearance ? Widgets in the Dashboard, I want to inject content into the widget area from functions.php.
Is there hook that allows this?
Thanks :) | Yes by using `widget_text` inject content into the widget area
Add the following code into your function.php file
function widget_content( $content )
{
// add $content as you want
return $content;
}
add_filter( 'widget_text', 'widget_content', 99 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "widgets, hooks, sidebar"
} |
strong tag not working in WordPress 4.0.1
I want to display some content in my post as strong text. so i am change the content with WordPress WYSIWYG Editor but it not display as BOLD text only displays like normal text | Hey Define bold and strong in your style.css file like this
b, strong {
font-weight: bold;
}
then it display bold | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wysiwyg"
} |
How can I add a class to a nav menu when I'm viewing a child page?
I'm using bootstrap in my theme, so I have a requirement that I add a class of `active` to the current nav menu item.
I was able to achieve this by using the `nav_menu_css_class` filter
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
if( in_array('current-menu-item', $classes) ){
$classes[] = 'active ';
}
return $classes;
}
The problem is, say the current page is 'about' -> 'locations'
then the 'about' nav menu looses its 'active' class because obviously it is no longer the `current-menu-item` but I also need it to have the 'active' class if I'm viewing one of its child pages
How would I go about solving this? | I figured out a way.
I changed the if statement to
if (in_array('current-menu-item', $classes) ||
in_array('current-page-ancestor', $classes)) {
$classes[] = 'active ';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
Get The Post Type A Taxonomy Is Attached To
Being given a taxonomy or term, is is possible to pull any / all post types the taxonomy is attached to?
For example, knowing the built in taxonomy `category` or being given a term in the `category` taxonomy, is there a function to reverse engineer that `category` is a taxonomy of `post` ?
**Unneeded Info**
I'm working with some custom fields in taxonomy terms that specifically need to know the post type, but if the post type parameter in the URL isn't there for whatever reason I run into trouble. | If we peek into the global `$wp_taxonomies` variable we see the associated object types.
There might be better ways to do this or even core functions, but you could try the following:
function wpse_172645_get_post_types_by_taxonomy( $tax = 'category' )
{
global $wp_taxonomies;
return ( isset( $wp_taxonomies[$tax] ) ) ? $wp_taxonomies[$tax]->object_type : array();
}
then for the default setup you get:
$out = wpse_172645_get_post_types_by_taxonomy( 'category' );
print_r( $out );
with the output:
Array
(
[0] => post
) | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 14,
"tags": "custom post types, custom taxonomy, terms"
} |
Send Admin Emails to Multiple Email Addresses
Is there a hook that would allow me to email multiple email addresses for the default admin email notifications?
I was hoping I could build an array:
$adminEmails = array('[email protected]', '[email protected]');
Then have all admin emails (like new user notifications) sent to $adminEmails
Possible? | Try this:
update_option( 'admin_email', '[email protected], [email protected]' );
Note that the value is a string; open and close quotes only! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "admin, email"
} |
get_thumbnail_id returns full size image
I want a thumbnail of the featured image of the posts as a URL. So I'm using the following code to get a smaller size of the featured image.
$post[$i]['thumbnail'] = wp_get_attachment_url(get_post_thumbnail_id($post[$i]['id'], 'thumbnail'));
However all the time it returns the full size image, I even tried,
$post[$i]['thumbnail'] = wp_get_attachment_url(get_post_thumbnail_id($post[$i]['id'], array(120,140)));
But still it returns the large image. How can I fix this? | Hey First add this line into your function.php file
add_image_size( 'custom-size', 120, 140 );
Then call custom-size like this
<?php $thumb_id = get_post_thumbnail_id( $id );
if ( '' != $thumb_id ) {
$thumb_url = wp_get_attachment_image_src( $thumb_id, 'custom-size', true );
$image = $thumb_url[0];
}?>
<img src="<?php echo $image;?>">
I think it work fine | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "post thumbnails"
} |
Alter a specific query on Wordpress
I need to change a query of a plugin that is **not** the main query. The author did not put any filters. I can see the query from
$wpdb->queries
Is there a way to access the specific query and replace what I need? If you need further info I will gladly provide. Thank you in advance.
**Edit** As requested:
There is a class eg. MyClass Inside there is a function eg myfunction
myfunction has
$event_obj = $wpdb->get_results($querystr, OBJECT);
Can I alter $querystr ?
**EDIT #2**
I believe I am getting somewhere (after 4 hours).
add_filter('query', 'spyros_query');
function spyros_query($query) {
if (strpos($query,'what_only_this_query_will_contain') !== false) {
return false; // for testing purposes
}
return $query;
}
** EDIT #3 (the full query) **
<
Regards,
Spyros | You might be able to use the `query` filter hook
See this WPSE answer
Basically, you can do something like:
add_filter( 'query', 'your_filter_function' );
function your_filter_function($query_sql) {
// do something to $query_sql
return $query_sql;
}
This will get called for _every_ query, so you'll need to test `$query_sql` to make sure it's the query you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "query, wpdb"
} |
how to add number value in front for variable
Hi there my question is very simple, is there a way by which we can add a value in the end of the variable a numeric value.
like we have a variable
$tota
$tota1
$tota2
$tota3
each have different value what I want here is to use a function that first write 1 in front of variable
something like
echo $tota . 1 ;
But its not working the php taking 1 as a different entity.
please note array is not a option I can use I want above function as describe. I don't want whole function I just want a technique that add number after variable. | Its Very simple you can implement like this
${variable_name}.another_varibale;
For Example
for($i=1;$i<10; $i++)
{
${total}.$i = 10+$i;
}
for(j=1;j<10;j++
{
echo ${total}.$i;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, variables, code"
} |
Force HTTPS 301 redirect with hook
I am trying to force a 301 https redirect with hooking into the 'template redirect' function. I want not doing it a htaccess because when I update my permalinks, htaccess with https redirect disappears.
So with this function I want to do a redirect if the url is loaded with 'http', but nothing happens. Is there anyone who can help me with this?
add_action( 'template_redirect', 'bhww_ssl_template_redirect', 1 );
function bhww_ssl_template_redirect() {
if ( is_ssl() && !is_admin() ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_redirect( preg_replace( '|^ ' $_SERVER['REQUEST_URI'] ), 301 );
exit();
} else {
wp_redirect( ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit();
}
}
} | We can add https in very simple way.... No need to had code all these in any hook....
1. Log in to wordpress admin
2. Go to Settings > General
3. Find WordPress Address (URL) and Replace HTTP with HTTPS
4. Find Site Address (URL) and Replace HTTP with HTTPS
5. Click **Save Changes**
Edit .htaccess file and add bellow code
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^huepixel\.com$ [NC]
RewriteRule ^ [L,R=301]
Install wordpress-https Plugin and configure it....
That's All | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, hooks, redirect, template redirect"
} |
featured image metabox not showing on the default post types edit page
I can't get the Featured Image metabox to show up on the edit page for the default `post` and `page` post types.
Though as opposed to this question, it _does_ work for the custom post type I've created using a plugin. It just doesn't work with the default ones.
I've read the Codex Article on Post_thumbnails.
Added the following line to the current theme's `functions.php` and to that plugin I was working on:
add_theme_support( 'post-thumbnails', array( 'post', 'page' ) );
Also been checking the screen options on the top right of the edit page and the checkbox for the Featured Image is not even there.
Where do I check to see if something else does not overwrite that? Please help | By default post types "post" and "page" do have support for featured image meta box. You don't need to add some thing in function.php for that. This might be happening due to some plugin confliction.
I would suggest try deactivating your plugins one by one and check if it gets back. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails"
} |
Custom urls in WordPress involving page slugs
I have a page called 'Cars' with slug `cars`. Is it possible that the page works as normal at this URL ` and ` can be used to show something some special content that is not a child-page but from a custom php file.
Can I add URL rewrite rule like this `add_rewrite_rule('^cars/([^/]+)/?','index.php?make=$matches[1]','top');`
I'm trying it but it doesn't work stucks in a redirect loop, looks like WordPress is trying to find a child-page may be, I could be wrong. | This exact piece of code works, the reason for redirect was some other plugin.
To create as many child pages you want dynamically you just need to this just hook it to 'init' hook.
add_action('init','my_custom_rewrite_rules' );
function my_custom_rewrite_rules(){
add_rewrite_tag( '%make%', '([^/]+)' );
add_rewrite_rule('^cars/([^/]+)/?','index.php?make=$matches[1]','top');
//or To go to a published page.
add_rewrite_rule('^cars/([^/]+)/?','index.php?pagename=page-slug&make=$matches[1]','top');
}
If you want to use a custom file just do this
add_action( 'template_redirect', 'myown_cars_display' );
function myown_cars_display($template) {
if ( $make = get_query_var('make') ){
include('templates/cars-make.php' );
exit;
}
}
Don't forget to flush the rewrite rules, just open the permalinks page in settings and you are done. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Embedded Videos (PB) - Not Available
I am using this link to create a wordpress website VIDEO At minute 53 the guy is using "Embedded Videos (PB)" widget in order to embedd a youtube video. (By the way he is using Page Builder). Problem is - that widget is not available in the wordpress. Where can I find it, or is there any other way I can embed the youtube video in the page with Page Builder???
And I am using Vantage Theme. | Go to Settings -> SiteOrigin Page Builder.
Enable "Bundled Widgets" and save settings.
Embedded Videos (PB) should be available now. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, widgets"
} |
How to display page content and a list of posts on the same page?
I was wondering if there is a way to display the page content and a list of posts from a specific category on the same page in my wordpress blog using a template.
I have a child theme set up, but don't know anything about the wordpress page structure. All of my attempts to achieve this have been unsuccessful so-far.
If someone could help me out that would be great! | php file add the following code snippet
<?php get_header(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_title( '<h1>', '</h1>' ); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
<?php
$post = array(
'post_type' => 'post',
'order' => 'ASC',
'post_status' => 'publish'
);
$loop = new WP_Query( $post ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php the_title( '<h1 class="text-center">', '</h1>' ); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
<?php wp_reset_postdata();?>
<?php get_footer(); ?>
it help you to show the all post after the page content | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "templates"
} |
How to add WordPress Settings in sidebar widgets
Is it possible to insert the Site Title in a widget text box?
I tried `<?php wp_title(); ?>` but nothing displayed. | The _Text Widget_ does not parse PHP - it even strips it.
You either could use a widget that is capable of parsing/interpreting PHP, such as the PHP Code Widget, or you could develop your own widget.
Here is a **very** simple example of how this could look like:
class WPDev172911TitleWidget extends WP_Widget {
public function widget( $args, $instance ) {
wp_title();
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp title, widget text"
} |
What's the proper way to include inlined javascript-source?
I'm making a theme where I'm including a javascript-lib which wants to be loaded/instrumented with a potion of generated code at `document.ready()`-time. Generated because some theme-options are influencing the behaviour.
I properly load the `.js` of the lib with `wp_enqueue_script()`. Now I need a proper way to put the the javascript-code below the script.
I found a way which suggests to change `header.php` to include the code after the call to `wp_head()`.
I think my question is, is there a way to add js-code so that the call to `wp_head()` includes at in the right place? Is there a `wp_enqueue_script_code()`? | To print JavaScript code to your page, you have several paths to choose from. The most obvious would be the `wp_footer` action. Just hook a function to it and make it print your JavaScript/jQuery code, wrapped in `<script />` tags.
**// EDIT**
As an addition, if your custom JavaScript/jquery code is static (i.e., there are no dynamic parts in it), you should put it in a separate JS file and enqueue it with the lib as dependency. But you explicitly asked for printing so that's what I answered.
As for your comment, as long as your code doesn't have to be executed before the page has been rendered--which doesn't seem to be the case, according to your question (`document.ready`)--this is just best practice to enqueue script files in the footer. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, javascript, theme options"
} |
Which PHP files should I edit for changing POSTS list and view pages?
Iam totally new to WP but now I got a situation to integrate blog in my magento store for that Iam using WP-Blog now I need to edit `blogs posts List page` and `posts view page` I want o do this by editing `.php` files but I cannot understand WP structure and cannot find the exact files which are related to posts.please help me in acheiving this
Thanks in advance | Depends on how your theme is built. I strongly recommend that you read Theme Development and Template Hierarchy
Based on your comment, I would start with: `single.php`, `index.php` and `comments.php` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts"
} |
Featured images get shrunken
While uploading featured images, the problem I am getting is, all images are shrinking automatically.
I want to retain the original image. Check this example. All staff memebers images are shrinked automatically but in featured images I have uploaded a full image of staff members.
I thought that images are too large so that wordpress is automatically shrinking the images, so, I have scaled and cropped the images in media library. Some of the images got fix but some remains the problem.
Is there a way that the orignial uploaded image will be shown as it is? | Hey if you want to add custom image size then add the following code in your function.php file
add_image_size( 'thumb', 220, 180, true );
and then call featured image in your template like this
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail('thumb');
}
?>
i think it will help you | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "media library, images"
} |
Assign automatically and manually modify category
I assign automatically a category to a post when published. But how can i modify this category in admin?
function add_bookcategory_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$bookcat = array (4 );
wp_set_object_terms( $post_ID, $bookcat, 'category');
}
}
add_action('publish_post', 'add_bookcategory_automatically');
For example, now the new post has category with id 4, but i can't change or add category in admin. Every time i save the post, category back to 4 id. How can i modify function? | Well, what is the expected behavior? You use `wp_set_object_terms` and pass just a single term.
If you want to make sure the specified term is assigned to the post, while being able to add as many other terms as you like, try it like this:
function add_bookcategory_automatically( $post_id ) {
if ( ! wp_is_post_revision( $post_id ) ) {
$bookcat = 4;
wp_add_object_terms( $post_id, $bookcat, 'category');
}
}
add_action( 'publish_post', 'add_bookcategory_automatically' );
See `wp_add_object_terms`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
Conditional tag search-no-results
Is there a way to make a conditional tag that tests if it is `search-no-results` page?
I know that there is a function to check if `is_search()` page:
if(is_search()){
echo "search page";
}
But I didn't found a way to check for search-no-results, and I noticed that WordPress gives body class with `search-no-results` to this page. | There is no conditional tag for no results on a search page, but you can create yourself one.
You basically just have to check the value of `$wp_query->found_posts`, if it is `0`, returns `false`, any other value, returns `true`
function is_search_has_results() {
return 0 != $GLOBALS['wp_query']->found_posts;
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "search, conditional tags"
} |
Insert Latest Articles in Homepage
How can I insert the latest articles (blog) on top of the homepage?
I intend with the release of the latest items with image and brief summary of the article.
I made an example (in the attached image) of I intend to do.
.
ps: I'm a beginner, please be patient and simple.
Thanks!! | Edit the home page template and add the following code :
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '1' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
I have used `<UL>` and `<li>` to list post.... You can use your own html & css to style.
You can use different wordpress functions, One I have used is `get_permalink()` to get the post URL, similarly you can use `get_the_post_thumbnail()` to get the featured image of the post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "homepage, blog"
} |
add taxonomy as one of menu items
I have created a custom `Taxonomy` called Documents and I want to show it as one of menu items, I am only able to choose from its posts. How shall I do that?
As below picture I am not able to choose Documents itself as a menu item...
!enter image description here | Finally I was able to find a way to do exactly what I wanted. Though adding **Custom Taxonomy** or **Custom Post Type** can easily be added, while having its **Template** file, as following:
Appearance> Menus > selecting Links widget > putting link of custom post type or taxonomy `
But also this answer help you to have a widget for your custom post type and taxonomy to select from them. The code there is for custom post type, but after working it around, it is now working for me as I had many custom post types and taxonomies. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, menus"
} |
How to link theme fonts directory in WordPress CSS?
So I installed WordPress locally and I'm on theme-development. I'm having a problem in linking my font files in my CSS. Is there any alternatives or best practices on how to link font files in a theme folder in WordPress? | If your theme's folder structure is similar to the following:
my-theme
|- index.php
|- style.css
|- fonts/font-name.ttf
|- inc/some-file.php
then the code to connect the font files in your `style.css` will be:
@font-face {
font-family: 'Font Name';
src: url('fonts/font-name.ttf');
}
body{
font-family: 'Font Name', sans-serif;
}
There shouldn't be any problem! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css"
} |
Is there any filter to trigger as soon as media is uploaded to post or page?
I am new to WordPress. I want to change attributes of image when uploaded to page or posts. Is there any filter for it? Thanks in advance. | Try to use, `image_send_to_editor` . Here is the link, image_send_to_editor | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "filters"
} |
Short website link for all post
I have web site and we need to short link of any post from
> www.thearoundtheworld.info/poas-name-title
to
> www.at.li/kfd
How can I do that | The the easiest way to create shortlink is by using Jetpack Plugin developed by Automatic guys.
This plugin comes with a lot of modules one of them is `wp.me` shortlink, which will give you the ability to create shortlink for any page/post/custom post in your site.
it will be like ` but if you want to use any other shortlink service `bit.ly` or `j.mp` you can use WP Bitly
Hope this helps. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -5,
"tags": "links"
} |
Show Wordpress Menu On External Site
So I have been working on a site using the theme Vantage and I am wanting to take the menu from the site and embed in another site in a subdirectory below, I have searched all over the internet trying to find someone who maybe have tried to do something like that but am unsuccessful so I am coming here. Could anyone please tell me how I might be able to do this?
Thanks in advance! | There's a couple ways to do this. One way might be to create a file on your web server, load up WP (so you can use its functions) and have it spit out the menu you want at a certain URL, like:
In that file you'd do something like:
<?php
include( './wp-load.php' ); // load up WordPress
wp_nav_menu( array ( 'menu' => 'whatever' ); // spit out a menu called 'menu'
?>
Then on the other site, you'll want to get the output of that file like:
<?php echo file_get_contents(' ?>
That'll spit out the menu where you need it on the second site.
To get it to look right, you'd also have to bring some markup and styles from the other site but that's the gist of it.
Related: wp_nav_menu(); Outside WordPress installation | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "menus, sub menu"
} |
Installing Jplayer in Wordpress
First, I would like to use Jplayer in Wordpress. I know that probably the procedure is very simple, but as I don't have much experience in WP, I'm having trouble.
The installation consists in tree steps (please check the link):
1. Upload the jPlayer plugin
2. Include jQuery
3. Include jPlayer
1 is OK. I think I can skip 2, because I read that jQuery is already included in WP. Is this right? 3 confuses me a little bit. Should I put the code in theme's head.php? | After uploading the plugin file to a directory inside your theme, you will want to enqueue the plugin file in functions.php
You should already have a similar function in your functions.php file, but if you don't yo can add it. Change false to true if you want the file to load in the footer instead of the header. In this example I put the file inside a folder named 'js' inside my theme folder.
//Enqueue scripts
function register_scripts() {
wp_enqueue_script('jplayer',get_template_directory_uri().'/js/jquery.jplayer.min.js',null,'1',false);
}
add_action('wp_enqueue_scripts','register_scripts');
//Enqueue styles
function register_styles() {
//($handle, $src, $deps, $ver, $media)
wp_enqueue_style('main_style',get_template_directory_uri().'/style.css?v=1',null,'0.1', $media = 'all');
}
add_action('wp_enqueue_scripts','register_styles'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins"
} |
Plugin Development - Functions or Hooks?
I am brand new to WordPress plugin development and have a few questions, mostly about best practices but also some specifics.
Essentially I just want to trigger an action (invoking a PHP class and calling a method) whenever the following happens:
* A post is published
* A page is published
* A comment is added
This will be site-wide, so no need to key in anything specific just yet. I know in the past people had used the add_action() function but that is now deprecated so any insight on best practices and how to accomplish the above would be much appreciated. To get started I am using: < just to ensure I have proper structure, etc. | Below I've included two hooks you _could_ use. There may be better hooks depending on what you're trying to accomplish exactly but this is what you've asked for. At the bottom I've listed some helpful resources:
**Publish Post Hook**
<
function published_post( $ID, $post ) {
if( $post->post_type == 'post' ) {
...
}
if( $post->post_type == 'page' ) {
...
}
}
add_action( 'publish_post', 'published_post', 10, 2 );
**Comment Post Hook**
function maybe_published_comment( $ID, $approval_bool ) {
...
}
add_action( 'comment_post', maybe_published_comment, 10, 2 );
**Resources**
1. Action Reference
2. Developer Reference
1. WP_Publish_Post()
2. Comment Post Hook | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, functions, hooks, actions, customization"
} |
Different structure/content for posts from a custom post type
I've a CPT: **Services** and created two posts underneath it. Now, both those posts have some static content which is different in structure and design from each other. How do I place that content in my `single-services.php` so that it gets showed up for the appropriate posts?
I have a vague idea of putting the two posts under separate categories or create a custom taxonomy but don't know how do I proceed after that or is there a completely different and easier method to achieve this? | WordPress allows to do this rather neatly for pages, supporting `page-$slug.php` and `page-$id.php` templates in hierarchy. Unfortunately it doesn't apply to posts and Custom Post Types.
So your options are either handling this inside `single-services.php` (in one file, or by further including other template files) or adjusting hierarchy to use custom templates for your posts as needed. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, posts, custom taxonomy"
} |
How to add class to the last image of the last post in a loop
ok, I'm creating a portfolio page, I want add a class to my last portfolio thumbnail. currently I have a class added to the div of the last portfolio item. I want to add it to the thumbnail, not the div itself.
my code:
<?php $args = array( 'post_type' => 'portfolio', 'order' => 'ASC');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="testing_imran<?php echo $loop->current_post + 1 === $loop->post_count ? ' imd_last' : '' ?>">
<?php the_post_thumbnail( 'thumbnail', array( 'class' => 'main-image portfolio' ) ); ?>
</div>
<?php endwhile; ?>
I want that "imd_last" class added to the post-thumbnail not the div. how can I do it? by the way, the thumbnails have a class attached as you can see, I just want to add an extra class to the last thumbnail. !enter image description here | Why don't you use CSS pseudo attributes for that. You can simply use `:first-child` and `:last-child` to target first and last element for CSS styling.
Here is how you do that with CSS pseudo attributes.
div.post:last-child div.testing_imran img {
your styles for last image
}
Also FYI, your code will work too, if you want to target last image in CSS file. You don't really need to add CSS class to image itself, but adding CSS class to div container will work fine too.
div.testing_imran.imd_last img {
your styles for last image
}
If you want to targe image in jQuery, then same rules work for jQuery too. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "loop"
} |
Wordpress Site in Multiple Languages
How can wordpress site have multiple languages options? I would like to have my wordpress site in 3 different languages? How can I do that? Is there any plugin or widget I can use for that purpose? | Best free plugin for your goal is Polylang:
<
Not so great but still easy to use is mqTranslate, which is a fork of the pretty popular qTranslate:
<
A good popular (but paid) one is WPML:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugins, multi language, language"
} |
Need to add class to first element in a foreach loop
I'm pulling all attachments for this particular post and displaying them in a carousel. Problem is I need to give the first item a class of active so bootstrap carousel will work.
Here is my loop:
<?php foreach ( $attachments as $attachment ):
$description = $attachment->post_content;
echo '<div class="item" data-description="' . $description . '">';
echo wp_get_attachment_image($attachment->ID, 'large');
echo '</div>';
endforeach;
?>
I've tried:
<?php $isFirst = true; ?>
<?php foreach ( $attachments as $attachment ):
$description = $attachment->post_content;
echo '<div class="item' . $isFirst ? ' active' : '' . '" data-description="' . $description . '">';
echo wp_get_attachment_image($attachment->ID, 'large');
echo '</div>';
endforeach;
?> | **Use below code**
<?php
$isFirst = true;
$i=1;
foreach ( $attachments as $attachment ):
$description = $attachment->post_content;
if($i==1)
{
echo '<div class="item'.$isFirst.'" data-description="' . $description . '">';
echo wp_get_attachment_image($attachment->ID, 'large');
echo '</div>';
}
else
{
echo '<div class="item" data-description="' . $description . '">';
echo wp_get_attachment_image($attachment->ID, 'large');
echo '</div>';
}
$i++;
endforeach;
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop, php, twitter bootstrap"
} |
How to change hover color on bulk-action-selector-top and bottom on wordpress admin?
i want to change this hover color
!enter image description here
i tried via css:
#bulk-action-selector-top{
color:#FFF;
}
but this not working. How to change it? thank you | Sorry to disappoint you, but there is no easy way to do it and no possible way with css.
Here is a similar thread in StackOverflow, that has the issue discussed:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
How to display html code on homepage
I have some HTML code wrapped in a div tag that I'd like to place on the homepage.
Because I use a static page for a homepage, I'm guessing I should use is_front_page() and I should place the desired code in footer.php
This is what I have now in footer.php (just the snippet we need):
<?php>
if (is_front_page())
{
//div html here
}
?>
</body> </html>
What am I doing wrong here? Should I use echo in the php? Or should I use an OR statement in the IF (is_home OR is_front_page) | if you are just trying to put HTML inside PHP, just close PHP and wrap with HTML
<?php if ( is_front_page() ) { ?>
<div>
HTML Code
</div>
<?php } ?>
And use is_front_page | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, homepage"
} |
Create custom field on post draft or publish?
How to automatically create custom field on post draft or publish with one of several offered values? For example I wish to create custom field named "random_color" with one of potential values: "white", "green", "blue"...
Any of values is acceptable, so how to create function which will create post custom field with one of values (randomly chosen from defined) on post draft or publish?
I found this, it is working, it creates "random_color" custom field on post draft with value "blue". How to make it randomly chose one of other values like, white, green?
add_action('draft_post', 'add_custom_field');
function add_custom_field($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
add_post_meta($post_ID, 'random_color', 'blue', true);
}
} | Add an array and choose one for the value.
add_action('draft_post', 'add_custom_field');
function add_custom_field($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$colors = array('white', 'green', 'blue');
add_post_meta($post_ID, 'random_color', $colors[array_rand($colors, 1)], true);
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "custom field, post meta"
} |
wp editor formatting
I am writing a plugin and have this code:
$settings = array("media_buttons" => false, "wpautop" => false, "teeny" => true);
wp_editor("", "viddesc", $settings);
The problem is when I paste this in wp editor:
<span class='infoTitle'>Nulla mauris justo</span>
And save it, it becomes this:
<p><span class='infoTitle'>Nulla mauris justo</span></p>
Is there a away to avoid adding p tags and converting <> characters?
Thank you. | If you use Text editor, instead of Visual editor, you will add exactly the html code you wanted to add there. It has nothing to do with the PHP code you mentioned, just html from visual editor is transformed in the way you get it later (< and > and so on). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp editor"
} |
Show custom field on attachment page?
I use this code to show custom field value outside loop on post page (single.php):
<?php echo get_custom_field('my_custom_field'); ?>
But, that is not working on attachment page (image.php). How to show post custom field on attachment page (image.php template)? | If this is related to your other question then the custom field is attached to the post and not the attachment. You need to get the post ID of the post first then you can get the custom field. This should work.
global $wp_query;
$attachment_id = $wp_query->post->ID;
$parent_id = get_post_field('post_parent', $attachment_id);
echo get_post_meta($parent_id, 'my_custom_field', true); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, attachments"
} |
Show post tags on attachment page?
I use this code to show post tag(s) on single.php template:
<?php the_tags('<div>Tagged with:<br> ',' | ','</div>');?>
I wish to display post tags on attachment page too, but code above shows nothing on attachment (image.php) template.
How to display parent post tag(s) on attachment page (specially on attachment page of post featured image)? | This should work to get the parent's tags.
<?php
global $wp_query;
$attachment_id = $wp_query->post->ID;
$parent_id = get_post_field('post_parent', $attachment_id);
$parent_tags = wp_get_post_tags($parent_id);
$tag_count = count($parent_tags); // Counting the tags to find know the last one so there is no pipe
$i = 1; // Setting up the count
if ($parent_tags) { ?>
<div>
Tagged with:<br />
<?php foreach ($parent_tags as $tag) {
if($i < $tag_count) {
echo '<a href=' . get_tag_link($tag->term_id) . '>' . $tag->name . '</a> | ';
} else {
echo '<a href=' . get_tag_link($tag->term_id) . '>' . $tag->name . '</a>';
}
$i++;
} ?>
</div>
} ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "tags, attachments"
} |
Check if parent post is sticky on attachment page?
I use this code on post template (single.php) to check if current post is sticky:
<?php
if ( is_sticky() )
echo 'Post is sticky.';
?>
But it is not working on attachment page template (image.php). I wish to check if parent post is sticky on attachment page of post featured image.
How to check if parent post is sticky on attachment page (image.php)? | The post parent can be accessed by `$post->post_parent`. The ID of the post parent is retrieved, so can try something like this
$parent_ID = $post->post_parent;
if( is_sticky( $parent_ID ) ) {
// DO SOMETHING IF POST PARENT IS STICKY
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "post thumbnails, attachments, sticky post, featured post"
} |
How to use esc_attr__ with custom translation function?
I just made a built-in translation function to help users to translate their theme from theme options.
Usually my functions works great as follow:
<?php _e( 'No Comments', 'mytextdomain' ); ?>
becomes:
<?php echo __myfunction( 'no_comments' ); ?>
My question is related to `esc_attr__` and I'm stuck here... How the following code should look using custom translation function?
esc_attr__( 'No Comments', 'mytextdomain' )
Where should I place my translation function `__myfunction` ? Will be corect the following code?
esc_attr__myfunction( 'no_comments' )
Thanks | As your function returns the translated string, you could pass the translation function as parameter for `esc_attr()` and `esc_attr_e()`:
esc_attr__( __myfunction( 'no_comments' ) );
esc_attr_e( __myfunction( 'no_comments' ) );
But `esc_attr__()` and `esc_attr_e()` will perform translation tasks that you don't need because you handle the translation at your own, so I think it is better to use `esc_attr()` only:
esc_attr( __myfunction( 'no_comments' ) );
and
echo esc_attr( __myfunction( 'no_comments' ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation"
} |
How can I get categories IDs if multiple categories requested via URI?
Let's say, I have two categories, '`color`' and '`temperature`'. Each one has a number of sub-categories.
Wordpress does great job displaying posts in requested categories when I go to URL like this one:
How can I get these categories (IDs or slugs) in category template?
**UPDATE** : Thanks to Rarst; I will analyze `$wp_query->tax_query->queries`.
ps. btw, ` gives posts in any of `blue` OR `yellow` categories. Nice ,)
pps. AND there may be more than two categories, of course. | Hm hm. WordPress might be good at making this work, but isn't too good at making it convenient to work _with_. Typically `get_queried_object()` is a good way to access such context, but in this case it will merely hold the _first_ term and ignore the rest.
You will probably have to scrape this information out of `$wp_query->tax_query->queries`, which will hold something like this:
array(2) [
array(5) [
'taxonomy' => string (8) "category"
'terms' => array(1) [
string (12) "post-formats"
]
'field' => string (4) "slug"
'operator' => string (2) "IN"
'include_children' => bool TRUE
]
array(5) [
'taxonomy' => string (8) "category"
'terms' => array(1) [
string (6) "markup"
]
'field' => string (4) "slug"
'operator' => string (2) "IN"
'include_children' => bool TRUE
]
] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "categories, templates"
} |
Custom Wordpress URL
Any ways I could show Custom Post Type's Content with such URL? E.g: (www.mydomain.com/view-promotion/christmas-promotion)
* view-promotion is page name
* christmas-promotion is the custom post type's post name
Currently this URL (www.mydomain.com/view-promotion/christmas-promotion) is automatically changed to (www.mydomain.com/promotion/christmas-promotion) where (promotion) is the post_type.
I am trying to have the view-promotion (Page Template) to show content by using custom post type name. | You can use a slug, when you are registering the post type with register_post_type(). You can add this argument like this
$labels = array(
//... add the labels as you need
)
);
$args = array(
'labels' => $labels,
//add other options as you need
'rewrite' => array('slug' => 'view-promotion')
);
register_post_type( 'promotion', $args );
}
**EDIT:**
You need some other identifier to differentiate between the page and your custom post type. Otherwise Wordpress won't be able to know whether you mean the `view-promotion` page or the custom post type.
Even something like this will work
...
'rewrite' => 'view-promotion/a',
... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, url rewriting"
} |
How create Group Blogs based on user created Groups
I'm looking to create a site that allows registered users to create their own groups and have their own group blogs. They should be able to have a group page with a few details about the group and it should show the group blog. I've thought of a couple of ways of doing this but both seem to require custom plugins.
1) Use the BuddyPress plugin. This gives the groups but there currently is no BP plugin that allows group blogs.
2) Use categories. This gives the group blog if categories are set with permissions as to who can post using them and if each blog post can only have one category. Would need to create a plugin that allows users to create a new category and have that as the 'group'. The plugin would also need to allow group members to be invited.
Is there another way to achieve this is WordPress? Any help would be greatly appreciated.
Note: I don't want to use WordPress MU. | Use a multisite. There are no good reasons not to do that. For the groups I would use two custom tables:
1. A `group` table for the description, maybe an image path/ID an a group ID. You could also use a custom post type on the main site for that, but it is easier to optimize the queries for a custom table.
2. A `group_users` table to associate user IDs with group IDs. You could the `usermeta` table, but again – performance.
Whenever a user creates a group, create a new blog. WordPress has internal routines for that, it will set up all the necessary tables for you, and you can even control the plugins and the theme that are active or available for that blog.
I would use the main site just to list the blogs. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, customization"
} |
Is there any difference between hooks posts_where with posts_join and posts_search performance wise?
I want to know which filter hook I should use that performs faster.
I did try both several times and I noticed that `posts_search` is a bit faster than using the combination of `posts_where` and `posts_join`
What is your take on this? | All of these hooks are called in a similar fashion and get passes similar data. Under normal circumstances there should be no meaningful performance difference between them.
One scenario I can think of is that if you aren't properly targeting your code to specific queries and it runs in _every_ query then `posts_search` might fire less time, because other two are conditional on `suppress_filters` in query being disabled. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "query, performance, posts where"
} |
Add sub menu page in your plugin
this is how i am adding the menu and trying to add the sub menu page which is not adding.
**party-reservation.php**
function a_qoute_admin_action()
{
add_menu_page(__('Reservations Pages'), __('Donation'), 'edit_themes', 'a-qoute', 'qoute_settings', ''); // working
add_submenu_page("party-reservation.php", "Donations Log", "Donations Log", 8, "DonationsLog", "Donations_Log"); // not working.
}
add_action('admin_menu', 'a_qoute_admin_action');
if i use 'themes.php' it adds a sub menu page in the appearance section. | The add_submenu_page first parameter should be the top menu page handle which in you case is `a-qoute` so:
function a_qoute_admin_action(){
add_menu_page(
__('Reservations Pages'),// the page title
__('Donation'),//menu title
'edit_themes',//capability
'a-qoute',//menu slug/handle this is what you need!!!
'qoute_settings',//callback function
'',//icon_url,
''//position
);
add_submenu_page(
'a-qoute',
'Donations Log', //page title
'Donations Log', //menu title
'edit_themes', //capability,
'DonationsLog',//menu slug
'Donations_Log' //callback function
);
}
add_action('admin_menu', 'a_qoute_admin_action'); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "plugins, filters, admin, wp admin, hooks"
} |
Use external link in the add sub menu
I want to show the data in the external plugins.php file. the below url path is correct but its not showing the file data. Whats the problem?
add_submenu_page( 'antify', 'Plugins', 'Plugins', 'manage_options', 'plugins', ANTIFY_PLUGIN_URL . '/admin/pages/plugins.php' );
**plugins.php**
<?php
echo 'Hello World';
?> | Last argument of function `add_submenu_page` is the name of the function to call when display the content of the page. As described here:
<
The right use is:
add_submenu_page( 'antify', 'Plugins', 'Plugins', 'manage_options', 'plugins', 'my_function' );
function my_function(){
echo 'hello';
}
If you want a separate file you can do this
add_submenu_page( 'antify', 'Plugins', 'Plugins', 'manage_options', 'plugins', 'my_function' );
function my_function(){
include plugin_dir_path( __FILE__ ) . 'path/of/file.php';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, filters, hooks, actions"
} |
Empty the_content for all posts
I'm moving everything that is displayed with the_content in custom fields and i want to remove/emtpy the content of the post_content column in the database, for every post.
Is there a mysql query that does that or another way? | You can use `UPDATE`wp_posts`SET`post_content`="" WHERE 1` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, the content"
} |
How to force excerpts / teasers in the loop
When I'm in "the loop" (archive pages etc.) how do I force teasers / excerpts for all articles, regardless of whether they contain the `<!--more-->` tag or not?
Details:
I'm starting off of the `_s` template which displays blog post content using the `content.php` template in which it calls `the_content()` function. This function inspects the post and tries to find the `<!--more-->` tag in. If it finds one, it returns a teaser and a _read more_ link, if it doesn't it simply outputs the whole post.
I'd like to keep the first part, i.e. respect the `<!--more-->` tag if the content author used it, but if he/she forgot it I want to automatically display the teaser / excerpt anyway (something like the first paragraph or two).
What is the best way to do this? There is a `the_content` filter but e.g. the read more customization text doesn't come into it. What would you recommend? | **EDIT**
OK, there is a very hidden native function, `get_extended()` that I never knew about and greatly explained by @kaiser in his answer. My answer should only be an extension to the answer by @kaiser
**ORIGINAL ANSWER**
There is no native function to do this. The best here would be to use a PHP function like `strpos` to search for the more tag, and then do something according to the result.
You can try something like this
if( strpos( $post->post_content, '<!--more-->' ) ) {
the_content( __( '… Read more about this article <span class="meta-nav">→</span>' ) );
}
else {
the_excerpt();
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 7,
"tags": "loop, excerpt"
} |
Problem with jQuery in post body?
I have the following code int he post body and it won't run. I can run it from the console just fine, but in the body of the post it won't do anything and doesn't return any kind of error either.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
console.log("Test");
$(".myBox").click(function(){
var myBoxOn = $(this).attr("data-class");
$(".myBoxContent").hide("slow");
$("#" + myBoxOn).show("slow");
});
});
</script> | When you are using Google CDN hosted version of jQuery then you don't need to use jQuery wrapper. It's for jQuery packed with WordPress core because jQuery with WordPress runs in noConflict mode.
So your jQuery code will be.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
console.log("Test");
$(".myBox").click(function(){
var myBoxOn = $(this).attr("data-class");
$(".myBoxContent").hide("slow");
$("#" + myBoxOn).show("slow");
});
});
</script> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, jquery"
} |
checkbox function not working for dropdown menu
I have created a dropdown menu that shows when a checkbox is clicked.
It works perfectly outside of wordpress see JS Fiddle - <
however when I add it into my WP theme ( running blankslate ) the checkbox function does not work ( I assume it is the checkbox function) - I have run it on a number of different themes to no avail which makes me think that this is a problem on all wordpress themes.
I have an example of it here on an existing website running wordpress twenty fourteen.
How can I make the menu drop down ?
Cheers | As per the `wp_nav_menu()` function the default classes are like below:
<ul class="menu">
<li><a href="#">Menu</a></li>
<li>
<a href="#">Menu</a>
<ul class="sub-menu">
<li><a href="#">SubMenu</a></li>
<li><a href="#">SubMenu</a></li>
</ul>
</li>
<li><a href="#">Menu</a></li>
</ul>
Note that, the `.menu` and `.sub-menu`. May be you are messing with the wrong `class` names, and some `class` conflicts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, html"
} |
Getting Internal server in sub folder pages
I have just created sub folder called "blog", so access link is `example.com/blog`.
I have installed WordPress in blog folder, configure database and all but when access above link then I am getting error called
> **Internal Server Error** The server encountered an internal error or misconfiguration and was unable to complete your request.
> Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
> More information about this error may be available in the server error log.
I am using godaddy server ,Also I have checked for `.htaccess` file but there is not `.htaccess` file created for main domain. Should I need to create separate `.htaccess` for sub folder "blog" to solve this error?
If yes then what code I need to put in `.htaccess` for sub folder internal server error remove. | you need to create .htaccess file. Create .htaccess file and paste below code in it
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPress | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "directory, internal server error"
} |
Loop through pages with specific template
I would like to know how I can loop through pages with a specific template name. I have several pages where the admin can select a template name of `SALE`. I want to display all content with this template name via the loop.
Any ideas are much appreciated! | Wordpress saves page templates that is assigned to a specific page in the db in the `wp_postmeta` table.
These are saved as follows:
'meta_key' => '_wp_page_template',
'meta_value' => 'NAME_ OF_TEMPLATE'
With this in mind, you can loop through pages which shares a specific page template, using `get_pages` ( _You can also make use of`WP_Query`_)
Example:
$pages = get_pages(array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page-special.php'
));
foreach($pages as $page){
echo $page->ID.'<br />';
echo apply_filters( 'the_content', $page->post_content );
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "loop, templates"
} |
Displaying Page Title on index.php
I have my posts page set as `index.php`, and on there I have my main heading (as I do on all pages).
I'm having trouble displaying the page's heading however. The page is called 'Blog' in WordPress, and has been specified as the posts page.
If I output the page heading with `wp_title('');`, I get the title of the page — 'Blog' — but with the site name after it (perhaps due to Yoast SEO plugin).
If I use `the_title()` then it gives me the title of the most recent blog post, even though I'm calling the function outside of the loop.
So I've had to resort to simple hardcoding `<h1>Blog</h1>` which is far from ideal.
Is there a way I can pull in the name of the page title dynamically but _just_ the page title on it's own? | Strange. Outside the loop, the_title() _should_ give you the current page name, _if_ you really are on a page, and not viewing a specific post. If it gives post title instead, it may mean that you are somehow inside a loop. But if that were true, wp_title shouldn't show "Blog".
See if other options give the same result:
//the_title();
single_post_title();
echo $post->post_name; // I think this shows the url page name
Also check for is_page(). You might try the is_page('Blog') test.
if (is_page('blog')) {
echo 'Blog';
}
else {
the_title();
}
just to see what happens. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "posts, theme development, title, homepage, wp title"
} |
Standard location for plugin to save/cache files?
**Are there official guidelines on where a plugin should cache files?**
If not, is there a best-practice out there that I can follow?
For example, a plugin grabs content from a back-end system benefits from caching the file so it doesn't repeatedly fetch the same content from the back-end.
Searching here and elsewhere is tough as most queries lead to caching plugins or database tutorials.
My instinct says to put them into a sub-directory of `wp-content/uploads`.
My secondary instinct would be to keep the files within the plugin's directory tree. This keeps plugin data grouped together but doesn't follow (what appears to be) WordPress architecture where user content is in `/uploads`. | It would be nice if WordPress had a standards based cache directory, but since it doesn't I think the best option is to keep it in the plugin folder itself.
Uploads are in my opinion for actual uploads and cache files are not really considered as such. I think it easier to manage , reduces possible conflicts and to be honest it's where I would look if a plugin has this functionality.
_tl;dr:_ The cache files are part of the functionality of a specific plugin and should be packaged with it. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 10,
"tags": "plugin development, uploads, wp filesystem"
} |
Link to post author but exclude administrator (on single.php)
How to exclude administrators from the code below? So **if** the current post author has the role of administrator, nothing will show.
<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>" ><?php the_author_meta( 'display_name' ); ?></a>
thank you | You can use the wordpress function `user_can` that accepts as arguments the id of the user and a string representing a capability or a role name ('administrator' in your case ) and returns a boolean value.
<
Referred to your code you can try this
<?php
if( !user_can( get_the_author_meta( 'ID' ), 'administrator' ) ): ?>
<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>" ><?php the_author_meta( 'display_name' ); ?></a>
<?php
endif; ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "admin, author"
} |
How to throw error to user when saving post
I made a custom post type and on saving its additional data I want to check if I a published post exists by its name. It works alright if there is, but I would like to throw some notice if article is not found.
$post_exists = $wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $_POST['article_name'] . "' AND post_type = 'post'", 'ARRAY_A');
if($post_exists)
update_post_meta($id, 'article_name', strip_tags($_POST['article_name']));
else
???
I noticed there is < but I dont think that is what I want since debugging is set to false?. Error could be anything - some usual notice would be fine, but even simple javascript alert could be good. Currently it tells me that the post is saved with green lights which doesnt seem right ! | You can use `admin_notices` hook <
For example:
function ravs_admin_notice() {
?>
<div class="error">
<p><?php _e( 'Article with this title is not found!', 'my-text-domain' ); ?></p>
</div>
<?php
}
on `publish_{your_custom_post_type}` hook <
function on_post_publish( $ID, $post ) {
// A function to perform actions when a {your_custom_post_type} is published.
$post_exists = $wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $_POST['article_name'] . "' AND post_type = 'post'", 'ARRAY_A');
if($post_exists)
update_post_meta($id, 'article_name', strip_tags($_POST['article_name']));
else
add_action( 'admin_notices', 'ravs_admin_notice' );
}
add_action( 'publish_{your_custom_post_type}', 'on_post_publish', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "custom post types, errors"
} |
How to associate 2 custom fields together (date & price for instance)?
On my website you can purchase a trip after choosing the departure date (among the available departure dates). In the back-end, a trip is a CPT in which departure dates are specified through "Repeater Field" (an extension of "Advanced Custom Fields" plugin).
Trip price depends on departure date so each departure date must have a trip price attached to it. How can I have a price field next to each date field?
I'd prefer to use those plugins but I'm open to any suggestion.
EDIT: I came across this thread that looks related to my problem, but I don't understand the code in it. | With ACF, in the same repeater custom field that your departure date uses, add a price field. Then each time you add a departure date, you can add the associated price. Wherever you're showing the departure date in the template you can add the price field as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field"
} |
How to redirect all pages of a custom post type
Here's the deal. Let's say I have a custom post type called "subscriptions". Under this post type there are pages like the following:
* mysite.com/subscription/ **my-first-subscription**
* mysite.com/subscription/ **my-second-subscription**
* mysite.com/subscription/ **my-third-subscription**
The issue is that I actually have a pricing page which allows users to use a widget to select the different subscriptions. I don't want the users to _ever_ be able to access the subscription pages directly, even if they know the URL. My first thought is that I'd like any attempt to access a page of "subscription" type to be redirected to the pricing page. How would I do that?
(If someone has a better idea, I'm open to that as well.) | As stated by Milo it looks like it a duplicate of [How to disable the single view for a custom post type?]
<?php
add_action( 'template_redirect', 'subscription_redirect_post' );
function subscription_redirect_post() {
$queried_post_type = get_query_var('post_type');
if ( is_single() && 'subscription' == $queried_post_type ) {
wp_redirect( pricingpageURL, 301 );
exit;
}
}
?>
Just swap our **pricingpageURL** with the pricing page URL value of your choice. Hope this helps. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "custom post types, php, redirect"
} |
How to add wechat (weixin) link to navigation menu?
The profile link of WeChat (or Weixin) has the following format: `weixin://contacts/profile/username`
As you can see, it doesn't use ` and that seems to be the reason that it cannot be added to the WordPress navigation menu.
Well you can add it, but after saving the menu, the URL field is blank (again).
The strangest thing is that the navigation menu does not exclusively save http(s); I just tried to save a telephone number URL (`tel:00861012345678`) and that is actually saved.
Is there any way to get the WeChat link to properly show?
Thanks. | Filter `kses_allowed_protocols` (`wp-includes/functions.php wp_allowed_protocols`) to add your protocol:
add_filter( 'kses_allowed_protocols', function( $protocols ) {
$protocols[] = 'weixin';
return $protocols;
});
The default values are 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', and 'xmpp'. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "menus, links, customization"
} |
Enqueue core jQuery in the footer?
I have this in my `functions.php` file and I can't get jQuery to load in the footer. The `includes` file loads in the footer fine, though. What else do I need to do?
function starter_scripts() {
wp_enqueue_style( 'starter-style', get_stylesheet_uri() );
wp_enqueue_script( 'jquery', '', '', '', true );
wp_enqueue_script( 'includes', get_template_directory_uri() . '/js/min/includes.min.js', '', '', true );
}
add_action( 'wp_enqueue_scripts', 'starter_scripts' ); | To do that you will first have to deregister your jQuery script and then register again. If you use jQuery comes with WordPress then following is the function your are looking for.
function starter_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, NULL, true );
wp_enqueue_script( 'jquery' );
wp_enqueue_style( 'starter-style', get_stylesheet_uri() );
wp_enqueue_script( 'includes', get_template_directory_uri() . '/js/min/includes.min.js', '', '', true );
}
add_action( 'wp_enqueue_scripts', 'starter_scripts' );
If you use Google CDN hosted version of jQuery then let me know I will modify this code for Google CDN URL. | stackexchange-wordpress | {
"answer_score": 28,
"question_score": 33,
"tags": "jquery, wp enqueue script"
} |
Why cant I add a custom post type to a custom taxonomy?
I am trying to assign a custom taxonomy to a custom post type with `wp_insert_post` function.
$args = array(
'post_type' => 'custom_post_type',
'post_title' => wp_strip_all_tags( $title ),
'post_content' => 'some content',
'post_status' => 'publish',
'post_author' => $author_id,
'post_category' => array($category_id), //$category_id = 33;
);
$new_cpt_id = wp_insert_post( $args );
A quick fix for now is:
wp_set_object_terms( $new_cpt_id, $category_id, 'custom_tax_category' );
However, I want to do it with `wp_insert_post` function.
**NOTE** I am using the following inside the `$args` for `register_post_type( 'custom_post_type', $args );`
'taxonomies' => array( 'custom_tax_category','custom_tax_tag' ),
So, what am I missing? | The `post_category` you are using is for core categories taxonomy. For custom taxonomies you have to use `tax_input`. For example, the next code set terms for `custom_tax_category` and `custom_ta_tag` taxonomies.
$args = array(
'post_type' => 'custom_post_type',
'post_title' => wp_strip_all_tags( $title ),
'post_content' => 'some content',
'post_status' => 'publish',
'post_author' => $author_id,
'tax_input' => array(
'custom_tax_category' => array( $category_id ),
'custom_tax_tag' => array( $tag_id )
),
);
$new_cpt_id = wp_insert_post( $args ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "custom post types, custom taxonomy, wp insert post"
} |
Display avatar of user profile when logged in
I am trying to display user's avatar/profile image when logged in, but when I use this:
<?php
global $current_user;
get_currentuserinfo();
echo get_avatar( $current_user->ID, 64 );
?>
it displays the default_avatar_male.jpg, but I don't want anything to be displayed unless logged in. Thanks for all help. | Hey pass the current user email id in get_avatar() function if user is logged in like this
<?php
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
if ( ($current_user instanceof WP_User) ) {
echo 'Welcome : ' . esc_html( $current_user->display_name );
echo get_avatar( $current_user->ID, 32 );
}
} | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "avatar"
} |
Display get_post_meta if contains value
Am struggling to get the below to work.
I just want to display the `get_post_meta` 'title_override_text' if it contains any value otherwise just display the standard title (already catered for in functions.php).
<?php $h1override = get_post_meta($id, "title_override_text", true); ?>
<?php if (!empty($h1override)) { ?>
<h1><span><?php title_text(); ?></span></h1>
<?php } else { ?>
<h1><span><?php title_override_text(); ?></span></h1>
<?php } ?>
It correctly displays 'title_override_text' if there is a value but when the field is empty, it doesn't display anything at all (i.e not 'title_text').
How can I display 'title_override_text' if it contains any value (it is a text field)?
Is there a better way of doing this like using (for example):-
if(get_post_meta($id, "page_title_override_text", true) == "" | I actually managed to achieve what I needed to do in the end by using the below:-
<?php if(get_post_meta($id, "h1_title_override", true) !== '') { ?>
<h1><?php title_override_text(); ?></h1>
<?php } else { ?>
<h1><?php title_text(); ?></h1>
<?php } ?>
With the necessary functions in place of course... | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "post meta"
} |
Removing rel="nofollow" from links posted in Post Content
I am running wordpress for my blog EasyPadhai.
I am writing a posts and I have included links to my Android app EasyPadhai for my users. But all links to app are turning in nofollow links. Also Social-links are becoming nofollow links.
How can I change this, so that links in post_Content become doFollow. I am not a pro-wordpress dev. Also I am using following plugins on my installation.
* Akismet
* Google Analytics for WordPress
* WordPress SEO
* W3 Total Cache
**How can I change nofollow links to do follow links for my Post Content?** | These links are generated by `alx_social_links()` function. So in your theme's `functions.php` file, search for `alx_social_links()` function and this link specifically.
echo '<li><a rel="nofollow" class="social-tooltip" '.$title.' '.$link.' '.$target.'><i '.$icon.' '.$color.'></i></a></li>';
and remove `rel="nofollow"` from it. So this will be the new link.
echo '<li><a class="social-tooltip" '.$title.' '.$link.' '.$target.'><i '.$icon.' '.$color.'></i></a></li>';
It will remove `nofollow` tag from these links. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, permalinks, links, seo, nofollow"
} |
Add variables to all permalinks in site
I need to add variables to all links in my site based on a condition.
So all permalink in a page that met my condition (in specific category or whatever) :
> www.domain.com/exemple-page or
>
> www.domain.com/category/cars
would be
> www.domain.com/exemple-page?var=1 and
>
> www.domain.com/category/cars?var=1
How can I do that? | All permalink output has filters you can use to modify it: `post_link`, `post_type_link`, `page_link`, `tag_link`, `category_link`, `term_link`.
A simple example with `page_link`:
function wpd_append_query_string( $url, $id ) {
// check some condition and add a query string var
if( some_condition ) {
$url = add_query_arg( 'var', 1, $url );
}
return $url;
}
add_filter( 'page_link', 'wpd_append_query_string', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
Check If comment author is registered
It should be simple, but I tried some codes, none does the trick. Searched on Google, nothing there either. Simply check if the comment author is a registered user (so I can add some code for it), if it's not registered show nothing.
This should do the trick `if( empty($comment_author_nickname) && empty($comment_author_email) )` but I don't know how to get that information
thank you | I wonder if you mean this kind of check:
if( $comment->user_id > 0 ) {
// Registered comment author
}
in your comment's template callback.
This is determined in the the `wp-comments-post.php` file:
$commentdata = compact('comment_post_ID', ..., 'user_ID' );
$comment_id = wp_new_comment( $commentdata );
but it's not obvious where the `user_ID` variable comes from, since this variable is not defined in that file.
So this is actually picking up the global variable `$user_ID` or `$GLOBALS['user_ID']` behind our back ;-) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "comments, author"
} |
Get the_field of Advanced Custom Fields in a custom query
I have a custom query to display content of a certain template:
<?php
$i = 0;
$pages = get_pages(array(
'meta_key' => '_wp_page_template',
'meta_value' => 'sale.php'
));
foreach($pages as $page){
echo '<div class="content_'. $i .'">' . apply_filters( 'the_content', $page->post_content ) . '</div>';
echo '<div class="title_' . $i . '">' . apply_filters( 'the_title', $page->post_title) . '</div>';
echo '<p>' . the_field('sale_images_url') . '</p>';
$i++;
}
?>
which works fine for `the_content()` and `the_title()` so far. Want I also wanna do is, to display the value of an Advanced Custom Field named `sale_images_url`.
But it displays nothing. Do I have to handle this different?
Thanks | In general, you need to pass the page ID to `the_field` and for that matter `get_post_meta` as well
You can try the following
the_field( 'sale_images_url', $page->ID ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, advanced custom fields"
} |
WPDB update row with != in where clause
I'm using wpdb to develop a plugin to add a custom form to wordpress. To update a row, I use an array and `wpdb->update()`. WP Class Reference says:
> My SQL code should be something like `UPDATE ROW .... WHERE a='a' AND b!='c'`.
The problem is that `!=` doesn't seem to be working, in fact from WP Class Reference
> A named array of `WHERE` clauses (in column => value pairs).
I need to connect to an external database and fetch data from that database so I can't use any of the available plugins. | Here is exmaple code,You will change as per your requirement
$wpdb->query(
"
UPDATE $wpdb->posts
SET post_parent = 7
WHERE ID = 15
AND post_status = 'static'
"
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wpdb, sql"
} |
show custom category posts from a custom post type
I am trying to show posts from a **Custom Post Type** (documents) that has a custom **Taxonomy** (subject) with two categories, each category page should have its own posts. But when I open any of these categories page, I get all posts from this Custom Post Type.
I created a file **taxonomy-subject.php** with below code:
$args = array( 'post_type' => 'documents',
'posts_per_page' => 20 );
$terms = get_terms( 'subject', array (
'hide_empty' => 0,)
);
$loop = new WP_Query( $args, $term );
while ( $loop->have_posts() ) : $loop->the_post();
// content
so where the problem exactly? | You should need to do any custom querying on `taxonomy-subject.php`, just use the normal loop api. WordPress will build a query for you.
As for your question:
$args = array(
'post_type' => 'documents',
'posts_per_page' => 20,
);
`WP_Query` doesn't take a second argument to its constructor. All its seeing is the arguments above. You're asking WP_Query for 20 posts from the document post type. Its giving them to you. If you want posts from a specific term, you'll need to tell it that with a taxonomy parameter.
$loop = new WP_Query(array(
'post_type' => 'documents',
'posts_per_page' => 20,
'tax_query' => array(array(
'taxonomy' => 'subject',
'terms' => get_queried_object_id(),
)),
));
`get_queried_object_id` should return the term ID on `taxonomy-subject.php`, you'll need to use some other code if this loop is being used elsewhere. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Order posts randomly, not by date
I'd like to know how to order by "random" instead of by "date".
Can someone help me modify this so it gets posts randomly instead of by date?
$posts = get_posts('numberposts=5&orderby=date&fields=all&tag='.$tag);
Thank you! | $randomPosts = get_posts(array(
'orderby' => 'rand',
'posts_per_page' => 5,
'tag' => $tag,
));
Take a gander at the `WP_Query` documentation. `get_posts` uses `WP_Query` under the hood, so you can use any arguments that may be used there. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, sort"
} |
Correct classes for WordPress menu items
I have been trying to get the current menu item to my custom post types. I cannot get it to work, and when looking at my menu, I am wondering, that if everything is allright.
Which are the correct classes WordPress should generate, when displaying pages, archives and custom post types?
I have this link explaning them: <
But my page for example has the following classes:
menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-146 current_page_item menu-item-147
And my custom post type:
menu-item menu-item-type-taxonomy menu-item-object-category menu-item-187
Which seems strange, since the menu is a link to the category and archive page, not a taxonomy?
Thanks in advance | The taxonomy archive menus have the classes `menu-item-type-taxonomy` and `menu-item-object-{taxonomy-name}`, so there is nothing strange because category is a taxonomy (here you are wrong when say that "the menu is a link to the category and archive page, not a taxonomy"). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom taxonomy, menus"
} |
How to move the sidebar in TwentyFifteen to the right?
Is it possible to move the sidebar in the TwentyFifteen theme to the right using a child theme and CSS only, or does it require changes to the theme itself? The main issue I'm running into is that I can get the sidebar on the right side in either the "default" or the "scrolled" scenario, but not in both (default uses position: relative and is what you get when the page loads, scrolled is set when the page is scrolled and changes the sidebar position to absolute.) | I took the following from the `rtl.css` and applied them via Magic Widget with additional `!important` keywords to an English site:
body:before {
right: 0 !important;
left: auto !important;
}
.sidebar {
float: right !important;
margin-right: auto !important;
margin-left: -100% !important;
}
.site-content {
float: right !important;
margin-right: 29.4118% !important;
margin-left: auto !important;
}
.site-footer {
float: right !important;
margin: 0 35.2941% 0 0 !important;
}
This seems to work, even when you scroll down. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 16,
"tags": "themes, child theme, theme twenty fifteen"
} |
echo same menu items across multi-site platform
I am trying to echo main theme's menu items across the headers of other sites in a WP multi-site environment and was wondering what is the proper way of doing this. I tried iframe which works but there is a delay in displaying the header. So, the body gets loaded and couple of seconds later the header populates. Here is the iframe code I have:
<iframe class="header-iframe" src=" frameborder="0" scrolling="no" width="100%" height="233px;" ></iframe>
(please excuse my way of questioning)
I notice that in one of the site's header, to echo something, it show something like this:
<?php bloginfo('siteurl')
now, if I want to display from the main theme, what should be my PHP statement? | Sorry this should be a comment --> you should be able to use a switch to blog < This will allow you to grab the main blog ID, from there you can use a WP list pages or a < to display the menu of your main site on the other blogs within the network | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, multisite, iframe"
} |
How do i get file_get_contents to work in wordpress
Im using geoplugin.com to display content based on users location the codex is set up like this:
$geoplugin = unserialize( file_get_contents(' ip=' . $_SERVER['REMOTE_ADDR']) );
This works on my dev site but not on my live site. I tried to use wp_remote_get but couldnt get it to set up properly. Any ideas on why this would work on one site and not another? | This is how I solved this issue ::
function get_client_ip_env() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$geoplugin = maybe_unserialize( wp_remote_fopen(' . get_client_ip_env()) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, customization"
} |
Increase returned number/pages on pagination
Im trying to increase the numbers/Pages for my pagination. I have 64 pages set, and this is how it shows now: « Previous 1 2 3 4 … 64 Next ». How do I control so I can show more numbers? In my case i need the counter to go up to about 30.
My query:
if ( $pagination === 'numbered' ) {
global $wp_query;
$big = 999999999; // need an unlikely integer
$output .= '<div class="nav-links2">';
$output .= paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
$output .= '</div>';
return $output; | Refer to the Codex page for `paginate_links` for all accepted arguments.
The two you want to modify are `mid_size` and possibly `end_size`.
$output .= paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'mid_size' => 8 // number of page links to display on either side of current page
) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, pagination"
} |
How to display Custom taxonomy on custom post listing page
I want to show the custom taxonomy name on the listing of custom post type on my front end | You can use following code in the custom post type listing template
<?php the_terms( $post->ID, 'custom_taxonomy_name' , ' ' ); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "custom taxonomy"
} |
Distinguish between 2 instances of admin-ajax.php
I've added an avatar image selector to my `profile.php` page.
I'd like to be able to alter the query that loads the image library using `pre_get_posts` but I can't find any way to distinguish between this page and the regular media library (`upload.php`).
Using the global `$pagenow` returns `admin-ajax.php` in both situations. Is there any other way to tell which page is loading the media library? | There isn't much point to distinguishing `admin-ajax.php` since it's essentially same file with same logic running for many many purposes.
You are passing `action` data and hooking into respective action. So `action` is your identifier. If you are reusing same action and need to further differentiate — just pass more data with your GET/POST request and check for it in your handler. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ajax, uploads, media library"
} |
How to Display CPT Posts on index Page
I have created Custom Post type called "Natural Food" and displays the Post of this CPT Under
> Natural Food
Menu, my index page also contains some post, as well as i want to display "Natural Food" post in index page how to do this. | Add a function hooked to `pre_get_posts` which modifies `post_type` argument of the main query to add your custom post type.
function wpd_home_post_types( $query ){
if( $query->is_home() && $query->is_main_query() ){
$query->set( 'post_type', array( 'post', 'natural_food' ) );
}
}
add_action( 'pre_get_posts', 'wpd_home_post_types' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, theme development"
} |
trying to show single post but displays all post on a custom post type
Good day,
I was trying to show a specific post when a user click on the title but all other post are shown as well, how can I filter it?
for example when I click link < the other post are shown as well.
or How do I get the title from the link so I could use it as my parameter on my query?
here's my single-students.php
<?php
/**
* The Template for displaying all single posts.
*
* @package Motif
*/
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php query_posts( 'post_type=students'); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; // end of the loop. ?>
</main><!-- #main -->
</div><!-- #primary --> | `query_posts( 'post_type=students');` that changes the main query to be for all posts with the type `students`. It's showing all the posts because you're asking it to.
If this is on a single post page, your loop will be sufficient, no need for extra `query_posts` calls or anything like that. Just remove that bit from your code.
In fact, you probably shouldn't use `query_posts` at all. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, single"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.