qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
237,305 |
<p><a href="https://i.stack.imgur.com/dWB4c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWB4c.jpg" alt="enter image description here"></a></p>
<p>I have been adding a post type to my theme, how do I hide/disable the Move to trash button?
Here is my code so far:</p>
<pre><code>$labels = array(
'name' => _x( 'Inhoud', 'taxonomy general name' ),
'singular_name' => _x( 'Inhoud', 'taxonomy singular name' ),
'search_items' => __( 'Zoek Inhoud' ),
// 'popular_items' => __( 'Popular Writers' ),
'all_items' => __( 'Alle Inhoud' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Wijzig Inhoud' ),
'update_item' => __( 'Update Inhoud' ),
'add_new_item' => __( 'Toevoegen Nieuwe Inhoud' ),
// 'new_item_name' => __( 'Nieuwe Evenement Naam' ),
// 'separate_items_with_commas' => __( 'Separate writers with commas' ),
// 'add_or_remove_items' => __( 'Add or remove writers' ),
// 'choose_from_most_used' => __( 'Choose from the most used writers' ),
'not_found' => __( 'Geen inhoud gevonden.' ),
'menu_name' => __( 'Inhoud' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
//'show_admin_column' => true,
//'update_count_callback' => '_update_post_term_count',
'menu_position' => 7,
'menu_icon' => 'dashicons-admin-post',
'show_in_menu' => true,
'show_in_nav_menus' => false,
'show_in_admin_bar' => false,
// 'query_var' => true,
// 'rewrite' => array( 'slug' => 'inhoud' ),
'capabilities' => array(
'create_posts' => 'do_not_allow',
//'edit_post' => 'true',
//'delete_posts' => 'do_not_allow'
),
'supports' => array( ),
'map_meta_cap' => array('delete_post' => false),
'has_archive' => true,
'public' => true
);
register_post_type( 'inhoud', $args );
</code></pre>
|
[
{
"answer_id": 237306,
"author": "Bhagchandani",
"author_id": 101627,
"author_profile": "https://wordpress.stackexchange.com/users/101627",
"pm_score": 3,
"selected": true,
"text": "<p>You can hide move to trash button via adding css in the admin area. Try following code in <code>functions.php</code> file:</p>\n\n<pre><code>function my_custom_admin_styles() {\n?>\n <style type=\"text/css\">\n .post-type-inhoud form #delete-action{\n display:none;\n }\n </style>\n<?php\n}\nadd_action('admin_head', 'my_custom_admin_styles');\n</code></pre>\n"
},
{
"answer_id": 237330,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": false,
"text": "<p>Tested out the code that was provided by <a href=\"https://wordpress.stackexchange.com/users/101627/user3888958\">user3888958</a>, but didn't work for me. here's my own version which hide the <em>Move to Trash</em> link:</p>\n\n<pre><code>add_action( 'admin_head', 'wpse_237305_disable_trash' );\n\nfunction wpse_237305_disable_trash() {\n global $pagenow;\n\n if ( $pagenow == 'post.php' ) {\n ?>\n <script type=\"text/javascript\">\n jQuery( document ).ready( function( $ ) {\n $( '#delete-action' ).remove();\n } );\n </script>\n <?php\n }\n}\n</code></pre>\n\n<h3>Result</h3>\n\n<p><a href=\"https://i.stack.imgur.com/tiEMT.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tiEMT.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2016/08/27
|
[
"https://wordpress.stackexchange.com/questions/237305",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73800/"
] |
[](https://i.stack.imgur.com/dWB4c.jpg)
I have been adding a post type to my theme, how do I hide/disable the Move to trash button?
Here is my code so far:
```
$labels = array(
'name' => _x( 'Inhoud', 'taxonomy general name' ),
'singular_name' => _x( 'Inhoud', 'taxonomy singular name' ),
'search_items' => __( 'Zoek Inhoud' ),
// 'popular_items' => __( 'Popular Writers' ),
'all_items' => __( 'Alle Inhoud' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Wijzig Inhoud' ),
'update_item' => __( 'Update Inhoud' ),
'add_new_item' => __( 'Toevoegen Nieuwe Inhoud' ),
// 'new_item_name' => __( 'Nieuwe Evenement Naam' ),
// 'separate_items_with_commas' => __( 'Separate writers with commas' ),
// 'add_or_remove_items' => __( 'Add or remove writers' ),
// 'choose_from_most_used' => __( 'Choose from the most used writers' ),
'not_found' => __( 'Geen inhoud gevonden.' ),
'menu_name' => __( 'Inhoud' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
//'show_admin_column' => true,
//'update_count_callback' => '_update_post_term_count',
'menu_position' => 7,
'menu_icon' => 'dashicons-admin-post',
'show_in_menu' => true,
'show_in_nav_menus' => false,
'show_in_admin_bar' => false,
// 'query_var' => true,
// 'rewrite' => array( 'slug' => 'inhoud' ),
'capabilities' => array(
'create_posts' => 'do_not_allow',
//'edit_post' => 'true',
//'delete_posts' => 'do_not_allow'
),
'supports' => array( ),
'map_meta_cap' => array('delete_post' => false),
'has_archive' => true,
'public' => true
);
register_post_type( 'inhoud', $args );
```
|
You can hide move to trash button via adding css in the admin area. Try following code in `functions.php` file:
```
function my_custom_admin_styles() {
?>
<style type="text/css">
.post-type-inhoud form #delete-action{
display:none;
}
</style>
<?php
}
add_action('admin_head', 'my_custom_admin_styles');
```
|
237,327 |
<p>I want to create shortcode like [genre] for WordPress. </p>
<pre><code>add_action( 'init', 'cptui_register_my_cpts_movie' );
function cptui_register_my_cpts_movie() {
$labels = array(
"name" => __( 'MOVIE', '' ),
"singular_name" => __( 'Movie', '' ),
"menu_name" => __( 'MOVIES LIBRARY', '' ),
"all_items" => __( 'All Movies', '' ),
"add_new" => __( 'Add New Movie', '' ),
"add_new_item" => __( 'Add New Movie', '' ),
"edit" => __( 'Edit', '' ),
"edit_item" => __( 'Edit Movie', '' ),
"new_item" => __( 'New Movie', '' ),
"view" => __( 'View', '' ),
"view_item" => __( 'View Movie', '' ),
"search_items" => __( 'Search Movie', '' ),
"not_found" => __( 'No Movies found', '' ),
"not_found_in_trash" => __( 'No Movies found in Trash', '' ),
"parent_item_colon" => __( 'Parent Movie', '' ),
);
$args = array(
"label" => __( 'MOVIE', '' ),
"labels" => $labels,
"description" => "All Publish Tools for Movies",
"public" => true,
"publicly_queryable" => false,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "movie", "with_front" => true ),
"query_var" => true,
"supports" => array( "title", "editor", "comments", "revisions", "thumbnail" ),
"taxonomies" => array( "genre", "year", "quality", "country", "awards", "type", "stars", "subtitle" ),
);
register_post_type( "movie", $args );
// End of cptui_register_my_cpts_movie()
}
</code></pre>
<p>I want to show 'genre' in shortcode</p>
<pre><code>function shortcode_for_genre() {
ob_start();
the_terms( $post->ID, array( 'taxonomy' => 'genre',), '', ', ', ' ' );
return ob_get_clean();
}
add_shortcode ('genre', 'shortcode_for_genre');
</code></pre>
<p>I'm tried above code and few other but no one works. This shortcode show genre of post. like drama, action. etc.</p>
|
[
{
"answer_id": 237333,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>page</code> post type.</p>\n\n<ul>\n<li>Simple to use.</li>\n<li>Easy to edit with page-builder tools/plugins.</li>\n<li>The permalink structure <code>example.com/parent-page/child-1/child-1.1</code> is already available.</li>\n</ul>\n\n<p>With \"Categories\", \"Taxonomies\" or \"CPT\", you have to register and rewrite permalink structures.</p>\n"
},
{
"answer_id": 237334,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 2,
"selected": false,
"text": "<p>I would not use WordPress pages nor articles for this.\nSimply, create a new custom post type called \"Projects\", with a plugin like Types, then create a new custom taxonomy \"Partners\" and associate it with that custom post type.\nClean and easy structure.</p>\n"
},
{
"answer_id": 237918,
"author": "somebodysomewhere",
"author_id": 44937,
"author_profile": "https://wordpress.stackexchange.com/users/44937",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Home</strong> - Create this as a <code>page</code>.</p>\n\n<p><strong>Partners</strong> - Create this is a <code>custom post type</code> since they need single pages (something like example.com/partner/partner1).</p>\n\n<p><strong>Projects</strong> - Create a <code>taxonomy</code> called \"projects\". The terms of that taxonomy will be your projects. Associate your taxonomy with the \"partners\" custom post type you created. This is the best way to share the same projects across partners.</p>\n\n<p>Edit: If you want to create a permalink structure like <code>example.com/{partner}/{project}</code> then you can easily do that using custom rewrite rules.</p>\n\n<pre><code>add_rewrite_rule(\n 'partner/([A-Za-z0-9\\-\\_]+)/?$',\n 'index.php?pagename={your-template-slug}&project_slug=$matches[1]',\n 'top'\n);\n</code></pre>\n\n<p>Using WordPress query vars you can access the <code>project_slug</code> variable in your template and get the term object using <code>get_term_by()</code>.</p>\n\n<p>My proposed structure takes full advantage of how the WordPress core was designed. Doing it this way is also the most flexible way of structuring it, allowing you to easily add new templates in the future if your client requests them, whether it's an archive of all the projects, viewing projects associated to multiple specific partners, partner profiles without projects, etc.</p>\n\n<p>The custom rewrite rules are completely optional, btw, but you'd need them if you want your custom permalink structure <em>and</em> want to use this data structure.</p>\n\n<p>Edit: -1 points? Alright... this site has gotta be filled with amateurs.</p>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101774/"
] |
I want to create shortcode like [genre] for WordPress.
```
add_action( 'init', 'cptui_register_my_cpts_movie' );
function cptui_register_my_cpts_movie() {
$labels = array(
"name" => __( 'MOVIE', '' ),
"singular_name" => __( 'Movie', '' ),
"menu_name" => __( 'MOVIES LIBRARY', '' ),
"all_items" => __( 'All Movies', '' ),
"add_new" => __( 'Add New Movie', '' ),
"add_new_item" => __( 'Add New Movie', '' ),
"edit" => __( 'Edit', '' ),
"edit_item" => __( 'Edit Movie', '' ),
"new_item" => __( 'New Movie', '' ),
"view" => __( 'View', '' ),
"view_item" => __( 'View Movie', '' ),
"search_items" => __( 'Search Movie', '' ),
"not_found" => __( 'No Movies found', '' ),
"not_found_in_trash" => __( 'No Movies found in Trash', '' ),
"parent_item_colon" => __( 'Parent Movie', '' ),
);
$args = array(
"label" => __( 'MOVIE', '' ),
"labels" => $labels,
"description" => "All Publish Tools for Movies",
"public" => true,
"publicly_queryable" => false,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "movie", "with_front" => true ),
"query_var" => true,
"supports" => array( "title", "editor", "comments", "revisions", "thumbnail" ),
"taxonomies" => array( "genre", "year", "quality", "country", "awards", "type", "stars", "subtitle" ),
);
register_post_type( "movie", $args );
// End of cptui_register_my_cpts_movie()
}
```
I want to show 'genre' in shortcode
```
function shortcode_for_genre() {
ob_start();
the_terms( $post->ID, array( 'taxonomy' => 'genre',), '', ', ', ' ' );
return ob_get_clean();
}
add_shortcode ('genre', 'shortcode_for_genre');
```
I'm tried above code and few other but no one works. This shortcode show genre of post. like drama, action. etc.
|
I would not use WordPress pages nor articles for this.
Simply, create a new custom post type called "Projects", with a plugin like Types, then create a new custom taxonomy "Partners" and associate it with that custom post type.
Clean and easy structure.
|
237,352 |
<p>I want to make custom button for some products in place of add to cart button on shop page and set dynamic relinking to some other page. So I made a checkbox at the product page and if that checkbox is enabled then the custom button with different link will be visible to that product. here is the code for checkbox:</p>
<pre><code>add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
add_action( 'add_meta_boxes', 'wdm_add_customize_enable_metabox' );
function wdm_add_customize_enable_metabox() {
add_meta_box(
'Checkbox_metabox',
'Check if you want to enable customization button',
'wdm_enable_callback',
'product',
'normal',
'high'
);
}
function wdm_enable_callback( $product ) {
$custom = get_post_custom( $product -> ID );
if( isset($custom[ "_wcm_custom_design_checkbox" ][0] ) ) {
$meta_box_check = $custom[ "_wcm_custom_design_checkbox" ][0];
}
else {
$meta_box_check = FALSE;
}
?>
<tr>
<td>Enable design panel at frontend?</td>
<td><input type="checkbox" name="wcm_enable_checkbox" id="wcm_enable_checkbox" <?php if ( $meta_box_check == true ) { ?> checked="checked"<?php } ?> /></td>
</tr>
<tr>
<?php
}
add_action( 'save_post', 'wdm_save_meta_check_box_data', 10,2 );
function wdm_save_meta_check_box_data( $post_id, $product ){
if ( $product -> post_type == 'product' ) {
if ( isset($_POST["wcm_enable_checkbox"] ) && $_POST["wcm_enable_checkbox"] ) {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', $_POST["wcm_enable_checkbox"] );
}
else {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', '');
}
}
}
</code></pre>
<p>The above code is working fine. I used this code into theme <code>add_to_cart</code> loop and here my only problem is how to get custom <code>add_to_cart_url()</code> for custom links and how to change the <code>add_to_cart_text()</code> text to whatever I want.</p>
<p>Here are the changes I made to <code>add_to_cart.php</code>:</p>
<pre><code>global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),//Here i want my own urls
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',//own css for custom text to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
</code></pre>
|
[
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement. By doing this it gets the page url and links it to custom button. \nThankx all for support :)</p>\n"
},
{
"answer_id": 237372,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": true,
"text": "<p>Per <a href=\"https://wordpress.stackexchange.com/users/101657/ashish-pariyani\">Ashish's</a> answer that's been posted, below is the update code for clarification with the correct answer by switching <code>add_to_cart_url()</code> to <code>get_permalink()</code>:</p>\n\n<pre><code>global $product, $post;\n$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );\n\nif ( $hasCustomization == 'on' ) {\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> get_permalink() ),\n esc_attr( $product->id ),\n esc_attr( $product->get_sku() ),\n $product->is_purchasable() ? '' : '',to show\n esc_attr( $product->product_type ),\n esc_html( $product->add_to_cart_text() )// Custom Text\n ),\n $product\n );\n}\n\nelse{\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> add_to_cart_url() ),\n esc_attr( $product -> id ),\n esc_attr( $product -> get_sku() ),\n $product -> is_purchasable() ? 'add_to_cart_button' : '',\n esc_attr( $product -> product_type ),\n esc_html( $product -> add_to_cart_text() )\n ),\n $product\n );\n}\n?>\n</code></pre>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101657/"
] |
I want to make custom button for some products in place of add to cart button on shop page and set dynamic relinking to some other page. So I made a checkbox at the product page and if that checkbox is enabled then the custom button with different link will be visible to that product. here is the code for checkbox:
```
add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
add_action( 'add_meta_boxes', 'wdm_add_customize_enable_metabox' );
function wdm_add_customize_enable_metabox() {
add_meta_box(
'Checkbox_metabox',
'Check if you want to enable customization button',
'wdm_enable_callback',
'product',
'normal',
'high'
);
}
function wdm_enable_callback( $product ) {
$custom = get_post_custom( $product -> ID );
if( isset($custom[ "_wcm_custom_design_checkbox" ][0] ) ) {
$meta_box_check = $custom[ "_wcm_custom_design_checkbox" ][0];
}
else {
$meta_box_check = FALSE;
}
?>
<tr>
<td>Enable design panel at frontend?</td>
<td><input type="checkbox" name="wcm_enable_checkbox" id="wcm_enable_checkbox" <?php if ( $meta_box_check == true ) { ?> checked="checked"<?php } ?> /></td>
</tr>
<tr>
<?php
}
add_action( 'save_post', 'wdm_save_meta_check_box_data', 10,2 );
function wdm_save_meta_check_box_data( $post_id, $product ){
if ( $product -> post_type == 'product' ) {
if ( isset($_POST["wcm_enable_checkbox"] ) && $_POST["wcm_enable_checkbox"] ) {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', $_POST["wcm_enable_checkbox"] );
}
else {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', '');
}
}
}
```
The above code is working fine. I used this code into theme `add_to_cart` loop and here my only problem is how to get custom `add_to_cart_url()` for custom links and how to change the `add_to_cart_text()` text to whatever I want.
Here are the changes I made to `add_to_cart.php`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),//Here i want my own urls
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',//own css for custom text to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
```
|
Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
```
|
237,365 |
<p>I want to add an <code>id="myid"</code> to shortcode embedded iframe:-</p>
<pre><code>$video_url = get_post_meta($post_id, 'video_url',true);
//or
$video_url .= 'video url';
$check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed]'. $video_url .'[/embed]' );
echo $check_embeds;
</code></pre>
<p>This code helps me to display video through custom meta box just using a video url. And additionally I want add an ID to iframe here, example:- <code><iframe id="myid" src=""></iframe></code>like this.
Can anybody help me to fix the issue?</p>
|
[
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement. By doing this it gets the page url and links it to custom button. \nThankx all for support :)</p>\n"
},
{
"answer_id": 237372,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": true,
"text": "<p>Per <a href=\"https://wordpress.stackexchange.com/users/101657/ashish-pariyani\">Ashish's</a> answer that's been posted, below is the update code for clarification with the correct answer by switching <code>add_to_cart_url()</code> to <code>get_permalink()</code>:</p>\n\n<pre><code>global $product, $post;\n$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );\n\nif ( $hasCustomization == 'on' ) {\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> get_permalink() ),\n esc_attr( $product->id ),\n esc_attr( $product->get_sku() ),\n $product->is_purchasable() ? '' : '',to show\n esc_attr( $product->product_type ),\n esc_html( $product->add_to_cart_text() )// Custom Text\n ),\n $product\n );\n}\n\nelse{\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> add_to_cart_url() ),\n esc_attr( $product -> id ),\n esc_attr( $product -> get_sku() ),\n $product -> is_purchasable() ? 'add_to_cart_button' : '',\n esc_attr( $product -> product_type ),\n esc_html( $product -> add_to_cart_text() )\n ),\n $product\n );\n}\n?>\n</code></pre>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101698/"
] |
I want to add an `id="myid"` to shortcode embedded iframe:-
```
$video_url = get_post_meta($post_id, 'video_url',true);
//or
$video_url .= 'video url';
$check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed]'. $video_url .'[/embed]' );
echo $check_embeds;
```
This code helps me to display video through custom meta box just using a video url. And additionally I want add an ID to iframe here, example:- `<iframe id="myid" src=""></iframe>`like this.
Can anybody help me to fix the issue?
|
Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
```
|
237,368 |
<p><a href="https://danscartoons.com" rel="nofollow noreferrer"><strong>My index page</strong></a> has three button on top upper right corner. They are Facebook, Twitter and RSS.</p>
<p>I have accessed my <code>header.php</code> to add the appropriate URL's for both Facebook & Twitter (I did not add RSS feed as of yet) below is a screenshot of what I have so far:</p>
<p><a href="https://i.stack.imgur.com/2BMUx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2BMUx.jpg" alt="screenshot"></a></p>
<p>However, the icons aren't going to the appropriate URL, why is that?</p>
|
[
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement. By doing this it gets the page url and links it to custom button. \nThankx all for support :)</p>\n"
},
{
"answer_id": 237372,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": true,
"text": "<p>Per <a href=\"https://wordpress.stackexchange.com/users/101657/ashish-pariyani\">Ashish's</a> answer that's been posted, below is the update code for clarification with the correct answer by switching <code>add_to_cart_url()</code> to <code>get_permalink()</code>:</p>\n\n<pre><code>global $product, $post;\n$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );\n\nif ( $hasCustomization == 'on' ) {\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> get_permalink() ),\n esc_attr( $product->id ),\n esc_attr( $product->get_sku() ),\n $product->is_purchasable() ? '' : '',to show\n esc_attr( $product->product_type ),\n esc_html( $product->add_to_cart_text() )// Custom Text\n ),\n $product\n );\n}\n\nelse{\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> add_to_cart_url() ),\n esc_attr( $product -> id ),\n esc_attr( $product -> get_sku() ),\n $product -> is_purchasable() ? 'add_to_cart_button' : '',\n esc_attr( $product -> product_type ),\n esc_html( $product -> add_to_cart_text() )\n ),\n $product\n );\n}\n?>\n</code></pre>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99226/"
] |
[**My index page**](https://danscartoons.com) has three button on top upper right corner. They are Facebook, Twitter and RSS.
I have accessed my `header.php` to add the appropriate URL's for both Facebook & Twitter (I did not add RSS feed as of yet) below is a screenshot of what I have so far:
[](https://i.stack.imgur.com/2BMUx.jpg)
However, the icons aren't going to the appropriate URL, why is that?
|
Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
```
|
237,374 |
<p>Is there any neat way of disabling the figures/images in a certain post category until a user logs in. I want the entire post content to be visible except for the images.</p>
<p>I'm not a programmer and I have not found any useful plugin.</p>
|
[
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement. By doing this it gets the page url and links it to custom button. \nThankx all for support :)</p>\n"
},
{
"answer_id": 237372,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": true,
"text": "<p>Per <a href=\"https://wordpress.stackexchange.com/users/101657/ashish-pariyani\">Ashish's</a> answer that's been posted, below is the update code for clarification with the correct answer by switching <code>add_to_cart_url()</code> to <code>get_permalink()</code>:</p>\n\n<pre><code>global $product, $post;\n$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );\n\nif ( $hasCustomization == 'on' ) {\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> get_permalink() ),\n esc_attr( $product->id ),\n esc_attr( $product->get_sku() ),\n $product->is_purchasable() ? '' : '',to show\n esc_attr( $product->product_type ),\n esc_html( $product->add_to_cart_text() )// Custom Text\n ),\n $product\n );\n}\n\nelse{\n echo apply_filters(\n 'woocommerce_loop_add_to_cart_link',\n sprintf(\n '<a href=\"%s\" rel=\"nofollow\" data-product_id=\"%s\" data-product_sku=\"%s\" class=\"add_to_cart %s product_type_%s\">%s</a>',\n esc_url( $product -> add_to_cart_url() ),\n esc_attr( $product -> id ),\n esc_attr( $product -> get_sku() ),\n $product -> is_purchasable() ? 'add_to_cart_button' : '',\n esc_attr( $product -> product_type ),\n esc_html( $product -> add_to_cart_text() )\n ),\n $product\n );\n}\n?>\n</code></pre>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101304/"
] |
Is there any neat way of disabling the figures/images in a certain post category until a user logs in. I want the entire post content to be visible except for the images.
I'm not a programmer and I have not found any useful plugin.
|
Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
```
|
237,381 |
<p>Suppose we registered the <code>composers</code> and the <code>interprets</code> custom taxonomies.</p>
<p>The <code>composers</code> taxonomy could have the following terms:</p>
<ul>
<li>Wolfgang Amadeus Mozart</li>
<li>Ludwig van Beethoven</li>
<li>Richard Wagner</li>
</ul>
<p>The <code>interprets</code> taxonomy could have the following terms:</p>
<ul>
<li>Glenn Gould</li>
<li>Daniel Barenboim</li>
<li>Vienna State Opera</li>
</ul>
<p>I am wondering whether the WordPress template hierarchy has a special file , like <code>taxonomy-terms.php</code>, to list taxonomy terms with a simple loop:</p>
<pre><code><?php
while ( have_posts() ) : the_post();
the_title();
endwhile;
?>
</code></pre>
<p>This would print (assuming the <code>/%postname%/</code> permalink setting): </p>
<ul>
<li><code>Wolfgang Amadeus Mozart</code>, <code>Ludwig van Beethoven</code>, <code>Richard Wagner</code> when viewing <code>example.com/composers</code></li>
<li><code>Glenn Gould</code>, <code>Daniel Barenboim</code>, <code>Vienna State Opera</code> when viewing <code>example.com/interprets</code></li>
</ul>
<p>If not, I would like to know the best way to implement this. I would create a page template for each taxonomy, <code>template-composers-terms.php</code> and <code>template-interprets-terms.php</code> and list terms using something like the following code:</p>
<pre><code><?php
/* Template Name: List of composers */ // or 'List of interprets'
$terms = get_terms( 'composers' ); // or get_terms( 'interprets' )
foreach ( $terms as $term ) :
echo $term->name;
endforeach;
?>
</code></pre>
<p>Then, I create two pages, "Composers" and "Interprets", to which I respectively assigned the "List of composers" and "List of interprets" templates.</p>
<p>I'm not very comfortable using this method, because it requires creating a new file for each taxonomy.</p>
|
[
{
"answer_id": 237379,
"author": "markratledge",
"author_id": 268,
"author_profile": "https://wordpress.stackexchange.com/users/268",
"pm_score": 3,
"selected": true,
"text": "<p>PHP errors are the cause of whitescreens. You will have error logs in your Cpanel at Hostgator, but it's much easier to use the debug logs that are available in WordPress. <em>(For debugging outside of the WordPress environment, see <a href=\"http://php.net/manual/en/debugger-about.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/debugger-about.php</a> about PHP's own debugger and third-party debuggers).</em></p>\n\n<p>And, there are several other debugging methods you should learn when working with WordPress - in order to handle PHP as well as to debug database queries and find/fix Javascript errors - since WordPress (and themes and plugins) use a database as well as Javascript.</p>\n\n<p><strong>PHP</strong></p>\n\n<p>For PHP debugging and finding the , use the built-in WordPress function <code>WP_DEBUG</code>. See <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/WP_DEBUG</a></p>\n\n<p>Add</p>\n\n<p><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_LOG', true );</code></p>\n\n<p>in wp-config.php and the debug.log file will be in wp-content.</p>\n\n<p>Add this line</p>\n\n<p><code>define( 'WP_DEBUG_DISPLAY', true);</code></p>\n\n<p>to wp-config.php to log <em>and</em> dump them to the browser.</p>\n\n<p><em>See this answer to find out how to change the location of the <code>debug.log</code> file: <a href=\"https://wordpress.stackexchange.com/questions/84132/is-it-possible-to-change-the-log-file-location-for-wp-debug-log\">Is it possible to change the log file location for WP_DEBUG_LOG?</a></em></p>\n\n<p><strong>Database queries:</strong></p>\n\n<p>Also look at the plugins <a href=\"https://wordpress.org/plugins/debug-objects/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/debug-objects/</a> and <a href=\"https://wordpress.org/plugins/debug-bar/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/debug-bar/</a> for help with database queries.\nYou need to set</p>\n\n<p><code>define('SAVEQUERIES', true);</code></p>\n\n<p>in wp-config.php to debug database queries.</p>\n\n<p><strong>Javascript:</strong></p>\n\n<p>For Javascript, you can turn on</p>\n\n<p><code>define('SCRIPT_DEBUG', true);</code></p>\n\n<p>too, in wp-config.php.</p>\n\n<p>And be sure and learn how to use the developer tools in <a href=\"https://developer.mozilla.org/en-US/docs/Tools\" rel=\"nofollow noreferrer\">Firefox</a> (or <a href=\"http://getfirebug.com/\" rel=\"nofollow noreferrer\">Firebug</a>) or <a href=\"https://developers.chrome.com/devtools/\" rel=\"nofollow noreferrer\">Chrome</a> or <a href=\"https://developer.apple.com/safari/tools/\" rel=\"nofollow noreferrer\">Safari</a> or <a href=\"http://msdn.microsoft.com/en-us/library/ie/hh673541(v=vs.85).aspx\" rel=\"nofollow noreferrer\">IE</a> to work with Javascript as well as HTML and CSS issues.</p>\n"
},
{
"answer_id": 237424,
"author": "arqam",
"author_id": 73878,
"author_profile": "https://wordpress.stackexchange.com/users/73878",
"pm_score": 1,
"selected": false,
"text": "<p>Okay I searched a lot and there seems to be a lot of problem in making a change in the setting if you have a shared server.</p>\n\n<p>So the best thing to do is add a php code debugger extenstion in your chrome.</p>\n\n<p>I used this and it works perfectly : <a href=\"https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef?hl=en\" rel=\"nofollow\">PHP Console</a></p>\n\n<p>But do tell me if anyone find the correct approach for the question. Till then this works perfectly.</p>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237381",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88041/"
] |
Suppose we registered the `composers` and the `interprets` custom taxonomies.
The `composers` taxonomy could have the following terms:
* Wolfgang Amadeus Mozart
* Ludwig van Beethoven
* Richard Wagner
The `interprets` taxonomy could have the following terms:
* Glenn Gould
* Daniel Barenboim
* Vienna State Opera
I am wondering whether the WordPress template hierarchy has a special file , like `taxonomy-terms.php`, to list taxonomy terms with a simple loop:
```
<?php
while ( have_posts() ) : the_post();
the_title();
endwhile;
?>
```
This would print (assuming the `/%postname%/` permalink setting):
* `Wolfgang Amadeus Mozart`, `Ludwig van Beethoven`, `Richard Wagner` when viewing `example.com/composers`
* `Glenn Gould`, `Daniel Barenboim`, `Vienna State Opera` when viewing `example.com/interprets`
If not, I would like to know the best way to implement this. I would create a page template for each taxonomy, `template-composers-terms.php` and `template-interprets-terms.php` and list terms using something like the following code:
```
<?php
/* Template Name: List of composers */ // or 'List of interprets'
$terms = get_terms( 'composers' ); // or get_terms( 'interprets' )
foreach ( $terms as $term ) :
echo $term->name;
endforeach;
?>
```
Then, I create two pages, "Composers" and "Interprets", to which I respectively assigned the "List of composers" and "List of interprets" templates.
I'm not very comfortable using this method, because it requires creating a new file for each taxonomy.
|
PHP errors are the cause of whitescreens. You will have error logs in your Cpanel at Hostgator, but it's much easier to use the debug logs that are available in WordPress. *(For debugging outside of the WordPress environment, see <http://php.net/manual/en/debugger-about.php> about PHP's own debugger and third-party debuggers).*
And, there are several other debugging methods you should learn when working with WordPress - in order to handle PHP as well as to debug database queries and find/fix Javascript errors - since WordPress (and themes and plugins) use a database as well as Javascript.
**PHP**
For PHP debugging and finding the , use the built-in WordPress function `WP_DEBUG`. See <https://codex.wordpress.org/WP_DEBUG>
Add
`define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );`
in wp-config.php and the debug.log file will be in wp-content.
Add this line
`define( 'WP_DEBUG_DISPLAY', true);`
to wp-config.php to log *and* dump them to the browser.
*See this answer to find out how to change the location of the `debug.log` file: [Is it possible to change the log file location for WP\_DEBUG\_LOG?](https://wordpress.stackexchange.com/questions/84132/is-it-possible-to-change-the-log-file-location-for-wp-debug-log)*
**Database queries:**
Also look at the plugins <https://wordpress.org/plugins/debug-objects/> and <https://wordpress.org/plugins/debug-bar/> for help with database queries.
You need to set
`define('SAVEQUERIES', true);`
in wp-config.php to debug database queries.
**Javascript:**
For Javascript, you can turn on
`define('SCRIPT_DEBUG', true);`
too, in wp-config.php.
And be sure and learn how to use the developer tools in [Firefox](https://developer.mozilla.org/en-US/docs/Tools) (or [Firebug](http://getfirebug.com/)) or [Chrome](https://developers.chrome.com/devtools/) or [Safari](https://developer.apple.com/safari/tools/) or [IE](http://msdn.microsoft.com/en-us/library/ie/hh673541(v=vs.85).aspx) to work with Javascript as well as HTML and CSS issues.
|
237,385 |
<p>so i wrote a simple script and enqueued it properly.</p>
<p><strong>my-jquery-script.js:</strong></p>
<pre><code>jQuery(document).ready(function($) {
$('#some_id').on('click','.clone',function(e){
alert('clicked');
/*.....*/
e.preventDefault();
});
});
</code></pre>
<p><strong>functions.php:</strong></p>
<pre><code>add_action( 'wp_enqueue_scripts', 'my_function' );
function my_function() {
wp_enqueue_script( 'my-jquery-script', get_stylesheet_directory_uri() . '/js/my-jquery-script.js' );
}
</code></pre>
<p><strong>some-page.php:</strong></p>
<pre><code><?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
</form>
</body>
<?php wp_footer(); ?>
</code></pre>
<p>it's not working but when i include jQuery script manually into <em>some-page.php</em> like this:</p>
<pre><code><?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
<script type='text/javascript' src='<?php echo get_stylesheet_directory_uri() . "/js/my-jquery-script.js"; ?>'></script>
</form>
</body>
<?php wp_footer(); ?>
</code></pre>
<p>it's working but "$(document).ready () fires twice" as mentioned here: <a href="https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice">https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice</a></p>
<p>What am i doing wrong? Any help would be appreciated.</p>
<p><em>update: I also noticed that <code>$(document.body).on('click','.clone',function(e){ }</code> selector is working instead of id selector.</em></p>
|
[
{
"answer_id": 237387,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>If your script depends on jQuery, you have to declare that dependency to make sure WordPress will enqueue it earlier than yours.</p>\n\n<pre><code>wp_enqueue_script( \n 'my-jquery-script', \n get_stylesheet_directory_uri() . '/js/my-jquery-script.js',\n [ 'jquery' ] /* declare the dependency */\n);\n</code></pre>\n"
},
{
"answer_id": 237514,
"author": "user2397435",
"author_id": 101800,
"author_profile": "https://wordpress.stackexchange.com/users/101800",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up changing theme and it resolved my problem.</p>\n"
}
] |
2016/08/28
|
[
"https://wordpress.stackexchange.com/questions/237385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101800/"
] |
so i wrote a simple script and enqueued it properly.
**my-jquery-script.js:**
```
jQuery(document).ready(function($) {
$('#some_id').on('click','.clone',function(e){
alert('clicked');
/*.....*/
e.preventDefault();
});
});
```
**functions.php:**
```
add_action( 'wp_enqueue_scripts', 'my_function' );
function my_function() {
wp_enqueue_script( 'my-jquery-script', get_stylesheet_directory_uri() . '/js/my-jquery-script.js' );
}
```
**some-page.php:**
```
<?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
</form>
</body>
<?php wp_footer(); ?>
```
it's not working but when i include jQuery script manually into *some-page.php* like this:
```
<?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
<script type='text/javascript' src='<?php echo get_stylesheet_directory_uri() . "/js/my-jquery-script.js"; ?>'></script>
</form>
</body>
<?php wp_footer(); ?>
```
it's working but "$(document).ready () fires twice" as mentioned here: <https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice>
What am i doing wrong? Any help would be appreciated.
*update: I also noticed that `$(document.body).on('click','.clone',function(e){ }` selector is working instead of id selector.*
|
If your script depends on jQuery, you have to declare that dependency to make sure WordPress will enqueue it earlier than yours.
```
wp_enqueue_script(
'my-jquery-script',
get_stylesheet_directory_uri() . '/js/my-jquery-script.js',
[ 'jquery' ] /* declare the dependency */
);
```
|
237,395 |
<p>I've been using site/page builders for so long in WP that I'm OOTL with the current setup of templates, stylesheets and functions in the newer WP builds.</p>
<p>I've got an older theme that I need to make a unique page for and am struggling to understand how to use a specific stylesheet for this page template.
If the page template is referral.php and I've added the header and footer into the template (so that I can use unique elements compared to the main site), I can see that the header brings in the sytlesheet using <code><?php wp_head(); ?></code>.</p>
<p><strong>What's the best way for this page to use the majority of the parent and child theme styles, but process my specific unique styles for this page ONLY?</strong></p>
<p>Is it to use <code><link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>/referral-style.css"></code> or is it to create a functions file in the child theme directory and use something like:</p>
<pre><code><?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php
function themeslug_enqueue_style() {
if( is_page( 'referral' ) ) { // Only add this style onto the Blog page.
wp_enqueue_style( 'referral-style', get_stylesheet_uri() );
}
if ( is_child_theme() ) {
// load parent stylesheet first if this is a child theme
wp_enqueue_style( 'parent-stylesheet', trailingslashit( get_template_directory_uri() ) . 'style.css', false );
}
// load active theme stylesheet in both cases
wp_enqueue_style( 'theme-stylesheet', get_stylesheet_uri(), false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
</code></pre>
|
[
{
"answer_id": 237398,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't need to use often some scripts or styles, it's better to register them before <code>enqueue</code>. It's kind of informing WordPress that \"Please register those scripts and style, I'm gonna need them later.\"-</p>\n\n<pre><code><?php\n\n// Exit if accessed directly\nif ( !defined( 'ABSPATH' ) ) {\n exit;\n}\n\n?>\n<?php\nfunction themeslug_enqueue_style() {\n wp_register_style( 'referral-style', get_stylesheet_uri() );\n wp_register_style( 'parent-stylesheet', trailingslashit( get_template_directory_uri() ) . 'style.css', false );\n if( is_page( 'referral' ) ) { // Only add this style onto the Blog page.\n wp_enqueue_style( 'referral-style' );\n }\n if ( is_child_theme() ) {\n // load parent stylesheet first if this is a child theme\n wp_enqueue_style( 'parent-stylesheet' );\n }\n // load active theme stylesheet in both cases\n wp_enqueue_style( 'theme-stylesheet', get_stylesheet_uri(), false );\n}\n\nadd_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );\n</code></pre>\n"
},
{
"answer_id": 237411,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 2,
"selected": false,
"text": "<p>The preferred way is to use <code>add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );</code> within your child theme <code>functions.php</code> file or directly in your <code>referral.php</code> template page. Either way, it's by using <code>add_action</code> and not by echoing into the <code><link></code> tag.</p>\n\n<p>Registering your style is also a recommended practice. The one benefit I would see in your case is that you could register all your styles in your <code>functions.php</code> with for each file their dependencies, then you would have to enqueue only one handle in your referral page and WP would load all other files registered as dependencies of your <code>referral-style.css</code>.</p>\n\n<p>For instance, in <code>functions.php</code></p>\n\n<pre><code>function themeslug_enqueue_style() {\n wp_register_style( 'referral-style', get_stylesheet_directory_uri() . 'path/to/your/css-file', array( 'theme-stylesheet' ) );\n wp_register_style( 'theme-stylesheet', get_stylesheet_uri() );\n\n // load active theme stylesheet in all cases\n wp_enqueue_style( 'theme-stylesheet' );\n\n}\nadd_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );\n</code></pre>\n\n<p>and in <code>referral.php</code></p>\n\n<pre><code>function my_referral_enqueue_style() {\n\n wp_enqueue_style( 'referral-style' ); // will load theme-stylesheet automatically\n\n}\nadd_action( 'wp_enqueue_scripts', 'my_referral_enqueue_style' );\n</code></pre>\n\n<p>of course you can omit this in <code>referral.php</code> and still add a conditional in your <code>functions.php</code></p>\n\n<pre><code>if( is_page( 'referral' ) ) { \n\n wp_enqueue_style( 'referral-style' );\n\n}\n</code></pre>\n\n<p>But I wanted to show you both ways</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30889/"
] |
I've been using site/page builders for so long in WP that I'm OOTL with the current setup of templates, stylesheets and functions in the newer WP builds.
I've got an older theme that I need to make a unique page for and am struggling to understand how to use a specific stylesheet for this page template.
If the page template is referral.php and I've added the header and footer into the template (so that I can use unique elements compared to the main site), I can see that the header brings in the sytlesheet using `<?php wp_head(); ?>`.
**What's the best way for this page to use the majority of the parent and child theme styles, but process my specific unique styles for this page ONLY?**
Is it to use `<link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>/referral-style.css">` or is it to create a functions file in the child theme directory and use something like:
```
<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php
function themeslug_enqueue_style() {
if( is_page( 'referral' ) ) { // Only add this style onto the Blog page.
wp_enqueue_style( 'referral-style', get_stylesheet_uri() );
}
if ( is_child_theme() ) {
// load parent stylesheet first if this is a child theme
wp_enqueue_style( 'parent-stylesheet', trailingslashit( get_template_directory_uri() ) . 'style.css', false );
}
// load active theme stylesheet in both cases
wp_enqueue_style( 'theme-stylesheet', get_stylesheet_uri(), false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
```
|
The preferred way is to use `add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );` within your child theme `functions.php` file or directly in your `referral.php` template page. Either way, it's by using `add_action` and not by echoing into the `<link>` tag.
Registering your style is also a recommended practice. The one benefit I would see in your case is that you could register all your styles in your `functions.php` with for each file their dependencies, then you would have to enqueue only one handle in your referral page and WP would load all other files registered as dependencies of your `referral-style.css`.
For instance, in `functions.php`
```
function themeslug_enqueue_style() {
wp_register_style( 'referral-style', get_stylesheet_directory_uri() . 'path/to/your/css-file', array( 'theme-stylesheet' ) );
wp_register_style( 'theme-stylesheet', get_stylesheet_uri() );
// load active theme stylesheet in all cases
wp_enqueue_style( 'theme-stylesheet' );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
```
and in `referral.php`
```
function my_referral_enqueue_style() {
wp_enqueue_style( 'referral-style' ); // will load theme-stylesheet automatically
}
add_action( 'wp_enqueue_scripts', 'my_referral_enqueue_style' );
```
of course you can omit this in `referral.php` and still add a conditional in your `functions.php`
```
if( is_page( 'referral' ) ) {
wp_enqueue_style( 'referral-style' );
}
```
But I wanted to show you both ways
|
237,410 |
<p>I'm new to WordPress, and I'm having an issue with "The Loop."
I have 2 custom post type named 'book' and 'author'
.in author post type I have custom filed checkbox which can choose between author and translator.
also in book post type I have 2 metaboxs which user must choose the name of author and translator from those.
all metabox and custom post type work well but when I want to call them and use the values of each meta-box I have problem.
my code can read author values well, but translator values just show the last value of author and I cant' figure out why this happen ?
I think foreach is the problem. but I don't know how can I solve it.
here is my code for single-book.php</p>
<pre><code><?php $args = array( 'post_type' => 'book');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post();
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
$vals=get_post_meta($post_id, $key2, true);
$values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
echo '<h4 class="text-right color-style"> نویسنده : ';
foreach($values as $value){
$author=get_post($value);
echo '<a href="'.
get_post_permalink($value).'" target="_blank">'.
$author->post_title .'</a> ، ' ;}
echo '</h4>';
echo '<h4 class="text-right color-style"> مترجم : ';
foreach($vals as $val){
$trans=get_post($val);
echo '<a href="'.
get_post_permalink($val).'" target="_blank">'.
$author->post_title.'</a>، ';}
echo '</h4>';
</code></pre>
<p>any idea would be appreciated. </p>
|
[
{
"answer_id": 237414,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 2,
"selected": true,
"text": "<p>I believe your issue is with <code>$vals=get_post_meta($post_id, $key2, true);</code></p>\n\n<p>If you check the codex, the last parameter for <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow\">get_post_meta</a> is whether to return a single value or array of values. You have set it to <code>true</code> which means return only one value.</p>\n\n<p>Try it with <code>false</code> (the default) it should work.</p>\n"
},
{
"answer_id": 237435,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p>I cant comment bynicolas answer, but I agree with him.\nIf I understood correctly your issue, it is because your are using <code>true</code> at the end of:</p>\n\n<pre><code>$vals=get_post_meta($post_id, $key2, true);\n$values = get_post_meta( $post_id, $key, true );\n</code></pre>\n\n<p>When you use true, from the <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow\">Codex</a>:</p>\n\n<blockquote>\n <p><strong>$single</strong> (bool) (Optional) Whether to return a single value.</p>\n \n <p><strong>Return</strong> (mixed) Will be an array if $single is false. Will be value of meta data field if $single is true.</p>\n</blockquote>\n\n<p>You can't <code>foreach</code> a <code>string</code>, only <code>arrays</code>, hence why if you don't use <code>false</code> instead, your code won't work.</p>\n\n<p>Or, if you only want the first result of the <code>post_meta</code>, keep using <code>true</code>, but then why do you use the foreach? You dont need it, you can simply use this:</p>\n\n<pre><code>if($value != '') {\n $author=get_post($value);\n echo '<a href=\"'.get_post_permalink($value).'\" target=\"_blank\">'.$author->post_title .'</a> ، ' ;\n}\n</code></pre>\n"
},
{
"answer_id": 237540,
"author": "Andrei",
"author_id": 26395,
"author_profile": "https://wordpress.stackexchange.com/users/26395",
"pm_score": 0,
"selected": false,
"text": "<p>Careful on line 11:</p>\n\n<pre><code> $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );\n ?>\n echo '<h4 class=\"text-right color-style\"> نویسنده : ';\n</code></pre>\n\n<p>Do you use exactly this code? Because you close the PHP syntax exactly after getting the <code>$feat_image</code> and after that, the code continues with PHP syntax like <code>echo</code>.</p>\n\n<p>I believe that the code breaks because of that little <code>?></code> and the first loop never ends.</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101035/"
] |
I'm new to WordPress, and I'm having an issue with "The Loop."
I have 2 custom post type named 'book' and 'author'
.in author post type I have custom filed checkbox which can choose between author and translator.
also in book post type I have 2 metaboxs which user must choose the name of author and translator from those.
all metabox and custom post type work well but when I want to call them and use the values of each meta-box I have problem.
my code can read author values well, but translator values just show the last value of author and I cant' figure out why this happen ?
I think foreach is the problem. but I don't know how can I solve it.
here is my code for single-book.php
```
<?php $args = array( 'post_type' => 'book');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post();
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
$vals=get_post_meta($post_id, $key2, true);
$values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
echo '<h4 class="text-right color-style"> نویسنده : ';
foreach($values as $value){
$author=get_post($value);
echo '<a href="'.
get_post_permalink($value).'" target="_blank">'.
$author->post_title .'</a> ، ' ;}
echo '</h4>';
echo '<h4 class="text-right color-style"> مترجم : ';
foreach($vals as $val){
$trans=get_post($val);
echo '<a href="'.
get_post_permalink($val).'" target="_blank">'.
$author->post_title.'</a>، ';}
echo '</h4>';
```
any idea would be appreciated.
|
I believe your issue is with `$vals=get_post_meta($post_id, $key2, true);`
If you check the codex, the last parameter for [get\_post\_meta](https://developer.wordpress.org/reference/functions/get_post_meta/) is whether to return a single value or array of values. You have set it to `true` which means return only one value.
Try it with `false` (the default) it should work.
|
237,427 |
<p>After getting so close to nailing my theme I've hit the last hurdle. Essentially I have three different areas on my homepage:</p>
<ol>
<li>The latest post appears in the header and styled as a featured post</li>
<li>Two posts below that styled as recent posts</li>
<li>The rest of the posts (10) in date order below those</li>
</ol>
<p>Latest post (1) and the two recent posts (2) are shown using a custom WP_Query and the remaining ten posts (3) are shown using the standard loop with an offset function which also solves the pagination BUT... there's a hiccup with page 2. For some reason, it's adding an extra three posts to the top of the list of posts (3)? After this, page 3 onwards, it's fine and works as it should. I should also mention that the latest and recent posts (1 and 2) are to be shown at the top at all times as you cycle through the pages.</p>
<p>Here the layout with the different areas and post numbers:</p>
<p><a href="https://i.stack.imgur.com/xXxdz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xXxdz.png" alt="Layout"></a></p>
<p>Here's the code used for the function that handles the main posts (3) and the pagination fix (the offset is used to skip the latest and recent posts shown above these):</p>
<pre><code>function offset_main_query ( $query ) {
if ( $query->is_home() && $query->is_main_query() && !$query->is_paged() ) {
$query->set( 'offset', '3' );
}
}
add_action( 'pre_get_posts', 'offset_main_query' );
</code></pre>
<p>Any help would be great as this is the last bit that's tripping me up.</p>
<p>Thanks :)</p>
|
[
{
"answer_id": 237444,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably try without the <code>&& !$query->is_paged()</code> (you already have 2 conditions that should be enough, even just the first one should work actually) and if that doesn't work, try to output the <code>$paged</code> value and see how you can tweak the function better.</p>\n\n<p>Some debug ideas:</p>\n\n<pre><code>// get current page we are on. If not set we can assume we are on page 1.\n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n// are we on page one?\nif(1 == $paged) {\n //true\n}\n</code></pre>\n"
},
{
"answer_id": 237457,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Here's a suggestion for a general way to support <strong>different</strong> number of posts on the <em>home page</em> than on the <em>other paginated pages</em>. We should use the <em>main query</em> instead of <em>sub-queries</em>, if possible.</p>\n\n<p><strong>Formula</strong></p>\n\n<p>It seems to make sense to take the <em>offset</em> for paginated pages as:</p>\n\n<pre><code>offset_op = ( paged - 1 ) * pp_op + ( pp_fp - pp_op ) + offset_fp \n = ( paged - 2 ) * pp_op + pp_fp + offset_fp \n</code></pre>\n\n<p>where <code>paged</code> (<em>pagination</em>), <code>pp_fp</code> (<em>posts per first page</em>), <code>pp_op</code> (<em>posts per other pages</em>) and offset_fp (<em>offset for the first page</em>) are non-negative integers.</p>\n\n<p>For <code>paged=1</code> the offset is <code>offset_fp</code>, else it's <code>offset_op</code> for other pages.</p>\n\n<p><strong>Example #1:</strong></p>\n\n<p>First we calculate the offset for few pages to better understand this:</p>\n\n<pre><code>For paged=1:\n offset_fp = 0\n\nFor paged=2:\n offset_op = (2-2)*10 + 13 + 0\n = 13\n\nFor paged=3:\n offset_op = (3-2)*10 + 13 + 0\n = 10+13\n = 23\n...\n</code></pre>\n\n<p>Here's a list of post indices on each page:</p>\n\n<pre><code>0,1,2,3,4,5,6,7,8,9,10,11,12 (offset_fp=0, pp_fp=13, paged=1)\n13,14,15,16,17,18,19,20,21,22 (offset_op=13, pp_op=10, paged=2)\n23,24,25,26, 27,28,29,30,31,32 (offset_op=23, pp_op=10, paged=3)\n...\n</code></pre>\n\n<p>We can see that the offset matches the indices.</p>\n\n<p><strong>Example #2:</strong></p>\n\n<p>Let's take <code>pp_fp = 3</code>, <code>pp_op = 5</code>, <code>offset_fp=4</code> and calculate the <em>offset_op</em>:</p>\n\n<pre><code>For paged=1:\n offset_fp = 4\n\nFor paged=2:\n offset_op = (2-2)*5 + 3 + 4\n = 7\n\nFor paged=3:\n offset_op = (3-2)*5 + 3 + 4\n = 5+3+4\n = 12\n...\n</code></pre>\n\n<p>and compare it to the indices:</p>\n\n<pre><code>4,5,6 (offset_fp=4, pp_fp=3, paged=1)\n7,8,9,10,11 (offset_op=7, pp_op=5, paged=2)\n12,13,14,15,16 (offset_op=12, pp_op=5, paged=3)\n...\n</code></pre>\n\n<p><strong>Demo Plugin</strong></p>\n\n<p>Here's a demo implementation:</p>\n\n<pre><code>/**\n * Plugin Name: WPSE demo\n */\nadd_action( 'pre_get_posts', function( \\WP_Query $query ) \n{\n // Nothing to do if backend or not home page or not the main query\n if ( is_admin() || ! $query->is_home() || ! $query->is_main_query() )\n return;\n\n // Get current pagination\n $paged = get_query_var( 'paged', 1 );\n\n // Modify sticky posts display\n $query->set( 'ignore_sticky_posts', true );\n\n // Modify post status\n $query->set( 'post_status', 'publish' );\n\n // Edit to your needs\n $pp_fp = 13; // posts per first page\n $pp_op = 10; // posts per other pages\n $offset_fp = 0; // offset for the first page\n\n // Offset for other pages than the first page\n $offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;\n\n // Modify offset\n $query->set( 'offset', $query->is_paged() ? $offset_op : $offset_fp );\n\n // Modify posts per page\n $query->set( 'posts_per_page', $query->is_paged() ? $pp_op : $pp_fp ); \n} );\n</code></pre>\n\n<p>Hope you can adjust it to your needs!</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99335/"
] |
After getting so close to nailing my theme I've hit the last hurdle. Essentially I have three different areas on my homepage:
1. The latest post appears in the header and styled as a featured post
2. Two posts below that styled as recent posts
3. The rest of the posts (10) in date order below those
Latest post (1) and the two recent posts (2) are shown using a custom WP\_Query and the remaining ten posts (3) are shown using the standard loop with an offset function which also solves the pagination BUT... there's a hiccup with page 2. For some reason, it's adding an extra three posts to the top of the list of posts (3)? After this, page 3 onwards, it's fine and works as it should. I should also mention that the latest and recent posts (1 and 2) are to be shown at the top at all times as you cycle through the pages.
Here the layout with the different areas and post numbers:
[](https://i.stack.imgur.com/xXxdz.png)
Here's the code used for the function that handles the main posts (3) and the pagination fix (the offset is used to skip the latest and recent posts shown above these):
```
function offset_main_query ( $query ) {
if ( $query->is_home() && $query->is_main_query() && !$query->is_paged() ) {
$query->set( 'offset', '3' );
}
}
add_action( 'pre_get_posts', 'offset_main_query' );
```
Any help would be great as this is the last bit that's tripping me up.
Thanks :)
|
Here's a suggestion for a general way to support **different** number of posts on the *home page* than on the *other paginated pages*. We should use the *main query* instead of *sub-queries*, if possible.
**Formula**
It seems to make sense to take the *offset* for paginated pages as:
```
offset_op = ( paged - 1 ) * pp_op + ( pp_fp - pp_op ) + offset_fp
= ( paged - 2 ) * pp_op + pp_fp + offset_fp
```
where `paged` (*pagination*), `pp_fp` (*posts per first page*), `pp_op` (*posts per other pages*) and offset\_fp (*offset for the first page*) are non-negative integers.
For `paged=1` the offset is `offset_fp`, else it's `offset_op` for other pages.
**Example #1:**
First we calculate the offset for few pages to better understand this:
```
For paged=1:
offset_fp = 0
For paged=2:
offset_op = (2-2)*10 + 13 + 0
= 13
For paged=3:
offset_op = (3-2)*10 + 13 + 0
= 10+13
= 23
...
```
Here's a list of post indices on each page:
```
0,1,2,3,4,5,6,7,8,9,10,11,12 (offset_fp=0, pp_fp=13, paged=1)
13,14,15,16,17,18,19,20,21,22 (offset_op=13, pp_op=10, paged=2)
23,24,25,26, 27,28,29,30,31,32 (offset_op=23, pp_op=10, paged=3)
...
```
We can see that the offset matches the indices.
**Example #2:**
Let's take `pp_fp = 3`, `pp_op = 5`, `offset_fp=4` and calculate the *offset\_op*:
```
For paged=1:
offset_fp = 4
For paged=2:
offset_op = (2-2)*5 + 3 + 4
= 7
For paged=3:
offset_op = (3-2)*5 + 3 + 4
= 5+3+4
= 12
...
```
and compare it to the indices:
```
4,5,6 (offset_fp=4, pp_fp=3, paged=1)
7,8,9,10,11 (offset_op=7, pp_op=5, paged=2)
12,13,14,15,16 (offset_op=12, pp_op=5, paged=3)
...
```
**Demo Plugin**
Here's a demo implementation:
```
/**
* Plugin Name: WPSE demo
*/
add_action( 'pre_get_posts', function( \WP_Query $query )
{
// Nothing to do if backend or not home page or not the main query
if ( is_admin() || ! $query->is_home() || ! $query->is_main_query() )
return;
// Get current pagination
$paged = get_query_var( 'paged', 1 );
// Modify sticky posts display
$query->set( 'ignore_sticky_posts', true );
// Modify post status
$query->set( 'post_status', 'publish' );
// Edit to your needs
$pp_fp = 13; // posts per first page
$pp_op = 10; // posts per other pages
$offset_fp = 0; // offset for the first page
// Offset for other pages than the first page
$offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;
// Modify offset
$query->set( 'offset', $query->is_paged() ? $offset_op : $offset_fp );
// Modify posts per page
$query->set( 'posts_per_page', $query->is_paged() ? $pp_op : $pp_fp );
} );
```
Hope you can adjust it to your needs!
|
237,436 |
<p>Can anyone tell me how to create a function out of the following code? It's for displaying page navigation links in a custom category template. As you can see, it's quite a large block of code and I would like to wrap it in a function so I can generate the links with just a single line of code in my template.</p>
<p>Here it is:</p>
<pre><code><?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo '&nbsp;<span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo '&nbsp;<a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
</code></pre>
<p>And here's the the custom category template with the above pagination code included:</p>
<pre><code><?php
/**
* Category Template: Custom
*/
get_header(); ?>
<div id="content" class="site-content container <?php echo codilight_lite_sidebar_position(); ?>">
<div class="content-inside">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
$catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$catnum = 2;
$offset = ($catnum * $catpage) - 2;
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;
$child_categories=get_categories(
array(
'parent' => $cat_id,
'orderby' => 'id',
'order' => 'DESC',
'hide_empty' => '0',
'number' => $catnum,
'offset' => $offset,
'paged' => $catpage
)
);
if (!empty($child_categories)) : $count = 0; ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="taxonomy-description">', '</div>' );
?>
</header><!-- .page-header -->
<?php
echo '<div class="block1 block1_grid">';
echo '<div class="row">';
foreach ( $child_categories as $child ){ $count++;
include( locate_template( 'template-parts/content-custom.php' ) );
if ( $count % 2 == 0 ) {
echo '</div>';
echo '<div class="row">';
}
}
echo '</div>';
echo '</div>';
?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
<?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo '&nbsp;<span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo '&nbsp;<a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
|
[
{
"answer_id": 237444,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably try without the <code>&& !$query->is_paged()</code> (you already have 2 conditions that should be enough, even just the first one should work actually) and if that doesn't work, try to output the <code>$paged</code> value and see how you can tweak the function better.</p>\n\n<p>Some debug ideas:</p>\n\n<pre><code>// get current page we are on. If not set we can assume we are on page 1.\n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n// are we on page one?\nif(1 == $paged) {\n //true\n}\n</code></pre>\n"
},
{
"answer_id": 237457,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Here's a suggestion for a general way to support <strong>different</strong> number of posts on the <em>home page</em> than on the <em>other paginated pages</em>. We should use the <em>main query</em> instead of <em>sub-queries</em>, if possible.</p>\n\n<p><strong>Formula</strong></p>\n\n<p>It seems to make sense to take the <em>offset</em> for paginated pages as:</p>\n\n<pre><code>offset_op = ( paged - 1 ) * pp_op + ( pp_fp - pp_op ) + offset_fp \n = ( paged - 2 ) * pp_op + pp_fp + offset_fp \n</code></pre>\n\n<p>where <code>paged</code> (<em>pagination</em>), <code>pp_fp</code> (<em>posts per first page</em>), <code>pp_op</code> (<em>posts per other pages</em>) and offset_fp (<em>offset for the first page</em>) are non-negative integers.</p>\n\n<p>For <code>paged=1</code> the offset is <code>offset_fp</code>, else it's <code>offset_op</code> for other pages.</p>\n\n<p><strong>Example #1:</strong></p>\n\n<p>First we calculate the offset for few pages to better understand this:</p>\n\n<pre><code>For paged=1:\n offset_fp = 0\n\nFor paged=2:\n offset_op = (2-2)*10 + 13 + 0\n = 13\n\nFor paged=3:\n offset_op = (3-2)*10 + 13 + 0\n = 10+13\n = 23\n...\n</code></pre>\n\n<p>Here's a list of post indices on each page:</p>\n\n<pre><code>0,1,2,3,4,5,6,7,8,9,10,11,12 (offset_fp=0, pp_fp=13, paged=1)\n13,14,15,16,17,18,19,20,21,22 (offset_op=13, pp_op=10, paged=2)\n23,24,25,26, 27,28,29,30,31,32 (offset_op=23, pp_op=10, paged=3)\n...\n</code></pre>\n\n<p>We can see that the offset matches the indices.</p>\n\n<p><strong>Example #2:</strong></p>\n\n<p>Let's take <code>pp_fp = 3</code>, <code>pp_op = 5</code>, <code>offset_fp=4</code> and calculate the <em>offset_op</em>:</p>\n\n<pre><code>For paged=1:\n offset_fp = 4\n\nFor paged=2:\n offset_op = (2-2)*5 + 3 + 4\n = 7\n\nFor paged=3:\n offset_op = (3-2)*5 + 3 + 4\n = 5+3+4\n = 12\n...\n</code></pre>\n\n<p>and compare it to the indices:</p>\n\n<pre><code>4,5,6 (offset_fp=4, pp_fp=3, paged=1)\n7,8,9,10,11 (offset_op=7, pp_op=5, paged=2)\n12,13,14,15,16 (offset_op=12, pp_op=5, paged=3)\n...\n</code></pre>\n\n<p><strong>Demo Plugin</strong></p>\n\n<p>Here's a demo implementation:</p>\n\n<pre><code>/**\n * Plugin Name: WPSE demo\n */\nadd_action( 'pre_get_posts', function( \\WP_Query $query ) \n{\n // Nothing to do if backend or not home page or not the main query\n if ( is_admin() || ! $query->is_home() || ! $query->is_main_query() )\n return;\n\n // Get current pagination\n $paged = get_query_var( 'paged', 1 );\n\n // Modify sticky posts display\n $query->set( 'ignore_sticky_posts', true );\n\n // Modify post status\n $query->set( 'post_status', 'publish' );\n\n // Edit to your needs\n $pp_fp = 13; // posts per first page\n $pp_op = 10; // posts per other pages\n $offset_fp = 0; // offset for the first page\n\n // Offset for other pages than the first page\n $offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;\n\n // Modify offset\n $query->set( 'offset', $query->is_paged() ? $offset_op : $offset_fp );\n\n // Modify posts per page\n $query->set( 'posts_per_page', $query->is_paged() ? $pp_op : $pp_fp ); \n} );\n</code></pre>\n\n<p>Hope you can adjust it to your needs!</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] |
Can anyone tell me how to create a function out of the following code? It's for displaying page navigation links in a custom category template. As you can see, it's quite a large block of code and I would like to wrap it in a function so I can generate the links with just a single line of code in my template.
Here it is:
```
<?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo ' <span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo ' <a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo ' <a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo ' <a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
```
And here's the the custom category template with the above pagination code included:
```
<?php
/**
* Category Template: Custom
*/
get_header(); ?>
<div id="content" class="site-content container <?php echo codilight_lite_sidebar_position(); ?>">
<div class="content-inside">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
$catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$catnum = 2;
$offset = ($catnum * $catpage) - 2;
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;
$child_categories=get_categories(
array(
'parent' => $cat_id,
'orderby' => 'id',
'order' => 'DESC',
'hide_empty' => '0',
'number' => $catnum,
'offset' => $offset,
'paged' => $catpage
)
);
if (!empty($child_categories)) : $count = 0; ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="taxonomy-description">', '</div>' );
?>
</header><!-- .page-header -->
<?php
echo '<div class="block1 block1_grid">';
echo '<div class="row">';
foreach ( $child_categories as $child ){ $count++;
include( locate_template( 'template-parts/content-custom.php' ) );
if ( $count % 2 == 0 ) {
echo '</div>';
echo '<div class="row">';
}
}
echo '</div>';
echo '</div>';
?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
<?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo ' <span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo ' <a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo ' <a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo ' <a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
|
Here's a suggestion for a general way to support **different** number of posts on the *home page* than on the *other paginated pages*. We should use the *main query* instead of *sub-queries*, if possible.
**Formula**
It seems to make sense to take the *offset* for paginated pages as:
```
offset_op = ( paged - 1 ) * pp_op + ( pp_fp - pp_op ) + offset_fp
= ( paged - 2 ) * pp_op + pp_fp + offset_fp
```
where `paged` (*pagination*), `pp_fp` (*posts per first page*), `pp_op` (*posts per other pages*) and offset\_fp (*offset for the first page*) are non-negative integers.
For `paged=1` the offset is `offset_fp`, else it's `offset_op` for other pages.
**Example #1:**
First we calculate the offset for few pages to better understand this:
```
For paged=1:
offset_fp = 0
For paged=2:
offset_op = (2-2)*10 + 13 + 0
= 13
For paged=3:
offset_op = (3-2)*10 + 13 + 0
= 10+13
= 23
...
```
Here's a list of post indices on each page:
```
0,1,2,3,4,5,6,7,8,9,10,11,12 (offset_fp=0, pp_fp=13, paged=1)
13,14,15,16,17,18,19,20,21,22 (offset_op=13, pp_op=10, paged=2)
23,24,25,26, 27,28,29,30,31,32 (offset_op=23, pp_op=10, paged=3)
...
```
We can see that the offset matches the indices.
**Example #2:**
Let's take `pp_fp = 3`, `pp_op = 5`, `offset_fp=4` and calculate the *offset\_op*:
```
For paged=1:
offset_fp = 4
For paged=2:
offset_op = (2-2)*5 + 3 + 4
= 7
For paged=3:
offset_op = (3-2)*5 + 3 + 4
= 5+3+4
= 12
...
```
and compare it to the indices:
```
4,5,6 (offset_fp=4, pp_fp=3, paged=1)
7,8,9,10,11 (offset_op=7, pp_op=5, paged=2)
12,13,14,15,16 (offset_op=12, pp_op=5, paged=3)
...
```
**Demo Plugin**
Here's a demo implementation:
```
/**
* Plugin Name: WPSE demo
*/
add_action( 'pre_get_posts', function( \WP_Query $query )
{
// Nothing to do if backend or not home page or not the main query
if ( is_admin() || ! $query->is_home() || ! $query->is_main_query() )
return;
// Get current pagination
$paged = get_query_var( 'paged', 1 );
// Modify sticky posts display
$query->set( 'ignore_sticky_posts', true );
// Modify post status
$query->set( 'post_status', 'publish' );
// Edit to your needs
$pp_fp = 13; // posts per first page
$pp_op = 10; // posts per other pages
$offset_fp = 0; // offset for the first page
// Offset for other pages than the first page
$offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;
// Modify offset
$query->set( 'offset', $query->is_paged() ? $offset_op : $offset_fp );
// Modify posts per page
$query->set( 'posts_per_page', $query->is_paged() ? $pp_op : $pp_fp );
} );
```
Hope you can adjust it to your needs!
|
237,438 |
<p>I'm trying to give custom color to each <strong>category item</strong>, But it gives only one style to all items.</p>
<p>I use this plugin for the colors:
'<a href="https://wordpress.org/plugins/category-color/" rel="nofollow">Category Color</a>'</p>
<p>My code as below,</p>
<pre><code><?php
$category = get_the_category();
$the_category_id = $category[0]->cat_ID;
if(function_exists('rl_color'))
{
$rl_category_color = rl_color($the_category_id);
}
$sep = '';
foreach ((get_the_category()) as $cat) {
echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background:' . $rl_category_color . '">' . $cat->cat_name . '</a>';
$sep = ', ';
}
?>
</code></pre>
|
[
{
"answer_id": 237439,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Why you don't use \"Term meta\"?</p>\n\n<p><a href=\"https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/\" rel=\"nofollow\">https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/</a></p>\n\n<p>It's new in wordpress, like post meta, but with taxonomies (categories are taxonomies)</p>\n"
},
{
"answer_id": 237450,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 2,
"selected": true,
"text": "<p>You are getting the color for one category (<em>term</em> is more appropriate though)</p>\n\n<pre><code>$the_category_id = $category[0]->cat_ID;\n</code></pre>\n\n<p>instead of checking the ID and Color for each term, that's why it's applying the same to all.</p>\n\n<p>Try this (untested):</p>\n\n<pre><code><?php\n\n $categories = get_the_category();\n $sep = '';\n foreach ($categories as $cat) {\n $the_category_id = $cat->term_id;\n if(function_exists('rl_color')){\n $rl_category_color = rl_color($the_category_id);\n } else {\n $rl_category_color = '#000'; // maybe a default color?\n }\n echo $sep . '<a href=\"' . get_category_link($cat->term_id) . '\" class=\"' . $cat->slug . '\" title=\"View all posts in '. esc_attr($cat->name) . '\" style=\"background-color:' . $rl_category_color . '\">' . $cat->cat_name . '</a>';\n $sep = ', ';\n }\n\n?>\n</code></pre>\n"
},
{
"answer_id": 237451,
"author": "Suraj Sakhare",
"author_id": 99171,
"author_profile": "https://wordpress.stackexchange.com/users/99171",
"pm_score": -1,
"selected": false,
"text": "<p>Please try below plugin's or code</p>\n\n<ol>\n<li><p><a href=\"https://wordpress.org/plugins/colorful-categories/\" rel=\"nofollow\">colorful-categories</a></p></li>\n<li><p><a href=\"https://wptavern.com/how-to-assign-icons-images-and-colors-to-categories-and-tags-in-the-wordpress-backend\" rel=\"nofollow\">how-to-assign-icons-images-and-colors-to-categories</a></p></li>\n<li><p><a href=\"http://ask.metafilter.com/251134/Different-background-color-for-each-WordPress-category\" rel=\"nofollow\">Different-background-color-for-each-WordPress-category</a></p></li>\n</ol>\n\n<p>May above links help you.</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101827/"
] |
I'm trying to give custom color to each **category item**, But it gives only one style to all items.
I use this plugin for the colors:
'[Category Color](https://wordpress.org/plugins/category-color/)'
My code as below,
```
<?php
$category = get_the_category();
$the_category_id = $category[0]->cat_ID;
if(function_exists('rl_color'))
{
$rl_category_color = rl_color($the_category_id);
}
$sep = '';
foreach ((get_the_category()) as $cat) {
echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background:' . $rl_category_color . '">' . $cat->cat_name . '</a>';
$sep = ', ';
}
?>
```
|
You are getting the color for one category (*term* is more appropriate though)
```
$the_category_id = $category[0]->cat_ID;
```
instead of checking the ID and Color for each term, that's why it's applying the same to all.
Try this (untested):
```
<?php
$categories = get_the_category();
$sep = '';
foreach ($categories as $cat) {
$the_category_id = $cat->term_id;
if(function_exists('rl_color')){
$rl_category_color = rl_color($the_category_id);
} else {
$rl_category_color = '#000'; // maybe a default color?
}
echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background-color:' . $rl_category_color . '">' . $cat->cat_name . '</a>';
$sep = ', ';
}
?>
```
|
237,442 |
<p>I need to get a post thumbnail to show up in an email, but this doesnt work with just <code>mailto</code>: as i've tried it.</p>
<pre><code><a href="mailto:?subject=Anbefalt innlegg - <?php the_title(); ?>&body=Hei, jeg fant et innlegg som jeg tror du vil like. <img src='<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>'>">
</code></pre>
<p>This only gives me the url, and the img tag doesnt work. Any ideas how to make this work? </p>
|
[
{
"answer_id": 237445,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>The <code>mailto</code> protocol is fairly limited and does not support html in the body. Notably iOS supports some tags, but you cannot rely on that. The point is that <code>mailto</code> parses information from the browser to the user's email program. The more tags are allowed, the higher the security risk becomes. So, if you insist on sending the mail using the remote mailing program, you're stuck.</p>\n\n<p>The alternative is using <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow\"><code>wp_mail</code></a>. Users could still click on a link, but in stead of to their mailing program, the will be brought to a (popup) page where can send their message. There are many plugins that do this. </p>\n"
},
{
"answer_id": 237446,
"author": "99teko",
"author_id": 69536,
"author_profile": "https://wordpress.stackexchange.com/users/69536",
"pm_score": 0,
"selected": false,
"text": "<p>This is just a workaround by encoding HTML Characters.</p>\n\n<pre><code><a href=\"mailto:?subject=Anbefalt innlegg - <?php the_title(); ?>&body=%3Cp%3EHei, jeg fant et innlegg som jeg tror du vil like. %3C%2Fp%3E%3Cimg%20src%3D%22<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>%22%20 %20%2F%3E\">Write Email!</a>\n</code></pre>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100922/"
] |
I need to get a post thumbnail to show up in an email, but this doesnt work with just `mailto`: as i've tried it.
```
<a href="mailto:?subject=Anbefalt innlegg - <?php the_title(); ?>&body=Hei, jeg fant et innlegg som jeg tror du vil like. <img src='<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>'>">
```
This only gives me the url, and the img tag doesnt work. Any ideas how to make this work?
|
The `mailto` protocol is fairly limited and does not support html in the body. Notably iOS supports some tags, but you cannot rely on that. The point is that `mailto` parses information from the browser to the user's email program. The more tags are allowed, the higher the security risk becomes. So, if you insist on sending the mail using the remote mailing program, you're stuck.
The alternative is using [`wp_mail`](https://developer.wordpress.org/reference/functions/wp_mail/). Users could still click on a link, but in stead of to their mailing program, the will be brought to a (popup) page where can send their message. There are many plugins that do this.
|
237,458 |
<p>I have a custom post type <code>Portfolio</code> and each portfolio is a questionnaire. If I email the link of a portfolio to a client via email. </p>
<p>How can I expire link after 10 minutes, So if client has came after 10 minutes to visit the link Then there should be message that link has expired Please try again.</p>
<p>How can I do that?</p>
|
[
{
"answer_id": 237472,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 0,
"selected": false,
"text": "<p>Here's one idea: Hook to the <code>template_redirect</code> action:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect</a></p>\n\n<p>At this point, you can examine the $post object to make sure it has the type of your CPT (<code>$post->post_type</code>), and get the timestamp (<code>$post->post_date</code>). If the current system time is > 10 minutes beyond the post time, then redirect the user to your desired URL.</p>\n\n<p>You'll probably want to do some sort of \"garbage collection\" on expired CPTs as well - delete those expired posts so your database doesn't fill up with unneeded content.</p>\n"
},
{
"answer_id": 237482,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 1,
"selected": false,
"text": "<p>You could add an <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\">custom query var</a> with the timestamp.</p>\n\n<pre><code>eg. example.com/portfolio?exp=12345678\n</code></pre>\n\n<p>Then, when a user lands on that url, you could check the current time against the timestamp.\nIf 10 mins have passed / or not, will allow you to output different things on the page.</p>\n\n<p>You could even store a certain timestamp, to know what client got which form/timestamp.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>As <strong>bynicolas</strong> has noted, technically the client could generate a current time timestamp and access the link again.</p>\n\n<p>So you might want to consider saving that timestamp as a transient, for 10 min.</p>\n\n<p>Now, when the client visits the url, you need to check if that transient with the timestamp <a href=\"https://stackoverflow.com/questions/12435364/check-if-transient-exists-without-retrieving-the-whole-data-in-wordpress\">has expired</a>.</p>\n\n<p>Just an idea.</p>\n"
},
{
"answer_id": 237493,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 4,
"selected": true,
"text": "<p>Ok I came up with this</p>\n\n<pre><code>add_action( 'wp_loaded', 'my_create_questionnaire_link');\nfunction my_create_questionnaire_link(){\n\n // this check is for demo, if you go to http://yoursite.demo/?create-my-link, you will get your unique url added to your content\n if( isset( $_GET['create-my-link'] ) ){\n\n // This filter is for demo purpose\n // You might want to create a button or a special page to generate your\n // unique URL\n add_filter( 'the_content', function( $content ){\n\n // This is the relevant part\n // This code will create a unique link containing valid period and a nonce\n\n $valid_period = 60 * 10; // 10 minutes\n $expiry = current_time( 'timestamp', 1 ) + $valid_period; // current_time( 'timestamp' ) for your blog local timestamp\n $url = site_url( '/path/to/your/portfolio/page' );\n $url = add_query_arg( 'valid', $expiry, $url ); // Adding the timestamp to the url with the \"valid\" arg\n $nonce_url = wp_nonce_url( $url, 'questionnaire_link_uid_' . $expiry, 'questionnaire' ); // Adding our nonce to the url with a unique id made from the expiry timestamp\n\n // End of relevant part\n // now here I return my nounce to the content of the post for demo purposed\n // You would use this code when a button is pressed or when a special page is visited\n\n $content .= $nonce_url;\n\n return $content;\n } );\n }\n\n}\n</code></pre>\n\n<p>This is where you would check for the validity of the unique URL</p>\n\n<pre><code>add_action( 'template_redirect', 'my_url_check' );\nfunction my_url_check(){\n\n if( isset( $_GET['questionnaire'] )){\n\n // if the nonce fails, redirect to homepage\n if( ! wp_verify_nonce( $_GET['questionnaire'], 'questionnaire_link_uid_' . $_GET['valid'] ) ){\n wp_safe_redirect( site_url() );\n exit;\n }\n\n // if timestamp is not valid, redirect to homepage\n if( $_GET['valid'] < current_time( 'timestamp', 1) ){\n wp_safe_redirect( site_url() );\n exit;\n }\n\n // Show your content as normal if all verification passes.\n }\n}\n</code></pre>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101087/"
] |
I have a custom post type `Portfolio` and each portfolio is a questionnaire. If I email the link of a portfolio to a client via email.
How can I expire link after 10 minutes, So if client has came after 10 minutes to visit the link Then there should be message that link has expired Please try again.
How can I do that?
|
Ok I came up with this
```
add_action( 'wp_loaded', 'my_create_questionnaire_link');
function my_create_questionnaire_link(){
// this check is for demo, if you go to http://yoursite.demo/?create-my-link, you will get your unique url added to your content
if( isset( $_GET['create-my-link'] ) ){
// This filter is for demo purpose
// You might want to create a button or a special page to generate your
// unique URL
add_filter( 'the_content', function( $content ){
// This is the relevant part
// This code will create a unique link containing valid period and a nonce
$valid_period = 60 * 10; // 10 minutes
$expiry = current_time( 'timestamp', 1 ) + $valid_period; // current_time( 'timestamp' ) for your blog local timestamp
$url = site_url( '/path/to/your/portfolio/page' );
$url = add_query_arg( 'valid', $expiry, $url ); // Adding the timestamp to the url with the "valid" arg
$nonce_url = wp_nonce_url( $url, 'questionnaire_link_uid_' . $expiry, 'questionnaire' ); // Adding our nonce to the url with a unique id made from the expiry timestamp
// End of relevant part
// now here I return my nounce to the content of the post for demo purposed
// You would use this code when a button is pressed or when a special page is visited
$content .= $nonce_url;
return $content;
} );
}
}
```
This is where you would check for the validity of the unique URL
```
add_action( 'template_redirect', 'my_url_check' );
function my_url_check(){
if( isset( $_GET['questionnaire'] )){
// if the nonce fails, redirect to homepage
if( ! wp_verify_nonce( $_GET['questionnaire'], 'questionnaire_link_uid_' . $_GET['valid'] ) ){
wp_safe_redirect( site_url() );
exit;
}
// if timestamp is not valid, redirect to homepage
if( $_GET['valid'] < current_time( 'timestamp', 1) ){
wp_safe_redirect( site_url() );
exit;
}
// Show your content as normal if all verification passes.
}
}
```
|
237,461 |
<p>Hello every one i am facing one issue in adding logo option in my theme panel of wordpress i am using this code</p>
<pre><code>function logo_display()
{
?>
<input type="file" name="logo" />
<?php echo get_option('logo'); ?>
<?php
}
function handle_logo_upload()
{
if(!empty($_FILES["demo-file"]["tmp_name"]))
{
$urls = wp_handle_upload($_FILES["logo"], array('test_form' => FALSE));
$temp = $urls["url"];
return $temp;
}
return $option;
}
function display_theme_panel_fields()
{
add_settings_section("section", "All Settings", null, "theme-options");
add_settings_field("logo", "Logo", "logo_display", "theme-options", "section");
register_setting("section", "logo", "handle_logo_upload");
}
add_action("admin_init", "display_theme_panel_fields");
</code></pre>
<p>The issue is its not saving logo and also not displaying it in admin as well. I have tried this 10 times with different ways but this code is not working. Please look in this code and help me in it please.</p>
|
[
{
"answer_id": 237714,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 2,
"selected": true,
"text": "<p>if you use wordpress customizer then try this code</p>\n\n<pre><code>public static function register ( $wp_customize ) {\n // Logo upload\n $wp_customize->add_section( 'bia_logo_section' , array(\n 'title' => __( 'Site Logo', 'bia' ),\n 'priority' => 30,\n 'description' => 'Upload a logo to replace the default site name and description in the header',\n ) );\n\n $wp_customize->add_setting( 'bia_logo', array(\n 'sanitize_callback' => 'esc_url_raw',\n ) );\n\n $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bia_logo', array(\n 'label' => __( 'Site Logo', 'bia' ),\n 'section' => 'bia_logo_section',\n 'settings' => 'bia_logo',\n ) ) );\n}\n</code></pre>\n\n<p>i think you can also try <a href=\"https://reduxframework.com/\" rel=\"nofollow\">redux framework</a> for admin panel option</p>\n"
},
{
"answer_id": 237715,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Since version 4.5 the <a href=\"https://codex.wordpress.org/Theme_Logo\" rel=\"nofollow\">Theme Logo</a> is a standard feature of WordPress. You can simply add the following code to your <code>functions.php</code>:</p>\n\n<pre><code>function wpse237461_theme_logo() {\n add_theme_support( 'custom-logo', array(\n 'height' => 100,\n 'width' => 400,\n 'flex-width' => true ) );\n }\nadd_action( 'after_setup_theme', 'wpse237461_theme_logo' );\n</code></pre>\n\n<p>Now you can change the logo in the theme customizer and you can add it to your theme with <code>the_custom_logo()</code>. No need to handle files and options yourself.</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98358/"
] |
Hello every one i am facing one issue in adding logo option in my theme panel of wordpress i am using this code
```
function logo_display()
{
?>
<input type="file" name="logo" />
<?php echo get_option('logo'); ?>
<?php
}
function handle_logo_upload()
{
if(!empty($_FILES["demo-file"]["tmp_name"]))
{
$urls = wp_handle_upload($_FILES["logo"], array('test_form' => FALSE));
$temp = $urls["url"];
return $temp;
}
return $option;
}
function display_theme_panel_fields()
{
add_settings_section("section", "All Settings", null, "theme-options");
add_settings_field("logo", "Logo", "logo_display", "theme-options", "section");
register_setting("section", "logo", "handle_logo_upload");
}
add_action("admin_init", "display_theme_panel_fields");
```
The issue is its not saving logo and also not displaying it in admin as well. I have tried this 10 times with different ways but this code is not working. Please look in this code and help me in it please.
|
if you use wordpress customizer then try this code
```
public static function register ( $wp_customize ) {
// Logo upload
$wp_customize->add_section( 'bia_logo_section' , array(
'title' => __( 'Site Logo', 'bia' ),
'priority' => 30,
'description' => 'Upload a logo to replace the default site name and description in the header',
) );
$wp_customize->add_setting( 'bia_logo', array(
'sanitize_callback' => 'esc_url_raw',
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bia_logo', array(
'label' => __( 'Site Logo', 'bia' ),
'section' => 'bia_logo_section',
'settings' => 'bia_logo',
) ) );
}
```
i think you can also try [redux framework](https://reduxframework.com/) for admin panel option
|
237,488 |
<p>I'm making my first wordpress site. When I publish a post I see it in my home page but despite I add an image I can't see it above the post title in my home page. <a href="https://i.stack.imgur.com/EnztZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EnztZ.jpg" alt="enter image description here"></a></p>
<p>Thank you in advice.</p>
|
[
{
"answer_id": 237714,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 2,
"selected": true,
"text": "<p>if you use wordpress customizer then try this code</p>\n\n<pre><code>public static function register ( $wp_customize ) {\n // Logo upload\n $wp_customize->add_section( 'bia_logo_section' , array(\n 'title' => __( 'Site Logo', 'bia' ),\n 'priority' => 30,\n 'description' => 'Upload a logo to replace the default site name and description in the header',\n ) );\n\n $wp_customize->add_setting( 'bia_logo', array(\n 'sanitize_callback' => 'esc_url_raw',\n ) );\n\n $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bia_logo', array(\n 'label' => __( 'Site Logo', 'bia' ),\n 'section' => 'bia_logo_section',\n 'settings' => 'bia_logo',\n ) ) );\n}\n</code></pre>\n\n<p>i think you can also try <a href=\"https://reduxframework.com/\" rel=\"nofollow\">redux framework</a> for admin panel option</p>\n"
},
{
"answer_id": 237715,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Since version 4.5 the <a href=\"https://codex.wordpress.org/Theme_Logo\" rel=\"nofollow\">Theme Logo</a> is a standard feature of WordPress. You can simply add the following code to your <code>functions.php</code>:</p>\n\n<pre><code>function wpse237461_theme_logo() {\n add_theme_support( 'custom-logo', array(\n 'height' => 100,\n 'width' => 400,\n 'flex-width' => true ) );\n }\nadd_action( 'after_setup_theme', 'wpse237461_theme_logo' );\n</code></pre>\n\n<p>Now you can change the logo in the theme customizer and you can add it to your theme with <code>the_custom_logo()</code>. No need to handle files and options yourself.</p>\n"
}
] |
2016/08/29
|
[
"https://wordpress.stackexchange.com/questions/237488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101850/"
] |
I'm making my first wordpress site. When I publish a post I see it in my home page but despite I add an image I can't see it above the post title in my home page. [](https://i.stack.imgur.com/EnztZ.jpg)
Thank you in advice.
|
if you use wordpress customizer then try this code
```
public static function register ( $wp_customize ) {
// Logo upload
$wp_customize->add_section( 'bia_logo_section' , array(
'title' => __( 'Site Logo', 'bia' ),
'priority' => 30,
'description' => 'Upload a logo to replace the default site name and description in the header',
) );
$wp_customize->add_setting( 'bia_logo', array(
'sanitize_callback' => 'esc_url_raw',
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bia_logo', array(
'label' => __( 'Site Logo', 'bia' ),
'section' => 'bia_logo_section',
'settings' => 'bia_logo',
) ) );
}
```
i think you can also try [redux framework](https://reduxframework.com/) for admin panel option
|
237,558 |
<h2>Introduction</h2>
<p>When uploading a file (<code>stackexchange.jpg</code>) to the media library in a WordPress site, there are two relevant links.</p>
<ol>
<li><p><strong>Direct link to file</strong><br><code>http://example.com/wp-content/uploads/stackexchange.jpg</code></p></li>
<li><p><strong>Attachment page</strong><br><code>http://example.com/stackexchange/</code></p></li>
</ol>
<p>My question deals with the second one: <em>attachment page</em>.</p>
<h2>What I Want to Do</h2>
<p>I would like to add the file extension in the attachment page permalink. For example, instead of</p>
<p><code>http://example.com/stackexchange/</code></p>
<p>I would like</p>
<p><code>http://example.com/stackexchange-jpg/</code></p>
<h3>Why This Would be Useful</h3>
<p>This would be very useful for a couple of reasons. For one, it won't be <a href="https://wordpress.stackexchange.com/questions/217848/media-items-hogging-pretty-permalinks">hogging permalinks</a> in case I want to use it for a post or a page, etc. For another, I can then upload another file called <code>stackexchange.png</code>. Then, I would have:<br>
<code>http://example.com/stackexchange-jpg/</code><br>
and<br>
<code>http://example.com/stackexchange-png/</code></p>
<p>And again, I can still use <code>http://example.com/stackexchange/</code> for an actual page.</p>
<p>I do realize that I <em>can</em> go through and edit every single file's slug manually, which in turn would indeed change the attachment page permalink, but I think it almost goes without saying that I wouldn't need to actually make a thread if I was looking to do that.</p>
<h2>Question</h2>
<p>Is there a function I can write to make it so that whenever a file is uploaded, it reflects the changes I'm looking for? Is this even possible? If so, how do I do it? If you know how to edit the default permalink, but you don't know how to add the file extension part, I can most likely still work with that information.</p>
<p>I'm thinking this is probably not possible without tampering with core files (which would be a deal breaker), but hopefully it is.</p>
<p>Thanks for reading and for any help.</p>
|
[
{
"answer_id": 238205,
"author": "KenB",
"author_id": 27576,
"author_profile": "https://wordpress.stackexchange.com/users/27576",
"pm_score": 2,
"selected": true,
"text": "<p>Great question! I've been thinking about this myself and your question prompted me to dig into it.</p>\n\n<p>There is a filter <code>wp_insert_attachment_data</code> than can be used to fix the slug name for uploaded files. It is called for attachments shortly before the attachment is inserted into the database in <code>post.php</code>.</p>\n\n<p>The following sample will append the mime type to the slug name, for example <code>image-jpg</code> will be added to a jpeg image title.</p>\n\n<pre><code> /**\n * Filter attachment post data before it is added to the database\n * - Add mime type to post_name to reduce slug collisions\n *\n * @param array $data Array of santized attachment post data\n * @param array $postarr Array of unsanitized attachment post data\n * @return $data, array of post data\n */\n function filter_attachment_slug($data, $postarr)\n {\n /**\n * Only work on attachment types\n */\n if ( ! array_key_exists( 'post_type', $data ) || 'attachment' != $data['post_type'] )\n return $data;\n\n /**\n * Add mime type to the post title to build post-name\n */\n $post_title = array_key_exists( 'post_title', $data ) ? $data['post_title'] : $postarr['post_title'];\n $post_mime_type = array_key_exists( 'post_mime_type', $data ) ? $data['post_mime_type'] : $postarr['post_mime_type'];\n $post_mime_type = str_replace( '/', '-', $post_mime_type );\n $post_name = sanitize_title( $post_title . '-' . $post_mime_type );\n\n /**\n * Generate unique slug for post name\n */\n $post_ID = array_key_exists( 'ID', $data ) ? $data['ID'] : $postarr['ID'];\n $post_status = array_key_exists( 'post_status', $data ) ? $data['post_status'] : $postarr['post_status'];\n $post_type = array_key_exists( 'post_type', $data ) ? $data['post_type'] : $postarr['post_type'];\n $post_parent = array_key_exists( 'post_parent', $data ) ? $data['post_parent'] : $postarr['post_parent'];\n\n $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );\n $data['post_name'] = $post_name;\n\n return $data;\n }\n\n /**\n * Adjust slug for uploaded files to include mime type\n */\n add_filter( 'wp_insert_attachment_data', 'filter_attachment_slug', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 238291,
"author": "Leon Williams",
"author_id": 88601,
"author_profile": "https://wordpress.stackexchange.com/users/88601",
"pm_score": 0,
"selected": false,
"text": "<p>This is an expansion upon <a href=\"https://wordpress.stackexchange.com/a/238205/88601\">KenB's answer</a>; I've just included minor edits.</p>\n\n<h2>The Difference</h2>\n\n<p>Let's consider the file <code>stackexchange.png</code> being uploaded to the media library.</p>\n\n<h3>KenB's original solution</h3>\n\n<p><em>Result:</em> <code>http://example.com/stackexchange-image-png/</code><br>\nThis taps into the database for posts and pulls from the <code>post_mime_type</code> column, which in this case results in <code>image/png</code>.</p>\n\n<h3>+ These edits</h3>\n\n<p><em>Result:</em> <code>http://example.com/stackexchange-png/</code><br>\nInstead of pulling from <code>post_mime_type</code>, we can pull from <code>guid</code> (which in this case, results in <code>http://example.com/wp-content/uploads/stackexchange.png</code>), then we can strip off everything but the file extension and work with that.</p>\n\n<h2>Code</h2>\n\n<p>So now that I've explained the difference between that solution and this one, here's how to do it. I've included and done a little editing to <a href=\"https://stackoverflow.com/a/1361752/5675729\">DisgruntledGoat and redanimalwar's answer to a question on StackOverflow</a>.</p>\n\n<p>Everything I disabled in KenB's solution, I left in the code, but just commented it out, so you can see what I actually did.</p>\n\n<pre><code>/**\n * This finds the last '.' in a URI and returns the string after that.\n * For example, in the case of 'example.com/photo.jpg', 'jpg' is returned. \n *\n * @author DisgruntledGoat\n * @author redanimalwar\n *\n * @link https://stackoverflow.com/a/1361752/5675729\n */\nfunction get_file_extension($uri) {\n $position = strrpos($uri, '.');\n $extension = $position === false ? $uri : substr($uri, $position + 1);\n return $extension;\n}\n\n/**\n * Filter attachment post data before it is added to the database\n * - Add mime type to post_name to reduce slug collisions\n *\n * @author KenB\n *\n * @link https://wordpress.stackexchange.com/a/238205/88601 Original solution\n * @link https://wordpress.stackexchange.com/a/238291/88601 This variation\n *\n * @param array $data Array of santized attachment post data\n * @param array $postarr Array of unsanitized attachment post data\n *\n * @return $data, array of post data\n */\nfunction filter_attachment_slug($data, $postarr) {\n /**\n * Only work on attachment types\n */\n if ( ! array_key_exists( 'post_type', $data ) || 'attachment' != $data['post_type'] )\n return $data;\n\n /**\n * Add mime type to the post title to build post-name\n */\n $post_title = array_key_exists( 'post_title', $data ) ? $data['post_title'] : $postarr['post_title'];\n\n /**\n * This was in KenB's original solution, but was removed by Leon Williams,\n * as this version does not deal with the MIME type.\n */\n //$post_mime_type = array_key_exists( 'post_mime_type', $data ) ? $data['post_mime_type'] : $postarr['post_mime_type'];\n\n /**\n * This this takes the MIME type, for example, 'image/jpg', into 'image-jpg'.\n * This was in KenB's original solution, but was removed by Leon Williams,\n * as this version does not deal with the MIME type.\n */\n //$post_mime_type = str_replace( '/', '-', $post_mime_type );\n\n /**\n * Access the 'guid' column from the database (which retrieves the link to the file),\n * then send it to get_file_extension().\n *\n * @author Leon Williams\n */\n $post_file_extention = get_file_extension($postarr['guid']);\n\n // Instead of tacking on the MIME type, tack on the file extension that we just obtained.\n $post_name = sanitize_title( $post_title . '-' /*. $post_mime_type*/ . $post_file_extention);\n\n /**\n * Generate unique slug for post name\n */\n $post_ID = array_key_exists( 'ID', $data ) ? $data['ID'] : $postarr['ID'];\n $post_status = array_key_exists( 'post_status', $data ) ? $data['post_status'] : $postarr['post_status'];\n $post_type = array_key_exists( 'post_type', $data ) ? $data['post_type'] : $postarr['post_type'];\n $post_parent = array_key_exists( 'post_parent', $data ) ? $data['post_parent'] : $postarr['post_parent'];\n\n $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );\n $data['post_name'] = $post_name;\n\n return $data;\n}\n\n/**\n * Adjust slug for uploaded files to include file extension\n */\nadd_filter( 'wp_insert_attachment_data', 'filter_attachment_slug', 10, 2 );\n</code></pre>\n\n<h3>Alternative (using <code>post_mime_type</code> instead of <code>guid</code>)</h3>\n\n<p>You could also just take the <code>png</code> off of <code>image/png</code> (by having <code>get_file_extension()</code> look for <code>/</code> instead of <code>.</code>), which works just as well. It's just, with this (the way I have it), you can also use the <code>get_file_extension()</code> for other links as well.</p>\n\n<h3>Word of Caution</h3>\n\n<p>With a little bit of testing, I discovered that in both the original solution and this version, <strong>this filter also fires anytime you push the \"Update\" button while editing an attachment</strong>.</p>\n\n<p>For example, let's say you're editing an attachment by the name of <code>example.png</code> and it has the custom slug of <code>example-file-slug</code> (let's suppose you gave it that custom slug a long time ago). Today you're editing the description and when you're finished with the description and hit \"Update\", this filter will fire and will <em>automatically</em> change the slug from <code>example-file-slug</code> to <code>example-png</code> in addition to updating the description. If you try to go back and change the slug to anything else, again, the filter will fire when you hit \"Update\" and will override your attempt to change the slug.</p>\n\n<p>This poses no problem for me personally, but it may be something to consider for others.</p>\n\n<p><strong>Workarounds</strong><br>\nIf you want to change the slug name, you would have to disable this filter (say, by commenting it out) then save your changes to the attachment, then enable the filter again. Alternatively, you could edit the database directly.</p>\n\n<p>I'm sure there's a way to code a solution, but I don't currently have one.</p>\n\n<hr>\n\n<p>Thanks to these fine people:</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/users/27576/kenb\">KenB</a></li>\n<li><a href=\"https://stackoverflow.com/users/37947/disgruntledgoat\">DisgruntledGoat</a></li>\n<li><a href=\"https://stackoverflow.com/users/2847723/redanimalwar\">redanimalwar</a></li>\n</ul>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88601/"
] |
Introduction
------------
When uploading a file (`stackexchange.jpg`) to the media library in a WordPress site, there are two relevant links.
1. **Direct link to file**
`http://example.com/wp-content/uploads/stackexchange.jpg`
2. **Attachment page**
`http://example.com/stackexchange/`
My question deals with the second one: *attachment page*.
What I Want to Do
-----------------
I would like to add the file extension in the attachment page permalink. For example, instead of
`http://example.com/stackexchange/`
I would like
`http://example.com/stackexchange-jpg/`
### Why This Would be Useful
This would be very useful for a couple of reasons. For one, it won't be [hogging permalinks](https://wordpress.stackexchange.com/questions/217848/media-items-hogging-pretty-permalinks) in case I want to use it for a post or a page, etc. For another, I can then upload another file called `stackexchange.png`. Then, I would have:
`http://example.com/stackexchange-jpg/`
and
`http://example.com/stackexchange-png/`
And again, I can still use `http://example.com/stackexchange/` for an actual page.
I do realize that I *can* go through and edit every single file's slug manually, which in turn would indeed change the attachment page permalink, but I think it almost goes without saying that I wouldn't need to actually make a thread if I was looking to do that.
Question
--------
Is there a function I can write to make it so that whenever a file is uploaded, it reflects the changes I'm looking for? Is this even possible? If so, how do I do it? If you know how to edit the default permalink, but you don't know how to add the file extension part, I can most likely still work with that information.
I'm thinking this is probably not possible without tampering with core files (which would be a deal breaker), but hopefully it is.
Thanks for reading and for any help.
|
Great question! I've been thinking about this myself and your question prompted me to dig into it.
There is a filter `wp_insert_attachment_data` than can be used to fix the slug name for uploaded files. It is called for attachments shortly before the attachment is inserted into the database in `post.php`.
The following sample will append the mime type to the slug name, for example `image-jpg` will be added to a jpeg image title.
```
/**
* Filter attachment post data before it is added to the database
* - Add mime type to post_name to reduce slug collisions
*
* @param array $data Array of santized attachment post data
* @param array $postarr Array of unsanitized attachment post data
* @return $data, array of post data
*/
function filter_attachment_slug($data, $postarr)
{
/**
* Only work on attachment types
*/
if ( ! array_key_exists( 'post_type', $data ) || 'attachment' != $data['post_type'] )
return $data;
/**
* Add mime type to the post title to build post-name
*/
$post_title = array_key_exists( 'post_title', $data ) ? $data['post_title'] : $postarr['post_title'];
$post_mime_type = array_key_exists( 'post_mime_type', $data ) ? $data['post_mime_type'] : $postarr['post_mime_type'];
$post_mime_type = str_replace( '/', '-', $post_mime_type );
$post_name = sanitize_title( $post_title . '-' . $post_mime_type );
/**
* Generate unique slug for post name
*/
$post_ID = array_key_exists( 'ID', $data ) ? $data['ID'] : $postarr['ID'];
$post_status = array_key_exists( 'post_status', $data ) ? $data['post_status'] : $postarr['post_status'];
$post_type = array_key_exists( 'post_type', $data ) ? $data['post_type'] : $postarr['post_type'];
$post_parent = array_key_exists( 'post_parent', $data ) ? $data['post_parent'] : $postarr['post_parent'];
$post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
$data['post_name'] = $post_name;
return $data;
}
/**
* Adjust slug for uploaded files to include mime type
*/
add_filter( 'wp_insert_attachment_data', 'filter_attachment_slug', 10, 2 );
```
|
237,573 |
<p>I'm trying to add a CSS class to every image in a custom post type. </p>
<p>I've found <a href="https://wordpress.stackexchange.com/questions/108831/add-css-class-to-every-image">this answer</a>, to add a class to every image in general: </p>
<pre><code>function add_image_class($class){
$class .= ' additional-class';
return $class;
}
add_filter('get_image_tag_class','add_image_class');
</code></pre>
<p>How would I build on this, so that it only applies to a custom post type? </p>
|
[
{
"answer_id": 237575,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>The function <a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow\"><code>get_post_type</code></a> returns the type of the current post, so supposing you want to add this class only to a post type called 'wpse' you should include a conditional like this:</p>\n\n<pre><code>function wpse237573_add_image_class($class){\n if ('wpse' == get_post_type()) $class .= ' additional-class';\n return $class;\n}\nadd_filter('get_image_tag_class','wpse237573_add_image_class');\n</code></pre>\n"
},
{
"answer_id": 237584,
"author": "Dvaeer",
"author_id": 92868,
"author_profile": "https://wordpress.stackexchange.com/users/92868",
"pm_score": 3,
"selected": false,
"text": "<p>Combining the answer here by @cjcj with the code in <a href=\"https://wordpress.stackexchange.com/a/22166/92868\">this answer</a>, the code that works for me outside the loop, in functions.php is:</p>\n\n<pre><code>// Add ability to check for custom post type outside the loop. \nfunction is_post_type($type){\n global $wp_query;\n if($type == get_post_type($wp_query->post->ID)) return true;\n return false;\n}\n\n// Add class to every image in 'wpse' custom post type.\nfunction add_image_class($class){\n if ('wpse' == is_post_type()){\n $class .= ' additional-class';\n }\n return $class;\n}\nadd_filter('get_image_tag_class','add_image_class');\n</code></pre>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92868/"
] |
I'm trying to add a CSS class to every image in a custom post type.
I've found [this answer](https://wordpress.stackexchange.com/questions/108831/add-css-class-to-every-image), to add a class to every image in general:
```
function add_image_class($class){
$class .= ' additional-class';
return $class;
}
add_filter('get_image_tag_class','add_image_class');
```
How would I build on this, so that it only applies to a custom post type?
|
Combining the answer here by @cjcj with the code in [this answer](https://wordpress.stackexchange.com/a/22166/92868), the code that works for me outside the loop, in functions.php is:
```
// Add ability to check for custom post type outside the loop.
function is_post_type($type){
global $wp_query;
if($type == get_post_type($wp_query->post->ID)) return true;
return false;
}
// Add class to every image in 'wpse' custom post type.
function add_image_class($class){
if ('wpse' == is_post_type()){
$class .= ' additional-class';
}
return $class;
}
add_filter('get_image_tag_class','add_image_class');
```
|
237,599 |
<p>Depending on the product category, I have different data to display on category page. I'm getting my category <code>ID</code> this way:</p>
<pre><code><?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ($product_cat_id == "6") {
echo "aaa";
}
elseif ($product_cat_id == "7") {
echo "bbb";
}
?>
</code></pre>
<p>But I need to display different data when product is in two categories and it does not work.</p>
<pre><code>echo $product_cat_id;
</code></pre>
<p>It recognizes only one category. How do I make it recognize two and make <code>IF</code> statement for product which is in category 6 <code>AND</code> 7?</p>
|
[
{
"answer_id": 237603,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>Your <code>$product_cat_id</code> is an <code>array()</code> of all of your categories and it looks like you are only running the <code>if</code> statement outside of the array to check the category's ID. Instead, you should run it inside the <code>foreach</code> loop. This is untested, but it should look something like this:</p>\n\n<pre><code><?php\nglobal $post;\n$terms = get_the_terms( $post->ID, 'product_cat' );\nforeach ( $terms as $term ) {\n $product_cat_id = $term->term_id;\n break;\n}\n\nforeach ( $product_cat_id as $key => $value ) {\n if ( $value == \"6\" ) {\n echo \"aaa\";\n }\n if ( $value == \"7\" ) {\n echo \"bbb\";\n }\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 237605,
"author": "Vivek Tamrakar",
"author_id": 96956,
"author_profile": "https://wordpress.stackexchange.com/users/96956",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Try This Code</p>\n</blockquote>\n\n<pre><code> <?php global $post;\n $terms = get_the_terms( $post->ID, 'product_cat' );\n foreach ($terms as $term) {\n $product_cat_id = $term->term_id;\n break;\n }\n\n if ($product_cat_id == \"6\" && $product_cat_id == \"7\" ) {\n echo \"aaabbb\";\n }\n else if ($product_cat_id == \"6\" ) {\n echo \"aaa\";\n }\n else if ($product_cat_id == \"7\") {\n echo \"bbb\";\n }\n ?>\n</code></pre>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101907/"
] |
Depending on the product category, I have different data to display on category page. I'm getting my category `ID` this way:
```
<?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ($product_cat_id == "6") {
echo "aaa";
}
elseif ($product_cat_id == "7") {
echo "bbb";
}
?>
```
But I need to display different data when product is in two categories and it does not work.
```
echo $product_cat_id;
```
It recognizes only one category. How do I make it recognize two and make `IF` statement for product which is in category 6 `AND` 7?
|
>
> Try This Code
>
>
>
```
<?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ($product_cat_id == "6" && $product_cat_id == "7" ) {
echo "aaabbb";
}
else if ($product_cat_id == "6" ) {
echo "aaa";
}
else if ($product_cat_id == "7") {
echo "bbb";
}
?>
```
|
237,601 |
<p>I am currently making an e-shop on woocommerce. On my homepage there is products slider with the add-to-cart button under each product. If I click on the button, product is added to cart successfully, but without any message.</p>
<p>While surfing the Internet, I've found out, that messages can be added on shop page, product category page and product tag page (<a href="https://www.skyverge.com/blog/display-woocommerce-cart-notices/" rel="nofollow">in this article</a>). According to that article, I should use filter/hook to catch the add-to-cart event and display message on main page.</p>
<p>I have tried this:</p>
<pre><code> add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
global $woocommerce;
// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
$return_to = get_permalink(woocommerce_get_page_id('shop'));
$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
else :
$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
endif;
return $message;
}
</code></pre>
<p>but nothing happens. Can anyone help me? </p>
|
[
{
"answer_id": 237602,
"author": "Faisal Ramzan",
"author_id": 85487,
"author_profile": "https://wordpress.stackexchange.com/users/85487",
"pm_score": 2,
"selected": false,
"text": "<p>This article will help you in this issue\n<a href=\"https://docs.woocommerce.com/document/woocommerce-cart-notices/\" rel=\"nofollow\">https://docs.woocommerce.com/document/woocommerce-cart-notices/</a></p>\n\n<p>Or you can put below code in functions.php to get success message </p>\n\n<pre><code>add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );\nfunction custom_add_to_cart_message() {\n global $woocommerce;\n // Output success messages\n if (get_option('woocommerce_cart_redirect_after_add')=='yes') :\n $return_to = get_permalink(woocommerce_get_page_id('shop'));\n\n $message = sprintf('<a href=\"%s\" class=\"button\">%s</a> %s', $return_to, __('Continue Shopping &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );\n\n else :\n $message = sprintf('<a href=\"%s\" class=\"button\">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );\n\n endif;\n return $message;\n}\nfunction your_woo_ajax_solution( $translation, $text, $domain ) {\nif ( $domain == 'woocommerce' ) { // your domain name\n if ( $text == 'View Cart' ) { // current text that shows\n $translation = 'Product successfully added to your cart.'; // The text that you would like to show\n }\n}\nreturn $translation;\n}\nadd_filter( 'gettext', 'your_woo_ajax_solution', 10, 3 ); \n</code></pre>\n"
},
{
"answer_id": 237608,
"author": "Артур Пипченко",
"author_id": 80324,
"author_profile": "https://wordpress.stackexchange.com/users/80324",
"pm_score": 3,
"selected": true,
"text": "<p>Solution was as simple as it should be: I've just added this piece of code into my main page .php file:</p>\n\n<pre><code>do_action( 'woocommerce_before_single_product' );\n</code></pre>\n"
},
{
"answer_id": 285505,
"author": "user131247",
"author_id": 131247,
"author_profile": "https://wordpress.stackexchange.com/users/131247",
"pm_score": 0,
"selected": false,
"text": "<p>Copy this code and paste it to your theme <code>page.php</code> or <code>singlepage.php</code></p>\n\n<pre><code>do_action('woocommerce_before_single_product');\n</code></pre>\n"
},
{
"answer_id": 375590,
"author": "user3438298",
"author_id": 98062,
"author_profile": "https://wordpress.stackexchange.com/users/98062",
"pm_score": 2,
"selected": false,
"text": "<p>woocommcerce has this as a separate function</p>\n<pre><code>wc_print_notices(); \n</code></pre>\n<p>so just use that on your template pages. You don't need to echo or print it, just use it as is.</p>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80324/"
] |
I am currently making an e-shop on woocommerce. On my homepage there is products slider with the add-to-cart button under each product. If I click on the button, product is added to cart successfully, but without any message.
While surfing the Internet, I've found out, that messages can be added on shop page, product category page and product tag page ([in this article](https://www.skyverge.com/blog/display-woocommerce-cart-notices/)). According to that article, I should use filter/hook to catch the add-to-cart event and display message on main page.
I have tried this:
```
add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
global $woocommerce;
// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
$return_to = get_permalink(woocommerce_get_page_id('shop'));
$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
else :
$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
endif;
return $message;
}
```
but nothing happens. Can anyone help me?
|
Solution was as simple as it should be: I've just added this piece of code into my main page .php file:
```
do_action( 'woocommerce_before_single_product' );
```
|
237,610 |
<p>Here is my query args :</p>
<pre><code> $query_args = array(
'post_type' => 'rented_properties',
'post_status' => 'publish',
'order' => 'DESC',
// 'fields' => 'SUM(amount_to_paid)',
);
$my_querys = null;
$my_querys = new WP_Query($query_args);
</code></pre>
<p>My meta key is <code>amount_to_paid</code>, and I want to get the sum all the meta_values of this query condition. Please suggest your answer with <code>query_args</code>.</p>
<p>My Scenario : I have 1000 posts and each with meta_key amount_to_paid and it has some value. Now I filter 20 posts and want to get sum of meta_value of amount_to_paid . Did you got me now?</p>
|
[
{
"answer_id": 237711,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p><code>WP_Query</code> gets posts from the database, but it's not a generic SQL query class, it should really be called <code>WP_Post_Query</code>, as <code>WP_Query</code> implies it can do any SQL.</p>\n\n<p>As a result, you need to do several things:</p>\n\n<ol>\n<li>Grab the posts you need</li>\n<li>Get their meta values for <code>amount_to_paid</code> using <code>get_post_meta</code></li>\n<li>Add those values up using the basic PHP maths <code>+ - / * = += -=</code></li>\n</ol>\n\n<p>So:</p>\n\n<pre><code>$sum = 0;\n$query = new WP_Query($query_args);\nif ( $query->have_posts() ) {\n while( $query->have_posts() ) {\n $query->the_post();\n // do the processing for each post\n $sum = $sum + get_post_meta( ... );\n }\n}\necho esc_html( $sum );\n</code></pre>\n"
},
{
"answer_id": 257001,
"author": "Joefrey",
"author_id": 113667,
"author_profile": "https://wordpress.stackexchange.com/users/113667",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this code.</p>\n<pre><code>global $wpdb;\n$meta_key = 'link_click_counter';\n$all_downloads = $wpdb->get_var($wpdb->prepare("\n SELECT sum(meta_value) \n FROM $wpdb->postmeta \n WHERE meta_key = %s", $meta_key));\n\necho $all_downloads;\n</code></pre>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99113/"
] |
Here is my query args :
```
$query_args = array(
'post_type' => 'rented_properties',
'post_status' => 'publish',
'order' => 'DESC',
// 'fields' => 'SUM(amount_to_paid)',
);
$my_querys = null;
$my_querys = new WP_Query($query_args);
```
My meta key is `amount_to_paid`, and I want to get the sum all the meta\_values of this query condition. Please suggest your answer with `query_args`.
My Scenario : I have 1000 posts and each with meta\_key amount\_to\_paid and it has some value. Now I filter 20 posts and want to get sum of meta\_value of amount\_to\_paid . Did you got me now?
|
`WP_Query` gets posts from the database, but it's not a generic SQL query class, it should really be called `WP_Post_Query`, as `WP_Query` implies it can do any SQL.
As a result, you need to do several things:
1. Grab the posts you need
2. Get their meta values for `amount_to_paid` using `get_post_meta`
3. Add those values up using the basic PHP maths `+ - / * = += -=`
So:
```
$sum = 0;
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// do the processing for each post
$sum = $sum + get_post_meta( ... );
}
}
echo esc_html( $sum );
```
|
237,613 |
<p>I'm using WP version 4.4.4. I have some posts where it has a continue reading button and link to the actual excerpt. My problem is the excerpt also has a continue reading button. Here is my code at the end of <code>functions.php</code>.</p>
<pre><code>function new_excerpt_more($more) {
global $post;
return '... <a class="moretag" href="'. get_permalink($post->ID). '"> continue reading &raquo;</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
</code></pre>
<p>Fairly new to WordPress. I searched this site but nothing worked for me. Thanks.</p>
|
[
{
"answer_id": 237711,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p><code>WP_Query</code> gets posts from the database, but it's not a generic SQL query class, it should really be called <code>WP_Post_Query</code>, as <code>WP_Query</code> implies it can do any SQL.</p>\n\n<p>As a result, you need to do several things:</p>\n\n<ol>\n<li>Grab the posts you need</li>\n<li>Get their meta values for <code>amount_to_paid</code> using <code>get_post_meta</code></li>\n<li>Add those values up using the basic PHP maths <code>+ - / * = += -=</code></li>\n</ol>\n\n<p>So:</p>\n\n<pre><code>$sum = 0;\n$query = new WP_Query($query_args);\nif ( $query->have_posts() ) {\n while( $query->have_posts() ) {\n $query->the_post();\n // do the processing for each post\n $sum = $sum + get_post_meta( ... );\n }\n}\necho esc_html( $sum );\n</code></pre>\n"
},
{
"answer_id": 257001,
"author": "Joefrey",
"author_id": 113667,
"author_profile": "https://wordpress.stackexchange.com/users/113667",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this code.</p>\n<pre><code>global $wpdb;\n$meta_key = 'link_click_counter';\n$all_downloads = $wpdb->get_var($wpdb->prepare("\n SELECT sum(meta_value) \n FROM $wpdb->postmeta \n WHERE meta_key = %s", $meta_key));\n\necho $all_downloads;\n</code></pre>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91536/"
] |
I'm using WP version 4.4.4. I have some posts where it has a continue reading button and link to the actual excerpt. My problem is the excerpt also has a continue reading button. Here is my code at the end of `functions.php`.
```
function new_excerpt_more($more) {
global $post;
return '... <a class="moretag" href="'. get_permalink($post->ID). '"> continue reading »</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
```
Fairly new to WordPress. I searched this site but nothing worked for me. Thanks.
|
`WP_Query` gets posts from the database, but it's not a generic SQL query class, it should really be called `WP_Post_Query`, as `WP_Query` implies it can do any SQL.
As a result, you need to do several things:
1. Grab the posts you need
2. Get their meta values for `amount_to_paid` using `get_post_meta`
3. Add those values up using the basic PHP maths `+ - / * = += -=`
So:
```
$sum = 0;
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// do the processing for each post
$sum = $sum + get_post_meta( ... );
}
}
echo esc_html( $sum );
```
|
237,620 |
<p>I am developing a wordpress theme. In <code>single.php</code> page I want to loop similar to this,</p>
<pre><code><?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-heading-info">
<!--Post heading info like title, category goes here -->
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php //sidebar widget goes here ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-content">
<!--Post content and footer goes here-->
</div>
<?php endif; ?>
<?php endwhile; ?>
</code></pre>
<p>So, in the code above I am trying to loop all the basic information like title, category and time. The In the middle I want to put the sidebar and then in the second loop the content and the post's footer information. </p>
<p>I need this because of various options in single.php page layout. Basically I want keep all header info on top above all the widgets and post contents. </p>
<p>My question is, <strong>Is this the code above acceptable as a good practice?</strong></p>
<p>Please help me in this and your few minutes from your life for my question would be really appreciated and helpful. </p>
|
[
{
"answer_id": 237621,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.</p>\n<p>This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.</p>\n<p>However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's <code>functions.php</code> file which runs your custom codes on top of WordPress.</p>\n<h3>Update: per <a href=\"https://wordpress.stackexchange.com/questions/237619#comment354057_237621\">Youssef's comment below</a></h3>\n<blockquote>\n<p>...what code should I add to <code>functions.php</code> to get users to verify their email?</p>\n</blockquote>\n<p>It wouldn't be a few lines of code to add to your <code>functions.php</code>, I can tell you that much.</p>\n<p>This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the <a href=\"http://s.tk/wp\" rel=\"nofollow noreferrer\">WPSE</a> community is here for.</p>\n<blockquote>\n<p><em>We don't want our members to ask people to create a solution without attempting it themselves.</em></p>\n</blockquote>\n<p>To start, I'd look into other <a href=\"https://wordpress.org/plugins/\" rel=\"nofollow noreferrer\">plugins</a> or <a href=\"https://wordpress.stackexchange.com/questions/tagged/functions\">functions</a> that are available tailor the codes for yourself. For example, this plugin: <a href=\"https://wordpress.org/plugins/user-activation-email/\" rel=\"nofollow noreferrer\">User Activation Email</a> is worth looking into. Just download the <code>.zip</code> file and play around with the source codes.</p>\n<p>Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, <em>editing WordPress' core is not recommended</em>.</p>\n"
},
{
"answer_id": 237626,
"author": "ASaxe",
"author_id": 101919,
"author_profile": "https://wordpress.stackexchange.com/users/101919",
"pm_score": -1,
"selected": false,
"text": "<p>You don't have to change Wordpress's core, you can add this within your theme files. Functions.php would be one way, or just include/require a class in your funtions.php to keep things neat.</p>\n\n<pre><code> require get_template_directory() . '/verify_user.php';\n</code></pre>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89234/"
] |
I am developing a wordpress theme. In `single.php` page I want to loop similar to this,
```
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-heading-info">
<!--Post heading info like title, category goes here -->
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php //sidebar widget goes here ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-content">
<!--Post content and footer goes here-->
</div>
<?php endif; ?>
<?php endwhile; ?>
```
So, in the code above I am trying to loop all the basic information like title, category and time. The In the middle I want to put the sidebar and then in the second loop the content and the post's footer information.
I need this because of various options in single.php page layout. Basically I want keep all header info on top above all the widgets and post contents.
My question is, **Is this the code above acceptable as a good practice?**
Please help me in this and your few minutes from your life for my question would be really appreciated and helpful.
|
As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.
This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.
However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's `functions.php` file which runs your custom codes on top of WordPress.
### Update: per [Youssef's comment below](https://wordpress.stackexchange.com/questions/237619#comment354057_237621)
>
> ...what code should I add to `functions.php` to get users to verify their email?
>
>
>
It wouldn't be a few lines of code to add to your `functions.php`, I can tell you that much.
This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the [WPSE](http://s.tk/wp) community is here for.
>
> *We don't want our members to ask people to create a solution without attempting it themselves.*
>
>
>
To start, I'd look into other [plugins](https://wordpress.org/plugins/) or [functions](https://wordpress.stackexchange.com/questions/tagged/functions) that are available tailor the codes for yourself. For example, this plugin: [User Activation Email](https://wordpress.org/plugins/user-activation-email/) is worth looking into. Just download the `.zip` file and play around with the source codes.
Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, *editing WordPress' core is not recommended*.
|
237,629 |
<p>I can think of a number of ways to go about doing this. I'm looking for the most efficient way. Menu looks like this:</p>
<p>catArchive1 [num_new_posts] catArchive2 [num_new_posts] catArchive3 [num_new_posts]</p>
<p>^^[num_new_posts] being the number of new posts</p>
<p>Assuming we have a cookie value set for the users last visit <code>$_COOKIE['lastvisit']</code>.</p>
<p>I could do something like the follow for EACH menu/category</p>
<pre><code>$args = array(
'category' => $cat_id,
'posts_per_page' => -1,
'date_query' => array( 'after' => $_COOKIE['lastvisit'] ),
);
$new_posts = get_posts($args);
$num_posts = count($num_posts); // Number of new posts
</code></pre>
<p>Of course, this is another query for each menu item. Any ideas how to combine this into one and still know how many new posts in each category? </p>
|
[
{
"answer_id": 237621,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.</p>\n<p>This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.</p>\n<p>However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's <code>functions.php</code> file which runs your custom codes on top of WordPress.</p>\n<h3>Update: per <a href=\"https://wordpress.stackexchange.com/questions/237619#comment354057_237621\">Youssef's comment below</a></h3>\n<blockquote>\n<p>...what code should I add to <code>functions.php</code> to get users to verify their email?</p>\n</blockquote>\n<p>It wouldn't be a few lines of code to add to your <code>functions.php</code>, I can tell you that much.</p>\n<p>This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the <a href=\"http://s.tk/wp\" rel=\"nofollow noreferrer\">WPSE</a> community is here for.</p>\n<blockquote>\n<p><em>We don't want our members to ask people to create a solution without attempting it themselves.</em></p>\n</blockquote>\n<p>To start, I'd look into other <a href=\"https://wordpress.org/plugins/\" rel=\"nofollow noreferrer\">plugins</a> or <a href=\"https://wordpress.stackexchange.com/questions/tagged/functions\">functions</a> that are available tailor the codes for yourself. For example, this plugin: <a href=\"https://wordpress.org/plugins/user-activation-email/\" rel=\"nofollow noreferrer\">User Activation Email</a> is worth looking into. Just download the <code>.zip</code> file and play around with the source codes.</p>\n<p>Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, <em>editing WordPress' core is not recommended</em>.</p>\n"
},
{
"answer_id": 237626,
"author": "ASaxe",
"author_id": 101919,
"author_profile": "https://wordpress.stackexchange.com/users/101919",
"pm_score": -1,
"selected": false,
"text": "<p>You don't have to change Wordpress's core, you can add this within your theme files. Functions.php would be one way, or just include/require a class in your funtions.php to keep things neat.</p>\n\n<pre><code> require get_template_directory() . '/verify_user.php';\n</code></pre>\n"
}
] |
2016/08/30
|
[
"https://wordpress.stackexchange.com/questions/237629",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11857/"
] |
I can think of a number of ways to go about doing this. I'm looking for the most efficient way. Menu looks like this:
catArchive1 [num\_new\_posts] catArchive2 [num\_new\_posts] catArchive3 [num\_new\_posts]
^^[num\_new\_posts] being the number of new posts
Assuming we have a cookie value set for the users last visit `$_COOKIE['lastvisit']`.
I could do something like the follow for EACH menu/category
```
$args = array(
'category' => $cat_id,
'posts_per_page' => -1,
'date_query' => array( 'after' => $_COOKIE['lastvisit'] ),
);
$new_posts = get_posts($args);
$num_posts = count($num_posts); // Number of new posts
```
Of course, this is another query for each menu item. Any ideas how to combine this into one and still know how many new posts in each category?
|
As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.
This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.
However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's `functions.php` file which runs your custom codes on top of WordPress.
### Update: per [Youssef's comment below](https://wordpress.stackexchange.com/questions/237619#comment354057_237621)
>
> ...what code should I add to `functions.php` to get users to verify their email?
>
>
>
It wouldn't be a few lines of code to add to your `functions.php`, I can tell you that much.
This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the [WPSE](http://s.tk/wp) community is here for.
>
> *We don't want our members to ask people to create a solution without attempting it themselves.*
>
>
>
To start, I'd look into other [plugins](https://wordpress.org/plugins/) or [functions](https://wordpress.stackexchange.com/questions/tagged/functions) that are available tailor the codes for yourself. For example, this plugin: [User Activation Email](https://wordpress.org/plugins/user-activation-email/) is worth looking into. Just download the `.zip` file and play around with the source codes.
Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, *editing WordPress' core is not recommended*.
|
237,671 |
<p>I have website in WordPress and I updated my <code>.htaccess</code> file with following rule. </p>
<pre><code><IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
</IfModule>
</code></pre>
<p>Now, when I checked my website performance with <a href="https://developers.google.com/speed/pagespeed/insights/" rel="nofollow">Google insight</a>. it still giving me error for <strong>leverage browser caching</strong></p>
<p>I have used this code </p>
<pre><code> add_filter( 'script_loader_src', 'elated_child__remove_ver' );
add_filter( 'style_loader_src', 'elated_child__remove_ver' );
function elated_child__remove_ver( $src ) { // Remove query strings from static resources
if ( strpos( $src, '?f=' ) || strpos( $src, '&f=' ) ) {
$src = remove_query_arg( 'f', $src );
}
return $src;
}
</code></pre>
<p>Any idea?</p>
|
[
{
"answer_id": 237621,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.</p>\n<p>This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.</p>\n<p>However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's <code>functions.php</code> file which runs your custom codes on top of WordPress.</p>\n<h3>Update: per <a href=\"https://wordpress.stackexchange.com/questions/237619#comment354057_237621\">Youssef's comment below</a></h3>\n<blockquote>\n<p>...what code should I add to <code>functions.php</code> to get users to verify their email?</p>\n</blockquote>\n<p>It wouldn't be a few lines of code to add to your <code>functions.php</code>, I can tell you that much.</p>\n<p>This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the <a href=\"http://s.tk/wp\" rel=\"nofollow noreferrer\">WPSE</a> community is here for.</p>\n<blockquote>\n<p><em>We don't want our members to ask people to create a solution without attempting it themselves.</em></p>\n</blockquote>\n<p>To start, I'd look into other <a href=\"https://wordpress.org/plugins/\" rel=\"nofollow noreferrer\">plugins</a> or <a href=\"https://wordpress.stackexchange.com/questions/tagged/functions\">functions</a> that are available tailor the codes for yourself. For example, this plugin: <a href=\"https://wordpress.org/plugins/user-activation-email/\" rel=\"nofollow noreferrer\">User Activation Email</a> is worth looking into. Just download the <code>.zip</code> file and play around with the source codes.</p>\n<p>Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, <em>editing WordPress' core is not recommended</em>.</p>\n"
},
{
"answer_id": 237626,
"author": "ASaxe",
"author_id": 101919,
"author_profile": "https://wordpress.stackexchange.com/users/101919",
"pm_score": -1,
"selected": false,
"text": "<p>You don't have to change Wordpress's core, you can add this within your theme files. Functions.php would be one way, or just include/require a class in your funtions.php to keep things neat.</p>\n\n<pre><code> require get_template_directory() . '/verify_user.php';\n</code></pre>\n"
}
] |
2016/08/31
|
[
"https://wordpress.stackexchange.com/questions/237671",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101535/"
] |
I have website in WordPress and I updated my `.htaccess` file with following rule.
```
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
</IfModule>
```
Now, when I checked my website performance with [Google insight](https://developers.google.com/speed/pagespeed/insights/). it still giving me error for **leverage browser caching**
I have used this code
```
add_filter( 'script_loader_src', 'elated_child__remove_ver' );
add_filter( 'style_loader_src', 'elated_child__remove_ver' );
function elated_child__remove_ver( $src ) { // Remove query strings from static resources
if ( strpos( $src, '?f=' ) || strpos( $src, '&f=' ) ) {
$src = remove_query_arg( 'f', $src );
}
return $src;
}
```
Any idea?
|
As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.
This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.
However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's `functions.php` file which runs your custom codes on top of WordPress.
### Update: per [Youssef's comment below](https://wordpress.stackexchange.com/questions/237619#comment354057_237621)
>
> ...what code should I add to `functions.php` to get users to verify their email?
>
>
>
It wouldn't be a few lines of code to add to your `functions.php`, I can tell you that much.
This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the [WPSE](http://s.tk/wp) community is here for.
>
> *We don't want our members to ask people to create a solution without attempting it themselves.*
>
>
>
To start, I'd look into other [plugins](https://wordpress.org/plugins/) or [functions](https://wordpress.stackexchange.com/questions/tagged/functions) that are available tailor the codes for yourself. For example, this plugin: [User Activation Email](https://wordpress.org/plugins/user-activation-email/) is worth looking into. Just download the `.zip` file and play around with the source codes.
Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, *editing WordPress' core is not recommended*.
|
237,741 |
<p>I need to protect some hooks which only can be hooked by functions/callbacks within my theme/plugin.</p>
<p>For example:</p>
<pre><code>if ( is_protected_hook('hook_name') ) {
throw new \Exception('You cannot hook to a protected hook.');
} else {
do_action('hook_name');
}
</code></pre>
<p>Is there a way to define the <code>is_protected_hook()</code> function?</p>
<p>Any suggestions will be greatly appreciated! </p>
|
[
{
"answer_id": 237748,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>As noted in my answer to <a href=\"https://wordpress.stackexchange.com/questions/237717/how-to-check-if-a-hook-is-hooked-or-not\">your related question</a> there is a datastructre <code>$wp_filter</code> that stores all information on hooks and filters. You may want to try a <code>var_dump</code> on it just to see what it looks like. There is no built in variable 'protected'.</p>\n\n<p>This leaves you with two options to keep the administration of the hooks you want to protect: build it into <code>$wp_filter</code> yourself or keep it separate. I recommend the latter.</p>\n\n<p>Maintain an array <code>$protected_hooks</code>. I don't know the conditions under which you want hooks to be protected, but you will have to set this array the moment you add an action to a specific hook.</p>\n\n<p>Now, in your tempate file you will need a double condition: is a hook active and is it protected. That would go like this:</p>\n\n<pre><code>if ((has_filter('hook_name') && in_array('hook_name',$protected_hooks)) ...\n</code></pre>\n"
},
{
"answer_id": 237752,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>This can not be solved by code, as wordpress, themes and plugins occupy the same data and program space, therefor there is no way to segregate anything in a way which will be bullet prof.</p>\n\n<p>The question is why do you want to do such a thing at all? if it is because it is unstable, then you can just explicitly document next to the use of the hook that it is for internal usage only. </p>\n"
}
] |
2016/08/31
|
[
"https://wordpress.stackexchange.com/questions/237741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92212/"
] |
I need to protect some hooks which only can be hooked by functions/callbacks within my theme/plugin.
For example:
```
if ( is_protected_hook('hook_name') ) {
throw new \Exception('You cannot hook to a protected hook.');
} else {
do_action('hook_name');
}
```
Is there a way to define the `is_protected_hook()` function?
Any suggestions will be greatly appreciated!
|
As noted in my answer to [your related question](https://wordpress.stackexchange.com/questions/237717/how-to-check-if-a-hook-is-hooked-or-not) there is a datastructre `$wp_filter` that stores all information on hooks and filters. You may want to try a `var_dump` on it just to see what it looks like. There is no built in variable 'protected'.
This leaves you with two options to keep the administration of the hooks you want to protect: build it into `$wp_filter` yourself or keep it separate. I recommend the latter.
Maintain an array `$protected_hooks`. I don't know the conditions under which you want hooks to be protected, but you will have to set this array the moment you add an action to a specific hook.
Now, in your tempate file you will need a double condition: is a hook active and is it protected. That would go like this:
```
if ((has_filter('hook_name') && in_array('hook_name',$protected_hooks)) ...
```
|
237,757 |
<p>I have the following code (below) in my theme. I am using redux framework for my theme options. My codes in a part looking like this. And I am really not sure about the security issue of this chunk of codes. Please any expert help me indicating any security problem in here. Your few minutes from your life would be really appreciated and helpful. </p>
<pre><code><?php if (isset($cosomic_options['blog_tag']) && $cosomic_options['blog_tag'] ) { ?>
<div class="entry-meta-tag">
<?php the_tags('', ' ', '<br />'); ?>
</div>
<?php } ?>
<div class="entry-content">
<p>
<?php $content = get_the_content();
echo wp_trim_words( $content , '35' );
?>
</p>
</div>
<?php $continue_reading = ''; ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) { ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) {
if ( isset($cosomic_options['blog_continue']) && $cosomic_options['blog_continue'] ) {
$continue_reading = $cosomic_options['blog_continue'];
}else {
$continue_reading = 'Continue Reading';
} ?>
<div class="a-btn">
<a href="<?php the_permalink(); ?>"><?php echo $continue_reading; ?> <i class="fa fa-hand-o-right"></i></a>
</div>
<?php } ?>
<?php } ?>
</code></pre>
|
[
{
"answer_id": 237759,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>Security issues arise when you write code that open up possibilities for outsiders to access your database or otherwise compromise your installation.</p>\n\n<p>The above code just reads options and content from the database and translates this into static html that will be send to the browser of the page's visitor. There's no code (like a <code>form</code>) that will allow the visitor to send information back to your server. So there are no security concerns.</p>\n\n<p>(Of course there still could be vulnerabilities in other parts of your code.)</p>\n"
},
{
"answer_id": 237850,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 1,
"selected": false,
"text": "<p>Redux framework has some issues but you can overcome it.</p>\n\n<p><a href=\"https://wptavern.com/xss-vulnerability-what-to-do-if-you-buy-or-sell-items-on-themeforest-and-codecanyon\" rel=\"nofollow\">check this link</a></p>\n\n<p>and check <a href=\"https://docs.reduxframework.com/core/the-basics/validation/\" rel=\"nofollow\">this link</a> when you need to data valid and the code you submitted the codes is fine, you have not worry about it. </p>\n"
}
] |
2016/08/31
|
[
"https://wordpress.stackexchange.com/questions/237757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89234/"
] |
I have the following code (below) in my theme. I am using redux framework for my theme options. My codes in a part looking like this. And I am really not sure about the security issue of this chunk of codes. Please any expert help me indicating any security problem in here. Your few minutes from your life would be really appreciated and helpful.
```
<?php if (isset($cosomic_options['blog_tag']) && $cosomic_options['blog_tag'] ) { ?>
<div class="entry-meta-tag">
<?php the_tags('', ' ', '<br />'); ?>
</div>
<?php } ?>
<div class="entry-content">
<p>
<?php $content = get_the_content();
echo wp_trim_words( $content , '35' );
?>
</p>
</div>
<?php $continue_reading = ''; ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) { ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) {
if ( isset($cosomic_options['blog_continue']) && $cosomic_options['blog_continue'] ) {
$continue_reading = $cosomic_options['blog_continue'];
}else {
$continue_reading = 'Continue Reading';
} ?>
<div class="a-btn">
<a href="<?php the_permalink(); ?>"><?php echo $continue_reading; ?> <i class="fa fa-hand-o-right"></i></a>
</div>
<?php } ?>
<?php } ?>
```
|
Security issues arise when you write code that open up possibilities for outsiders to access your database or otherwise compromise your installation.
The above code just reads options and content from the database and translates this into static html that will be send to the browser of the page's visitor. There's no code (like a `form`) that will allow the visitor to send information back to your server. So there are no security concerns.
(Of course there still could be vulnerabilities in other parts of your code.)
|
237,762 |
<p>I would like to disable all attachment pages completely. I Googled it, but there's just information on <a href="https://stackoverflow.com/questions/28885293/how-disable-image-attachment-pages-in-wordpress">how to redirect to parent post or homepage</a>. That's not what I would call an elegant solution. Why introduce unnecessary permalinks that redirect to the homepage? Couldn't it be disabled completely? </p>
|
[
{
"answer_id": 271089,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 4,
"selected": false,
"text": "<p>You can filter default rewrite rules and remove those for attachments:</p>\n\n<pre><code>function cleanup_default_rewrite_rules( $rules ) {\n foreach ( $rules as $regex => $query ) {\n if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) {\n unset( $rules[ $regex ] );\n }\n }\n\n return $rules;\n}\nadd_filter( 'rewrite_rules_array', 'cleanup_default_rewrite_rules' );\n</code></pre>\n\n<p>Don't forget to re-save your permalinks once. WordPress will generate new rules without anything related to attachments.</p>\n\n<p>Now, the attachment page URL gives 404. You can also add that redirect to prevent the 404 page, it's useless in this case. But I'm not sure how to catch the redirect - is_attachment() will not work if the rewrite rules are removed.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>WordPress will still offer the attachment page pretty URLs in media library and media insertion dialog. You can filter this as well:</p>\n\n<pre><code>function cleanup_attachment_link( $link ) {\n return;\n}\nadd_filter( 'attachment_link', 'cleanup_attachment_link' );\n</code></pre>\n\n<p>In this case, even when you insert your attachment into post ans select \"Link to attachment page\", the image will be inserted <strong>without the link</strong>.</p>\n"
},
{
"answer_id": 377735,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 3,
"selected": false,
"text": "<p>For those who might not use plugins or prefer light-weighted method. This might be of help.</p>\n<p>This method redirect attachment to the exact file instead of the attachment page and it is the method that some plugins are using.</p>\n<p>To test, by putting the following code in <code>functions.php</code> of the theme.</p>\n<pre><code>add_action( 'template_redirect', 'test_attachment_redirect', 10 );\nfunction test_attachment_redirect() {\n if( is_attachment() ) {\n $url = wp_get_attachment_url( get_queried_object_id() );\n wp_redirect( $url, 301 );\n }\n return;\n}\n</code></pre>\n<p>Reference:\n<a href=\"https://developer.wordpress.org/reference/functions/is_attachment/\" rel=\"noreferrer\">is_attachment</a>\n<a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"noreferrer\">wp_redirect</a></p>\n"
},
{
"answer_id": 388465,
"author": "fairport",
"author_id": 202135,
"author_profile": "https://wordpress.stackexchange.com/users/202135",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to disable media pages completely, you should use a 404 response code instead of redirection. This can be done with the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse237762_set_404() {\n if (is_attachment()) {\n global $wp_query;\n $wp_query->set_404();\n status_header(404);\n }\n}\n\n// This will show 404 on the attachment page\nadd_filter('template_redirect', 'wpse237762_set_404');\n\n// This will show 404 instead of redirecting to attachment page when dealing with a trailing slash\nadd_filter('redirect_canonical', 'wpse237762_set_404', 0);\n</code></pre>\n<p>To keep links to attachment pages working and redirect them straight to the file, you can use the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse237762_change_attachment_link($url, $id) {\n $attachment_url = wp_get_attachment_url($id);\n if ($attachment_url) {\n return $attachment_url;\n }\n return $url;\n}\n\nadd_filter('attachment_link', 'wpse237762_change_attachment_link', 10, 2);\n</code></pre>\n<p>To prevent attachment pages from reserving slugs from normal pages, you can use this code to set all new attachment slugs to random ones (UUIDv4 in this case)</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse237762_unique_slug($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) {\n if ($post_type === 'attachment') {\n return str_replace('-', '', wp_generate_uuid4());\n }\n return $slug;\n}\n\nadd_filter('wp_unique_post_slug', 'wpse237762_unique_slug', 10, 6);\n</code></pre>\n<p>This will prevent an image named <code>products.jpeg</code> reserving the URL <code>https://example.com/products</code>. That would result in a page named <strong>Products</strong> being given the URL <code>https://example.com/products-2</code> which obviously wouldn't be that great.</p>\n<p>I have put this code together in the <a href=\"https://wordpress.org/plugins/disable-media-pages/\" rel=\"noreferrer\">Disable Attachment Pages plugin</a>, which also includes a tool to scramble existing attachment slugs so they won't cause any problems in the future.</p>\n"
}
] |
2016/08/31
|
[
"https://wordpress.stackexchange.com/questions/237762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88787/"
] |
I would like to disable all attachment pages completely. I Googled it, but there's just information on [how to redirect to parent post or homepage](https://stackoverflow.com/questions/28885293/how-disable-image-attachment-pages-in-wordpress). That's not what I would call an elegant solution. Why introduce unnecessary permalinks that redirect to the homepage? Couldn't it be disabled completely?
|
You can filter default rewrite rules and remove those for attachments:
```
function cleanup_default_rewrite_rules( $rules ) {
foreach ( $rules as $regex => $query ) {
if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) {
unset( $rules[ $regex ] );
}
}
return $rules;
}
add_filter( 'rewrite_rules_array', 'cleanup_default_rewrite_rules' );
```
Don't forget to re-save your permalinks once. WordPress will generate new rules without anything related to attachments.
Now, the attachment page URL gives 404. You can also add that redirect to prevent the 404 page, it's useless in this case. But I'm not sure how to catch the redirect - is\_attachment() will not work if the rewrite rules are removed.
**Update:**
WordPress will still offer the attachment page pretty URLs in media library and media insertion dialog. You can filter this as well:
```
function cleanup_attachment_link( $link ) {
return;
}
add_filter( 'attachment_link', 'cleanup_attachment_link' );
```
In this case, even when you insert your attachment into post ans select "Link to attachment page", the image will be inserted **without the link**.
|
237,816 |
<p>I have build a custom post_type with "Resellers" in order to enter my personal reseller items. The "Resellers" post have taxonomies like "Countries" and "Departmens".</p>
<p>I am running into a problem:</p>
<p>The first time that the page is displayed, nothing gets fetched from my custom post type taxonomies. If I click on one of my links, then the data get successfully updated. The issue is Country without "Département" assigned category (Allemagne for example) = The results are displayed but the "Département" drop-list should be hidden.</p>
<p>Can anyone tell me where have I done a mistake ?</p>
<p><strong>function.php</strong></p>
<pre><code>if( !function_exists( 'reseller_department' ) ){
function reseller_department(){
$location = get_terms( 'reseller-department', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_department']) ){
if($_GET['reseller_department'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_department']) || $_GET['reseller_department'] == '-1'){
echo '<option value="-1" selected>'.__( 'all departments', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
if( !function_exists( 'reseller_country' ) ){
function reseller_country(){
$location = get_terms( 'reseller-country', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_country']) ){
if($_GET['reseller_country'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_country']) || $_GET['reseller_country'] == '-1'){
echo '<option value="-1" selected>'.__( '...', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
</code></pre>
<p><strong>archieve.js</strong></p>
<pre><code>jQuery(document).ready(function($) {
$("#archive-wrapper").height($("#archive-pot").height());
$("#archive-browser select").change(function() {
$("#archive-pot")
.empty()
.html("<div style='text-align: center; padding: 30px;'>Loading...</div>");
var d = $("#reseller_department").val();
var e = $("#reseller_country").val();
$.ajax({
url: "/work/",
dataType: "html",
type: "POST",
data: {
"digwp_d" : d,
"digwp_e" : e
},
success: function(data) {
$("#archive-pot").html(data);
$("#archive-wrapper").animate({
height: $("#archives-table tr").length * 50
});
}
});
});
// get all data option value reseller country
var values = [];
var sel = document.getElementById('reseller_country');
for (var i=0, n=sel.options.length;i<n;i++) {
if (sel.options[i].value)
values.push(sel.options[i].value);
}
var jupe = '"' + values.join('","') + '"';
var dataOptionCountry = values;
dataOptionCountry.pop();
// console.log(dataOptionCountry);
$("#reseller_country").change(function () {
$("#reseller_department").prop("disabled", !(dataOptionCountry.indexOf(this.value) !== -1));
});
});
</code></pre>
<p><strong>template-reseller-getter.php</strong></p>
<pre><code><?php
$rd = $_POST['digwp_d'];
$rc = $_POST['digwp_e'];
$querystring = "cat=$rc&cat=$rd&posts_per_page=-1";
query_posts($querystring);
?>
<?php if (($rc == '-1') && ($rd == '-1')) { ?>
<table id="archives-table" class="table">
<tr>
<td style='text-align: center; font-size: 15px; padding: 5px;'><?php _e("Please choose from above.", "nalys-plugin") ?></td>
</tr>
</table>
<?php } else { ?>
<div id="archives-table">
<?php
$custom_args_empty_one = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
$custom_args = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
if ( $rc != '-1' && $rd == '-1' || $rc == '-1' && $rd != '-1' ) {
$custom_query = new WP_Query( $custom_args_empty_one );
} elseif ( $rc != '-1' && $rd != '-1' ){
$custom_query = new WP_Query( $custom_args );
}
if ($custom_query->have_posts()) :
$row = 0;
while ($custom_query->have_posts()) :
$custom_query->the_post();
$count = $custom_query->post_count;
if($count==1){
// Displaying data
echo '<div class="archives-table-reseller col-md-offset-4 col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}else{
// Displaying data
echo '<div class="archives-table-reseller col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}
endwhile; else:
echo "Nothing found.";
endif;
?>
</div>
<?php } ?>
</code></pre>
|
[
{
"answer_id": 271089,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 4,
"selected": false,
"text": "<p>You can filter default rewrite rules and remove those for attachments:</p>\n\n<pre><code>function cleanup_default_rewrite_rules( $rules ) {\n foreach ( $rules as $regex => $query ) {\n if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) {\n unset( $rules[ $regex ] );\n }\n }\n\n return $rules;\n}\nadd_filter( 'rewrite_rules_array', 'cleanup_default_rewrite_rules' );\n</code></pre>\n\n<p>Don't forget to re-save your permalinks once. WordPress will generate new rules without anything related to attachments.</p>\n\n<p>Now, the attachment page URL gives 404. You can also add that redirect to prevent the 404 page, it's useless in this case. But I'm not sure how to catch the redirect - is_attachment() will not work if the rewrite rules are removed.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>WordPress will still offer the attachment page pretty URLs in media library and media insertion dialog. You can filter this as well:</p>\n\n<pre><code>function cleanup_attachment_link( $link ) {\n return;\n}\nadd_filter( 'attachment_link', 'cleanup_attachment_link' );\n</code></pre>\n\n<p>In this case, even when you insert your attachment into post ans select \"Link to attachment page\", the image will be inserted <strong>without the link</strong>.</p>\n"
},
{
"answer_id": 377735,
"author": "西門 正 Code Guy",
"author_id": 35701,
"author_profile": "https://wordpress.stackexchange.com/users/35701",
"pm_score": 3,
"selected": false,
"text": "<p>For those who might not use plugins or prefer light-weighted method. This might be of help.</p>\n<p>This method redirect attachment to the exact file instead of the attachment page and it is the method that some plugins are using.</p>\n<p>To test, by putting the following code in <code>functions.php</code> of the theme.</p>\n<pre><code>add_action( 'template_redirect', 'test_attachment_redirect', 10 );\nfunction test_attachment_redirect() {\n if( is_attachment() ) {\n $url = wp_get_attachment_url( get_queried_object_id() );\n wp_redirect( $url, 301 );\n }\n return;\n}\n</code></pre>\n<p>Reference:\n<a href=\"https://developer.wordpress.org/reference/functions/is_attachment/\" rel=\"noreferrer\">is_attachment</a>\n<a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"noreferrer\">wp_redirect</a></p>\n"
},
{
"answer_id": 388465,
"author": "fairport",
"author_id": 202135,
"author_profile": "https://wordpress.stackexchange.com/users/202135",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to disable media pages completely, you should use a 404 response code instead of redirection. This can be done with the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse237762_set_404() {\n if (is_attachment()) {\n global $wp_query;\n $wp_query->set_404();\n status_header(404);\n }\n}\n\n// This will show 404 on the attachment page\nadd_filter('template_redirect', 'wpse237762_set_404');\n\n// This will show 404 instead of redirecting to attachment page when dealing with a trailing slash\nadd_filter('redirect_canonical', 'wpse237762_set_404', 0);\n</code></pre>\n<p>To keep links to attachment pages working and redirect them straight to the file, you can use the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse237762_change_attachment_link($url, $id) {\n $attachment_url = wp_get_attachment_url($id);\n if ($attachment_url) {\n return $attachment_url;\n }\n return $url;\n}\n\nadd_filter('attachment_link', 'wpse237762_change_attachment_link', 10, 2);\n</code></pre>\n<p>To prevent attachment pages from reserving slugs from normal pages, you can use this code to set all new attachment slugs to random ones (UUIDv4 in this case)</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse237762_unique_slug($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) {\n if ($post_type === 'attachment') {\n return str_replace('-', '', wp_generate_uuid4());\n }\n return $slug;\n}\n\nadd_filter('wp_unique_post_slug', 'wpse237762_unique_slug', 10, 6);\n</code></pre>\n<p>This will prevent an image named <code>products.jpeg</code> reserving the URL <code>https://example.com/products</code>. That would result in a page named <strong>Products</strong> being given the URL <code>https://example.com/products-2</code> which obviously wouldn't be that great.</p>\n<p>I have put this code together in the <a href=\"https://wordpress.org/plugins/disable-media-pages/\" rel=\"noreferrer\">Disable Attachment Pages plugin</a>, which also includes a tool to scramble existing attachment slugs so they won't cause any problems in the future.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101256/"
] |
I have build a custom post\_type with "Resellers" in order to enter my personal reseller items. The "Resellers" post have taxonomies like "Countries" and "Departmens".
I am running into a problem:
The first time that the page is displayed, nothing gets fetched from my custom post type taxonomies. If I click on one of my links, then the data get successfully updated. The issue is Country without "Département" assigned category (Allemagne for example) = The results are displayed but the "Département" drop-list should be hidden.
Can anyone tell me where have I done a mistake ?
**function.php**
```
if( !function_exists( 'reseller_department' ) ){
function reseller_department(){
$location = get_terms( 'reseller-department', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_department']) ){
if($_GET['reseller_department'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_department']) || $_GET['reseller_department'] == '-1'){
echo '<option value="-1" selected>'.__( 'all departments', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
if( !function_exists( 'reseller_country' ) ){
function reseller_country(){
$location = get_terms( 'reseller-country', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_country']) ){
if($_GET['reseller_country'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_country']) || $_GET['reseller_country'] == '-1'){
echo '<option value="-1" selected>'.__( '...', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
```
**archieve.js**
```
jQuery(document).ready(function($) {
$("#archive-wrapper").height($("#archive-pot").height());
$("#archive-browser select").change(function() {
$("#archive-pot")
.empty()
.html("<div style='text-align: center; padding: 30px;'>Loading...</div>");
var d = $("#reseller_department").val();
var e = $("#reseller_country").val();
$.ajax({
url: "/work/",
dataType: "html",
type: "POST",
data: {
"digwp_d" : d,
"digwp_e" : e
},
success: function(data) {
$("#archive-pot").html(data);
$("#archive-wrapper").animate({
height: $("#archives-table tr").length * 50
});
}
});
});
// get all data option value reseller country
var values = [];
var sel = document.getElementById('reseller_country');
for (var i=0, n=sel.options.length;i<n;i++) {
if (sel.options[i].value)
values.push(sel.options[i].value);
}
var jupe = '"' + values.join('","') + '"';
var dataOptionCountry = values;
dataOptionCountry.pop();
// console.log(dataOptionCountry);
$("#reseller_country").change(function () {
$("#reseller_department").prop("disabled", !(dataOptionCountry.indexOf(this.value) !== -1));
});
});
```
**template-reseller-getter.php**
```
<?php
$rd = $_POST['digwp_d'];
$rc = $_POST['digwp_e'];
$querystring = "cat=$rc&cat=$rd&posts_per_page=-1";
query_posts($querystring);
?>
<?php if (($rc == '-1') && ($rd == '-1')) { ?>
<table id="archives-table" class="table">
<tr>
<td style='text-align: center; font-size: 15px; padding: 5px;'><?php _e("Please choose from above.", "nalys-plugin") ?></td>
</tr>
</table>
<?php } else { ?>
<div id="archives-table">
<?php
$custom_args_empty_one = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
$custom_args = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
if ( $rc != '-1' && $rd == '-1' || $rc == '-1' && $rd != '-1' ) {
$custom_query = new WP_Query( $custom_args_empty_one );
} elseif ( $rc != '-1' && $rd != '-1' ){
$custom_query = new WP_Query( $custom_args );
}
if ($custom_query->have_posts()) :
$row = 0;
while ($custom_query->have_posts()) :
$custom_query->the_post();
$count = $custom_query->post_count;
if($count==1){
// Displaying data
echo '<div class="archives-table-reseller col-md-offset-4 col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}else{
// Displaying data
echo '<div class="archives-table-reseller col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}
endwhile; else:
echo "Nothing found.";
endif;
?>
</div>
<?php } ?>
```
|
You can filter default rewrite rules and remove those for attachments:
```
function cleanup_default_rewrite_rules( $rules ) {
foreach ( $rules as $regex => $query ) {
if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) {
unset( $rules[ $regex ] );
}
}
return $rules;
}
add_filter( 'rewrite_rules_array', 'cleanup_default_rewrite_rules' );
```
Don't forget to re-save your permalinks once. WordPress will generate new rules without anything related to attachments.
Now, the attachment page URL gives 404. You can also add that redirect to prevent the 404 page, it's useless in this case. But I'm not sure how to catch the redirect - is\_attachment() will not work if the rewrite rules are removed.
**Update:**
WordPress will still offer the attachment page pretty URLs in media library and media insertion dialog. You can filter this as well:
```
function cleanup_attachment_link( $link ) {
return;
}
add_filter( 'attachment_link', 'cleanup_attachment_link' );
```
In this case, even when you insert your attachment into post ans select "Link to attachment page", the image will be inserted **without the link**.
|
237,820 |
<p>I retrieve information from database postmeta table.
I have 2 custom post type 'book' and 'author' I using metabox to connect them together. when user go to book custom post and adding new book. he must use check box metabox to determined which author write this book.</p>
<p>I have another page in my website which show author profile. in this page user can see books of author, my codes can save author for each book in database and read them perfectly and also can retrieve books of any author.</p>
<p>here is my problem I want to find each book feature image but when I use get_the_post_thumbnail it doesn't give me anything.</p>
<p>how can I fix this </p>
<p>I use var_dump to see each book information
here is the picture of it.
<a href="https://i.stack.imgur.com/5WQF3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5WQF3.png" alt="enter image description here"></a> </p>
<p>and here is my codes</p>
<pre><code><?php $args = array( 'post_type' => 'author');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post(); ?>
<div class="title-pack col-md-12 col-sm-12 col-xs-12">
<span class="line visible-sm-block"></span>
<span class="visible-sm-block tittle-style"><?php the_title(); ?></span>
</div>
<div class="row writer-crit">
<div class="writer-crit-box col-md-9 col-sm-8 col-xs-12">
<div class="col-md-11 col-sm-11 col-xs-12 pull-right">
<div class="writer-bio pull-right col-md-12 col-sm-12 col-xs-12">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'pull-right')); ?>
<div class="writer-content-bio col-md-8 col-sm-8 col-xs-12 pull-right">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 pull-right">
<h3>کتابشناسی </h3>
<?php $ars = array( 'post_type' => 'book');
$loop = new WP_Query( $ars );
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
// $vals=get_post_meta($post_id, $key2, true);
// $values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
global $wpdb;
$x=(string) $post_id;
$sql='SELECT post_id FROM wp_postmeta WHERE meta_key = "save-author-to-book" AND meta_value LIKE "%'.$x.'%"';
$results = $wpdb->get_results( $sql, OBJECT );
foreach ($results as $result ) {
$array[]=$result->post_id;
}
foreach ($array as $arr) { ?>
<?php $autr_book=get_post($arr);
//var_dump($autr_book);?>
<li class="">
<a href="<?php echo $autr_book->guid;?>">
<div><?php get_the_post_thumbnail( $autr_book->ID ); ?></div>
<p><?php echo $autr_book->post_title; ?></p>
</a>
</li>
<?php } ?>
</div>
</div>
</div>
</div>
<?php endwhile; // End of the loop. ?>
<!-- ====================================
</code></pre>
|
[
{
"answer_id": 237821,
"author": "WordPress Mechanic",
"author_id": 33660,
"author_profile": "https://wordpress.stackexchange.com/users/33660",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look here:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_post_thumbnail_id\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_post_thumbnail_id</a></p>\n\n<p>$post_thumbnail_id = get_post_thumbnail_id( $post_id );</p>\n\n<p>You are almost there if you correct your $post_id variable.</p>\n\n<p>Problem is here: \n<strong>$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );</strong></p>\n\n<p>Corrected:</p>\n\n<p><em>$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post_id) );</em></p>\n"
},
{
"answer_id": 237822,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": true,
"text": "<p>You use the function <code>get_the_post_thumbnail()</code> which returns a <code>string</code>. So you need to print that string with <code>echo</code> or use <code>the_post_thumbnail()</code> which echos itself.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237820",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101035/"
] |
I retrieve information from database postmeta table.
I have 2 custom post type 'book' and 'author' I using metabox to connect them together. when user go to book custom post and adding new book. he must use check box metabox to determined which author write this book.
I have another page in my website which show author profile. in this page user can see books of author, my codes can save author for each book in database and read them perfectly and also can retrieve books of any author.
here is my problem I want to find each book feature image but when I use get\_the\_post\_thumbnail it doesn't give me anything.
how can I fix this
I use var\_dump to see each book information
here is the picture of it.
[](https://i.stack.imgur.com/5WQF3.png)
and here is my codes
```
<?php $args = array( 'post_type' => 'author');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post(); ?>
<div class="title-pack col-md-12 col-sm-12 col-xs-12">
<span class="line visible-sm-block"></span>
<span class="visible-sm-block tittle-style"><?php the_title(); ?></span>
</div>
<div class="row writer-crit">
<div class="writer-crit-box col-md-9 col-sm-8 col-xs-12">
<div class="col-md-11 col-sm-11 col-xs-12 pull-right">
<div class="writer-bio pull-right col-md-12 col-sm-12 col-xs-12">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'pull-right')); ?>
<div class="writer-content-bio col-md-8 col-sm-8 col-xs-12 pull-right">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 pull-right">
<h3>کتابشناسی </h3>
<?php $ars = array( 'post_type' => 'book');
$loop = new WP_Query( $ars );
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
// $vals=get_post_meta($post_id, $key2, true);
// $values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
global $wpdb;
$x=(string) $post_id;
$sql='SELECT post_id FROM wp_postmeta WHERE meta_key = "save-author-to-book" AND meta_value LIKE "%'.$x.'%"';
$results = $wpdb->get_results( $sql, OBJECT );
foreach ($results as $result ) {
$array[]=$result->post_id;
}
foreach ($array as $arr) { ?>
<?php $autr_book=get_post($arr);
//var_dump($autr_book);?>
<li class="">
<a href="<?php echo $autr_book->guid;?>">
<div><?php get_the_post_thumbnail( $autr_book->ID ); ?></div>
<p><?php echo $autr_book->post_title; ?></p>
</a>
</li>
<?php } ?>
</div>
</div>
</div>
</div>
<?php endwhile; // End of the loop. ?>
<!-- ====================================
```
|
You use the function `get_the_post_thumbnail()` which returns a `string`. So you need to print that string with `echo` or use `the_post_thumbnail()` which echos itself.
|
237,827 |
<p>How we can get the complete cart details from the order id in woocommerce including the totals and subtotals etc.</p>
|
[
{
"answer_id": 237831,
"author": "Annapurna",
"author_id": 98322,
"author_profile": "https://wordpress.stackexchange.com/users/98322",
"pm_score": 2,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code><?php\n global $woocommerce;\n $items = $woocommerce->cart->get_cart();\n?>\n</code></pre>\n"
},
{
"answer_id": 343382,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 0,
"selected": false,
"text": "<p>Another variant:</p>\n\n<pre><code><?php\n\nWC()->cart->get_cart();\n</code></pre>\n"
},
{
"answer_id": 400469,
"author": "Walid Ajaj",
"author_id": 217075,
"author_profile": "https://wordpress.stackexchange.com/users/217075",
"pm_score": 2,
"selected": false,
"text": "<p>You can get order's cart details from the order object.</p>\n<p>if you only have the <code>id</code>, you can get <code>$order</code> object like this:</p>\n<pre><code>// Get $order object from order ID\n \n$order = wc_get_order( $order_id );\n</code></pre>\n<p>to get order's details:</p>\n<pre><code>if ( $order ) {\n\n // Get Order Totals $0.00\n $order->get_formatted_order_total();\n $order->get_cart_tax();\n $order->get_currency();\n $order->get_discount_tax();\n $order->get_discount_to_display();\n $order->get_discount_total();\n // etc.\n // etc.\n\n // Get and Loop Over Order Items\n foreach ( $order->get_items() as $item_id => $item ) {\n $product_id = $item->get_product_id();\n $variation_id = $item->get_variation_id();\n // etc.\n // etc.\n }\n}\n</code></pre>\n<p>You can refer to this link for more details:\n<a href=\"https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/\" rel=\"nofollow noreferrer\">https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/</a></p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83446/"
] |
How we can get the complete cart details from the order id in woocommerce including the totals and subtotals etc.
|
Try this:
```
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
?>
```
|
237,833 |
<p>I've got a partial called within <code>single.php</code> that looks like this:</p>
<pre><code><?php $userdata = get_userdata($post->post_author) ; ?>
<div class="entry-meta">
<span class="byline author vcard"><?= __('By', 'sage'); ?>
<a href="<?= get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn">
<?php echo ucfirst($userdata->user_nicename) ?>
</a>
</span>
</div>
</code></pre>
<p>Now, <code>$userdata</code> might be useful elsewhere within my single. So I'd like the variable and its value to be available globally within all templates that are included whenever my single is used.</p>
<p>So I cut out the first line: the creation of <code>$userdata</code> and put earlier in a 'parent' template that gets called earlier in the loop. </p>
<p>Alas, the variable was no longer avaiable to the partial. I tried a few other templates that are also called earlier in the loop. I got the same result: the variable wasn't available.</p>
<p>I thought about creating a function within <code>functions.php</code>. But I can think of a couple of reasons not to do this. First of all, why bother with an abstraction for <code>get_userdata()</code> when <code>get_userdata</code> already exists? This seems inelegant. </p>
|
[
{
"answer_id": 237843,
"author": "WordPress Mechanic",
"author_id": 33660,
"author_profile": "https://wordpress.stackexchange.com/users/33660",
"pm_score": 0,
"selected": false,
"text": "<p><strong>There are two solutions:</strong></p>\n\n<p><strong>1)</strong> Use a variable like this\nglobal <code>$userdata</code>;</p>\n\n<pre><code>$userdata = //object you want inside partial;\n</code></pre>\n\n<p>and then use </p>\n\n<p><code>global $userdata;</code> inside that <code>single.php</code> or loop etc.</p>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/get_template_part/</a></p>\n\n<p><strong>2)</strong> Keep doing the things as you are except one change\ninstead of <code>get_template_part</code>\nuse <code>include_once('filename.php')</code></p>\n"
},
{
"answer_id": 238082,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress caches the user information. There's really no problem just to call <code>get_userdata</code> every time you need it. The only thing you are doing by transfering it to a variable <code>$userdata</code> is have WP fetch it from another place in the memory.</p>\n\n<p>Note: read <a href=\"https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part\">this post</a> for a more general dealing with passing variables to partials.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51378/"
] |
I've got a partial called within `single.php` that looks like this:
```
<?php $userdata = get_userdata($post->post_author) ; ?>
<div class="entry-meta">
<span class="byline author vcard"><?= __('By', 'sage'); ?>
<a href="<?= get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn">
<?php echo ucfirst($userdata->user_nicename) ?>
</a>
</span>
</div>
```
Now, `$userdata` might be useful elsewhere within my single. So I'd like the variable and its value to be available globally within all templates that are included whenever my single is used.
So I cut out the first line: the creation of `$userdata` and put earlier in a 'parent' template that gets called earlier in the loop.
Alas, the variable was no longer avaiable to the partial. I tried a few other templates that are also called earlier in the loop. I got the same result: the variable wasn't available.
I thought about creating a function within `functions.php`. But I can think of a couple of reasons not to do this. First of all, why bother with an abstraction for `get_userdata()` when `get_userdata` already exists? This seems inelegant.
|
WordPress caches the user information. There's really no problem just to call `get_userdata` every time you need it. The only thing you are doing by transfering it to a variable `$userdata` is have WP fetch it from another place in the memory.
Note: read [this post](https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part) for a more general dealing with passing variables to partials.
|
237,834 |
<p>I set post per page from setting>maximum post per page to 20. I have 2 different custom post types 'book' and 'author' for archives of each of them. I want to load different number of post in page. I want to load 20 book per page in book archive and 5 post in author archive in each page. I also use WP-PageNavi plugin.</p>
<p>Here is my code</p>
<pre><code><?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array( 'post_type' => 'Author','paged' => $paged,'posts_per_page' =>5 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink(); ?>" class="writer-link col-md-12 col-sm-12 col-xs-12">
<div class="writer-row1 col-md-12 col-sm-12 col-xs-12">
<div class="col-md-2 col-sm-3 col-xs-12 image-right">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'img-responsive')); ?>
</div>
<div class="col-md-10 col-xs-12 col-sm-9 col-xs-12 pull-right writer-content">
<h3><?php the_title(); ?></h3>
<h4><?php the_field('auth-trans'); ?></h4>
<?php if ( get_field('writer-bio') ) {
echo '<p>'.get_field('writer-bio').'</p>';} ?>
<span>...</span>
</div>
</div>
</a>
<?php endwhile; // End of the loop. ?>
<div class="wp-pagenavi row">
<div id="wp_page_numbers text-center col-sm-6 center-margin">
<ul>
<li class="active_page text-center"><?php if(function_exists('wp_pagenavi')) { wp_pagenavi(array( 'query' => $loop )); } ?></li>
</ul>
</div>
</div>
</code></pre>
<p>No problem with book archive: it loads 20 posts. But I don't know how I can make author page to load just 5 post per page and after it has loaded 5 first posts it is going to next page.</p>
|
[
{
"answer_id": 237847,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>You will have to make the query arguments dependend on the type of archive you are generating (which WP already knows from the <a href=\"https://codex.wordpress.org/Post_Types#URLs\" rel=\"nofollow\">page slug</a>). Luckily there is a test for that, called <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive</code></a>. In the beginning of your code you would include this:</p>\n\n<pre><code>if (is_post_type_archive('books')) {\n $args = array( 'post_type' => 'Books','paged' => $paged,'posts_per_page' =>20 );\n }\nelseif (is_post_type_archive('author')) {\n $args = array( 'post_type' => 'Author','paged' => $paged,'posts_per_page' =>5 );\n }\n</code></pre>\n"
},
{
"answer_id": 270679,
"author": "megi",
"author_id": 122155,
"author_profile": "https://wordpress.stackexchange.com/users/122155",
"pm_score": 2,
"selected": false,
"text": "<p>add below code in functions.php file , here \"event\" is custom post type (change it as per your post type) , so here it will display 6 post on events list page , also you need to copy default archive.php file and copy and create new archive-event.php (replace event with your post type).</p>\n\n<pre><code> function custom_type_archive_display($query) {\n if (is_post_type_archive('event')) {\n $query->set('posts_per_page',6);\n $query->set('orderby', 'date' );\n $query->set('order', 'DESC' );\n return;\n } \n}\nadd_action('pre_get_posts', 'custom_type_archive_display');\n</code></pre>\n\n<p>Hope this Helps :)</p>\n\n<p>More detail how to list custom post on custom page refer this link <a href=\"https://wordpress.stackexchange.com/questions/175120/custom-posts-on-different-pages/270656#270656\">Custom Posts on Different Pages</a></p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101035/"
] |
I set post per page from setting>maximum post per page to 20. I have 2 different custom post types 'book' and 'author' for archives of each of them. I want to load different number of post in page. I want to load 20 book per page in book archive and 5 post in author archive in each page. I also use WP-PageNavi plugin.
Here is my code
```
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array( 'post_type' => 'Author','paged' => $paged,'posts_per_page' =>5 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink(); ?>" class="writer-link col-md-12 col-sm-12 col-xs-12">
<div class="writer-row1 col-md-12 col-sm-12 col-xs-12">
<div class="col-md-2 col-sm-3 col-xs-12 image-right">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'img-responsive')); ?>
</div>
<div class="col-md-10 col-xs-12 col-sm-9 col-xs-12 pull-right writer-content">
<h3><?php the_title(); ?></h3>
<h4><?php the_field('auth-trans'); ?></h4>
<?php if ( get_field('writer-bio') ) {
echo '<p>'.get_field('writer-bio').'</p>';} ?>
<span>...</span>
</div>
</div>
</a>
<?php endwhile; // End of the loop. ?>
<div class="wp-pagenavi row">
<div id="wp_page_numbers text-center col-sm-6 center-margin">
<ul>
<li class="active_page text-center"><?php if(function_exists('wp_pagenavi')) { wp_pagenavi(array( 'query' => $loop )); } ?></li>
</ul>
</div>
</div>
```
No problem with book archive: it loads 20 posts. But I don't know how I can make author page to load just 5 post per page and after it has loaded 5 first posts it is going to next page.
|
add below code in functions.php file , here "event" is custom post type (change it as per your post type) , so here it will display 6 post on events list page , also you need to copy default archive.php file and copy and create new archive-event.php (replace event with your post type).
```
function custom_type_archive_display($query) {
if (is_post_type_archive('event')) {
$query->set('posts_per_page',6);
$query->set('orderby', 'date' );
$query->set('order', 'DESC' );
return;
}
}
add_action('pre_get_posts', 'custom_type_archive_display');
```
Hope this Helps :)
More detail how to list custom post on custom page refer this link [Custom Posts on Different Pages](https://wordpress.stackexchange.com/questions/175120/custom-posts-on-different-pages/270656#270656)
|
237,854 |
<p>I have problem with <code>wp_localize_script</code>, That I cannot get <strong>boolean</strong> and <strong>int</strong> as variable</p>
<pre><code>wp_enqueue_script( 'helloworld' , 'helloworld.js', false, '1.0.0', true);
$site_config = array();
$site_config['boo'] = (bool)true;
$site_config['number'] = (int)1;
wp_localize_script( 'helloworld' , 'site_config' , $site_config );
</code></pre>
<p><strong>Why I getting :</strong></p>
<pre><code>var site_config = {"boo":"1","number":"1"};
</code></pre>
<p><strong>Why not :</strong></p>
<pre><code>var site_config = {"boo":true,"number":1};
</code></pre>
<ul>
<li>Wordpress 4.6 <em>(latest)</em></li>
<li>PHP 5.6.10</li>
</ul>
<p>Does not it fixed ? <a href="https://core.trac.wordpress.org/ticket/25280" rel="nofollow">https://core.trac.wordpress.org/ticket/25280</a> , I do anything wrong or missing something ?</p>
|
[
{
"answer_id": 237856,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2><em>Why</em> part:</h2>\n\n<p>The <em>Why</em> part can be found within the <code>WP_Scripts::localize()</code> method:</p>\n\n<pre><code>foreach ( (array) $l10n as $key => $value ) {\n if ( !is_scalar($value) )\n continue;\n\n $l10n[$key] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8');\n}\n</code></pre>\n\n<p>where we note the <code>(string)</code> casting.</p>\n\n<h2>Workarounds:</h2>\n\n<p>The <a href=\"https://core.trac.wordpress.org/attachment/ticket/25280/25280.5.patch\" rel=\"nofollow\">latest proposed patch</a> suggests replacing <code>is_scalar()</code> with <code>is_string()</code> and remove the <code>(string)</code> cast. That would work e.g. in a custom wrapper. But I don't think it's the way to go here, because the core <code>wp_scripts()->localize()</code> method can always change in the future.</p>\n\n<p>I also think it's too hacky to modify the data through the methods:</p>\n\n<pre><code>wp_scripts()->get_data( $handle, 'data' )\n</code></pre>\n\n<p>and</p>\n\n<pre><code>wp_scripts()->add_data( $handle, 'data', $data )\n</code></pre>\n\n<p>Doing it properly, we might end up writing a duplicate wrapper for <code>wp_scripts()->localize()</code> ;-)</p>\n\n<p>A more flexible workaround might be to use the <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow\">core function</a>:</p>\n\n<pre><code>wp_add_inline_script( $handle, $data, $position )` \n</code></pre>\n\n<p>to add our dynamic <strong>non-string</strong> values.</p>\n"
},
{
"answer_id": 237858,
"author": "Faisal Ramzan",
"author_id": 85487,
"author_profile": "https://wordpress.stackexchange.com/users/85487",
"pm_score": 1,
"selected": false,
"text": "<p>If Boolean value is <strong>true</strong> then it will return always <strong>1</strong> or if Boolean value is <strong>false</strong> then it will return <strong>empty</strong> that is why you're getting <strong>1</strong> in case of <strong>true</strong>.</p>\n\n<p>Below code is tested on my locally project. Copy and paste it exactly</p>\n\n<pre><code>//Add it in **functions.php**\nfunction load_localize_scripts() {\n wp_enqueue_script('localize_script', get_template_directory_uri() . '/js/localize_script.js', array(), '1.0.0', true );\n wp_localize_script('localize_script', 'localize_scripts_vars', array(\n 'boolean' => true, // it will return 1 \n 'integer' => 10 // it will always return integre\n )\n );\n}\nadd_action('wp_enqueue_scripts', 'load_localize_scripts');\n\n//Add this in **localize_script.js**\njQuery(document).ready(function() {\n var site_config;\n if (localize_scripts_vars.boolean == '1') {\n site_config = {\"boolean\":'true',\"number\":localize_scripts_vars.integer};\n console.log(site_config);\n } else if (localize_scripts_vars.boolean == '' || localize_scripts_vars.boolean == NULL) {\n site_config = {\"boolean\":'false',\"number\":localize_scripts_vars.integer};\n console.log(site_config);\n };\n});\n</code></pre>\n\n<p>You can see the consol result too <br/>\n<a href=\"https://i.stack.imgur.com/OhbKd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OhbKd.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 238253,
"author": "l2aelba",
"author_id": 6332,
"author_profile": "https://wordpress.stackexchange.com/users/6332",
"pm_score": 3,
"selected": true,
"text": "<p><strong>I just do something like this so long :</strong></p>\n\n<pre><code>wp_add_inline_script('helloworld','var site_config ='.json_encode($site_config));\n</code></pre>\n"
},
{
"answer_id": 371126,
"author": "rassoh",
"author_id": 18713,
"author_profile": "https://wordpress.stackexchange.com/users/18713",
"pm_score": 0,
"selected": false,
"text": "<p>If you wrap your booleans in an array, they come out clean:</p>\n<pre><code>$settings = [\n 'booleans' => [\n 'foo' => true,\n 'bar' => false,\n ],\n];\nwp_localize_script('my-script-handle', 'mySettings', $settings);\n</code></pre>\n<p>will render:</p>\n<pre><code><script type='text/javascript'>\n/* <![CDATA[ */\nvar mySettings = {"booleans":{"foo":true;"bar":false}};\n/* ]]> */\n</script>\n</code></pre>\n<p>Then you can access them cleanly from your script:</p>\n<pre><code>console.log( mySettings.booleans.foo === true ); // true\nconsole.log( mySettings.booleans.bar === false ); // true\n</code></pre>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6332/"
] |
I have problem with `wp_localize_script`, That I cannot get **boolean** and **int** as variable
```
wp_enqueue_script( 'helloworld' , 'helloworld.js', false, '1.0.0', true);
$site_config = array();
$site_config['boo'] = (bool)true;
$site_config['number'] = (int)1;
wp_localize_script( 'helloworld' , 'site_config' , $site_config );
```
**Why I getting :**
```
var site_config = {"boo":"1","number":"1"};
```
**Why not :**
```
var site_config = {"boo":true,"number":1};
```
* Wordpress 4.6 *(latest)*
* PHP 5.6.10
Does not it fixed ? <https://core.trac.wordpress.org/ticket/25280> , I do anything wrong or missing something ?
|
**I just do something like this so long :**
```
wp_add_inline_script('helloworld','var site_config ='.json_encode($site_config));
```
|
237,878 |
<p>Sometimes I want to change a post a little bit, but the post was already published on my blog. The change concerns adding/removing tags or rewriting the title of the post (just to correct a misspelled word). All the things can be done using the admin panel by pressing "quick edit".</p>
<p>Unfortunately, the action updates the "modified time". I'm using the "modified time" so people would know whether a post was modified or not. But I want to disable the modified time updates in the case when I just make some small changes like to ones described above. Is there a way to do it?</p>
|
[
{
"answer_id": 237889,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you're only displaying this information on the single post view and not making any searches for it.</p>\n\n<p>So another approach could be to save the <em>last modified</em> date-time for the content changes in a hidden <em>post meta field</em>, e.g. <code>_wpse_content_modified</code>.</p>\n\n<p>Look e.g. into the <a href=\"https://github.com/WordPress/WordPress/blob/4babadb704bade7ea2cddd2b33d56c72fc29b0ba/wp-includes/post.php#L3374-L3383\" rel=\"nofollow\"><code>post_updated</code></a> hook where you've access to both the previous post object and the modified post object.</p>\n\n<p>That way you don't have to make <em>irreversible</em> data modifications, for a core functionality, that you might later want to use unchanged.</p>\n"
},
{
"answer_id": 379931,
"author": "nydame",
"author_id": 86502,
"author_profile": "https://wordpress.stackexchange.com/users/86502",
"pm_score": 2,
"selected": false,
"text": "<p>The question of how to customize which post data gets updated has been answered <a href=\"https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved\">elsewhere on StackExchange</a>.</p>\n<p>Here is a specific example of how to stop the modified date from being updated:</p>\n<pre><code>function stop_modified_date_update( $new, $old ) {\n $new['post_modified'] = $old['post_modified'];\n $new['post_modified_gmt'] = $old['post_modified_gmt'];\n return $new;\n}\n\nadd_filter( 'wp_insert_post_data', 'stop_modified_date_update', 10, 2 );\n\n// do stuff that updates post(s) here\n\nremove_filter( 'wp_insert_post_data', 'stop_modified_date_update', 10, 2 );\n</code></pre>\n<p>NB: It is extremely important to remove the filter when you're done with your special tasks unless you really want the modified date to never update anywhere on the site.</p>\n<p>Happy coding!</p>\n"
},
{
"answer_id": 397115,
"author": "Yco",
"author_id": 210698,
"author_profile": "https://wordpress.stackexchange.com/users/210698",
"pm_score": 0,
"selected": false,
"text": "<p>Although that doesn't exactly answer the question, I leave 30 minutes before showing the modified date to correct a few errors quickly.</p>\n<pre><code><?php if ( get_the_modified_time( 'U' ) > get_the_time( 'U' ) + 1800 ) : ?>\n <div class="update"><?php the_modified_time( 'F j, Y g:i a' ); ?></div>\n<?php endif; ?>\n</code></pre>\n<p>Here, it is the delay <code>+ 1800</code> (1800 secs = 30 mins) that makes the difference.</p>\n"
},
{
"answer_id": 404865,
"author": "Pikamander2",
"author_id": 119995,
"author_profile": "https://wordpress.stackexchange.com/users/119995",
"pm_score": 0,
"selected": false,
"text": "<p>I tried out the answers above and the similar solution found <a href=\"https://brogramo.com/how-to-update-a-wordpress-post-without-updating-the-modified-date-using-wp_update_post/\" rel=\"nofollow noreferrer\">here</a> but was running into a problem where draft posts were still having their "Last Modified" date updated to the current time even though the published posts were updating correctly.</p>\n<p>On our site, that was a catastrophic problem because we have thousands of draft posts saved and being updated caused them to all be pushed to the top of the post list by default, crowding out all the published posts that had been updated recently.</p>\n<p>After restoring a backup of our site, I looked through the <a href=\"https://developer.wordpress.org/reference/functions/wp_update_post/\" rel=\"nofollow noreferrer\">wp_update_post documentation</a> but wasn't able to find much about the problem.</p>\n<p>After some trial and error, I came up with this workaround code that successfully updates both draft and published posts without changing their "Last Modified" date. I'm not sure if all of the code below is necessary, but at least it seems to work.</p>\n<pre><code>function do_not_update_modified_date($new, $old)\n{\n $post_status = $new['post_status'];\n \n if ($post_status === 'draft' || $post_status === 'pending' || $post_status === 'auto-draft')\n {\n $new_post_modified = $old['post_modified'];\n \n if ((!empty($new_post_modified)) && ($new_post_modified !== '0000-00-00 00:00:00'))\n {\n $new_post_modified = substr($new_post_modified, 0, -1) . (intval(substr($new_post_modified, -1)) + 1) % 10;\n }\n \n $new['post_modified'] = $new_post_modified;\n $new['post_modified_gmt'] = $new_post_modified;\n \n }\n \n else\n {\n $new['post_date'] = $old['post_date'];\n $new['post_date_gmt'] = $old['post_date_gmt'];\n $new['post_modified'] = $old['post_modified'];\n $new['post_modified_gmt'] = $old['post_modified_gmt'];\n }\n \n return $new;\n}\n\nadd_filter('wp_insert_post_data', 'do_not_update_modified_date'], 1, 2);\nwp_update_post(['edit_date' => true, 'ID' => $post_id, 'post_name' => $new_post_name, 'post_title' => $new_post_title,]);\nremove_filter('wp_insert_post_data', 'do_not_update_modified_date', 1, 2);\n</code></pre>\n<p><strong>Warning:</strong> I haven't tested this on anything besides published posts and draft posts. I have no idea whether this will mess up any scheduled posts or create any other problems. Please take a backup before running this and check everything thoroughly afterwards.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70882/"
] |
Sometimes I want to change a post a little bit, but the post was already published on my blog. The change concerns adding/removing tags or rewriting the title of the post (just to correct a misspelled word). All the things can be done using the admin panel by pressing "quick edit".
Unfortunately, the action updates the "modified time". I'm using the "modified time" so people would know whether a post was modified or not. But I want to disable the modified time updates in the case when I just make some small changes like to ones described above. Is there a way to do it?
|
The question of how to customize which post data gets updated has been answered [elsewhere on StackExchange](https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved).
Here is a specific example of how to stop the modified date from being updated:
```
function stop_modified_date_update( $new, $old ) {
$new['post_modified'] = $old['post_modified'];
$new['post_modified_gmt'] = $old['post_modified_gmt'];
return $new;
}
add_filter( 'wp_insert_post_data', 'stop_modified_date_update', 10, 2 );
// do stuff that updates post(s) here
remove_filter( 'wp_insert_post_data', 'stop_modified_date_update', 10, 2 );
```
NB: It is extremely important to remove the filter when you're done with your special tasks unless you really want the modified date to never update anywhere on the site.
Happy coding!
|
237,879 |
<p>Is it possible to override Javascript in a plugin with a child theme?</p>
<p>Specifically I'm trying to override a portion of a WooCommerce product page - I would like to get rid of the tabbed content areas, and instead have all of the content visible with the "tabs" then being anchor links down the page.</p>
<p>I've figured out how to do that on a local install by deleting a portion of Javascript within the WooCommerce plugin files - but that's obviously not a workable solution longterm.</p>
<p>I would like to essentially dequeue the Javascript in the plugin, and enqueue my own file with the unneeded portion removed.</p>
<p>This is the bit of code I need to be rid of, if there's another way to go about overriding it?</p>
<pre><code>.on( 'click', '.wc-tabs li a, ul.tabs li a', function( e ) {
e.preventDefault();
var $tab = $( this );
var $tabs_wrapper = $tab.closest( '.wc-tabs-wrapper, .woocommerce-tabs' );
var $tabs = $tabs_wrapper.find( '.wc-tabs, ul.tabs' );
$tabs.find( 'li' ).removeClass( 'active' );
$tabs_wrapper.find( '.wc-tab, .panel:not(.panel .panel)' ).hide();
$tab.closest( 'li' ).addClass( 'active' );
$tabs_wrapper.find( $tab.attr( 'href' ) ).show();
})
</code></pre>
|
[
{
"answer_id": 237881,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable this portion of JavaScript code with this code : </p>\n\n<pre><code>$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');\n</code></pre>\n\n<p><code>.off(</code> detach the listeners : <a href=\"http://api.jquery.com/off/\" rel=\"nofollow\">http://api.jquery.com/off/</a></p>\n"
},
{
"answer_id": 237902,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than hide them with javascript (you could also do that with CSS for that matter), the better solution would be to not generate the tabs to begin with. This is from the WooCommerce docs.</p>\n\n<pre><code>add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );\n\nfunction woo_remove_product_tabs( $tabs ) {\n\n unset( $tabs['description'] ); // Remove the description tab\n unset( $tabs['reviews'] ); // Remove the reviews tab\n unset( $tabs['additional_information'] ); // Remove the additional information tab\n\n return $tabs;\n}\n</code></pre>\n\n<p>From there you can edit the template file to display the content however you want to view it.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85805/"
] |
Is it possible to override Javascript in a plugin with a child theme?
Specifically I'm trying to override a portion of a WooCommerce product page - I would like to get rid of the tabbed content areas, and instead have all of the content visible with the "tabs" then being anchor links down the page.
I've figured out how to do that on a local install by deleting a portion of Javascript within the WooCommerce plugin files - but that's obviously not a workable solution longterm.
I would like to essentially dequeue the Javascript in the plugin, and enqueue my own file with the unneeded portion removed.
This is the bit of code I need to be rid of, if there's another way to go about overriding it?
```
.on( 'click', '.wc-tabs li a, ul.tabs li a', function( e ) {
e.preventDefault();
var $tab = $( this );
var $tabs_wrapper = $tab.closest( '.wc-tabs-wrapper, .woocommerce-tabs' );
var $tabs = $tabs_wrapper.find( '.wc-tabs, ul.tabs' );
$tabs.find( 'li' ).removeClass( 'active' );
$tabs_wrapper.find( '.wc-tab, .panel:not(.panel .panel)' ).hide();
$tab.closest( 'li' ).addClass( 'active' );
$tabs_wrapper.find( $tab.attr( 'href' ) ).show();
})
```
|
You can disable this portion of JavaScript code with this code :
```
$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');
```
`.off(` detach the listeners : <http://api.jquery.com/off/>
|
237,882 |
<p>I'm getting a feed error of 'XML parsing error: :[line number]:0: junk after document element'.</p>
<p>Although such errors often seem to be from unwanted code injections, mine is showing 'Cannot modify header information - headers already sent by'... which I've previously had with unwanted white space.</p>
<p>'Warning: Cannot modify header information - headers already sent by (output started at ...path to... /wp-includes/feed-rss2.php:11) in ...path to custom theme... /feed-rss2.php on line 3<.'</p>
<p>The two files noted in the error, are identical to those in other installs which don't have this error - which seems to trigger at the end of the last-but-one item in the feed.</p>
|
[
{
"answer_id": 237881,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable this portion of JavaScript code with this code : </p>\n\n<pre><code>$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');\n</code></pre>\n\n<p><code>.off(</code> detach the listeners : <a href=\"http://api.jquery.com/off/\" rel=\"nofollow\">http://api.jquery.com/off/</a></p>\n"
},
{
"answer_id": 237902,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than hide them with javascript (you could also do that with CSS for that matter), the better solution would be to not generate the tabs to begin with. This is from the WooCommerce docs.</p>\n\n<pre><code>add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );\n\nfunction woo_remove_product_tabs( $tabs ) {\n\n unset( $tabs['description'] ); // Remove the description tab\n unset( $tabs['reviews'] ); // Remove the reviews tab\n unset( $tabs['additional_information'] ); // Remove the additional information tab\n\n return $tabs;\n}\n</code></pre>\n\n<p>From there you can edit the template file to display the content however you want to view it.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] |
I'm getting a feed error of 'XML parsing error: :[line number]:0: junk after document element'.
Although such errors often seem to be from unwanted code injections, mine is showing 'Cannot modify header information - headers already sent by'... which I've previously had with unwanted white space.
'Warning: Cannot modify header information - headers already sent by (output started at ...path to... /wp-includes/feed-rss2.php:11) in ...path to custom theme... /feed-rss2.php on line 3<.'
The two files noted in the error, are identical to those in other installs which don't have this error - which seems to trigger at the end of the last-but-one item in the feed.
|
You can disable this portion of JavaScript code with this code :
```
$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');
```
`.off(` detach the listeners : <http://api.jquery.com/off/>
|
237,886 |
<p><strong>I know it's not supposed to work like this and that InstantWP is made for testing and not for an actual website</strong>, but I didn't know it when I started out and after two months of work I just can't throw it all away and start over.</p>
<p><em>Is there any way to transfer what I made on a ftp server ?</em></p>
<p>I'm a newbie, so please be kind and detailed :)</p>
|
[
{
"answer_id": 237881,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable this portion of JavaScript code with this code : </p>\n\n<pre><code>$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');\n</code></pre>\n\n<p><code>.off(</code> detach the listeners : <a href=\"http://api.jquery.com/off/\" rel=\"nofollow\">http://api.jquery.com/off/</a></p>\n"
},
{
"answer_id": 237902,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than hide them with javascript (you could also do that with CSS for that matter), the better solution would be to not generate the tabs to begin with. This is from the WooCommerce docs.</p>\n\n<pre><code>add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );\n\nfunction woo_remove_product_tabs( $tabs ) {\n\n unset( $tabs['description'] ); // Remove the description tab\n unset( $tabs['reviews'] ); // Remove the reviews tab\n unset( $tabs['additional_information'] ); // Remove the additional information tab\n\n return $tabs;\n}\n</code></pre>\n\n<p>From there you can edit the template file to display the content however you want to view it.</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102015/"
] |
**I know it's not supposed to work like this and that InstantWP is made for testing and not for an actual website**, but I didn't know it when I started out and after two months of work I just can't throw it all away and start over.
*Is there any way to transfer what I made on a ftp server ?*
I'm a newbie, so please be kind and detailed :)
|
You can disable this portion of JavaScript code with this code :
```
$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');
```
`.off(` detach the listeners : <http://api.jquery.com/off/>
|
237,903 |
<p>I've got a Layer 7 Load Balancer setup using HAProxy for WordPress Multisite.</p>
<p>I'm looking to have anything related to the WordPress backend to be served from a specific group of servers (A/K/A anything in <code>/wp-admin/</code>) while serving the frontend of the WordPress websites from another group of servers.</p>
<p>Do I need to adjust something in <code>wp-config.php</code> to change cookie names so that they include the server ID? or check for the server ID in the WordPress cookie? I feel like problems #1 and #2 are cookie related. I have no idea why #3 is happening. My servers aren't lagging at all, and should be responding plenty fast.</p>
<p><strong>With my current configuration I'm facing a few problems here:</strong></p>
<ol>
<li><p>It does indeed appear to be connecting me to the appropriate admin server. However, after a while in the dashboard. The WordPress
login form pops up asking me to re-login again.</p></li>
<li><p>Most admin pages work just fine however once in a while, again, same
as #1, the WordPress login for pops up and asks me to login again.</p></li>
<li><p>Every now in then I get a "504 Gateway Time-out - The server didn't
respond in time."</p></li>
</ol>
<p><strong>Here's what my configuration looks like:</strong></p>
<pre><code>defaults
log global
mode http
option httplog
option dontlognull
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
retries 3
option redispatch
maxconn 2000
timeout connect 5000
timeout check 5000
timeout client 30000
timeout server 30000
frontend http-in
bind *:80
option httplog
option http-server-close
acl has_domain hdr(host) -m found
acl has_www hdr_beg(host) -i www.
use_backend live_servers if has_domain has_www
acl has_admin path_beg /wp-admin
acl has_login path_beg /wp-login.php
acl has_custom_login path_beg /manage
use_backend admin_servers if has_admin or has_login or has_custom_login
default_backend live_servers
backend live_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
server s2 2.2.2.2:80 check cookie s2
backend admin_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
</code></pre>
<p>I'm willing to provide a pretty hefty bounty for this. If there's any settings which I'm missing or you think you could improve upon my configuration, please provide a full configuration including all appropriate settings in your answer.</p>
<p>Edit: I am currently using HAProxy 1.6.x and willing to upgrade to latest version if that's what it takes to get a valid solution.</p>
|
[
{
"answer_id": 238745,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Most of your question seem to be server related and would be off topic here, but here's my five cents on the WordPress related part.</p>\n\n<p>WP has a <a href=\"https://codex.wordpress.org/WordPress_Cookies\" rel=\"nofollow noreferrer\">pretty simple login cookies</a> system. It stores three cookies, one for the main url, one for the <code>wp-admin</code> directory and one for <code>wp-content\\plugins</code>. They contain just the user name and a double hashed password. Nothing server related. So, if the install is found at the right url, those cookies are not going to block anything unless they expire, an <a href=\"https://wordpress.stackexchange.com/questions/515/whats-the-easiest-way-to-stop-wp-from-ever-logging-me-out\">event that is plugin controlable</a>.</p>\n\n<p>You seem to report irregular logouts. From the above it follows that two things could be happening. Either a plugin is messing with the cookie expiration time or the url doesn't match.</p>\n\n<p>Concerning the first. Plenty of (e-commerce) plugins use <a href=\"http://silvermapleweb.com/using-the-php-session-in-wordpress/\" rel=\"nofollow noreferrer\">PHP sessions</a> to store data. That data may be stored server side. If the plugin somehow logs the user out when some session data is missing, you will be logged out when your load balancer decides to redirect you to a different server. This would explain irregular logouts.</p>\n\n<p>Concerning the second. That would involve some redirecting to a different url between servers. To me this seems less likely.</p>\n"
},
{
"answer_id": 239029,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p><strong>The problem #1 & #2</strong>:</p>\n\n<p>Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:</p>\n\n<p>This is what I have tried on vagrant boxes and with default WordPress structure:</p>\n\n<p><strong>1</strong>. Prepare 6 separate servers</p>\n\n<ul>\n<li><code>111.111.1.10</code> - MySQL server</li>\n<li><code>111.111.1.11</code> - HAProxy server</li>\n<li><code>111.111.1.12</code> & <code>111.111.1.13</code> - for admin URLs</li>\n<li><code>111.111.1.14</code> & <code>111.111.1.15</code> - for non-admin URLs</li>\n</ul>\n\n<p>HAProxy (v1.6) configurations:</p>\n\n<pre><code>defaults\n log global\n mode http\n option httplog\n option forwardfor \n option dontlognull\n option http-server-close\n timeout connect 5000\n timeout client 50000\n timeout server 50000\n errorfile 400 /etc/haproxy/errors/400.http\n errorfile 403 /etc/haproxy/errors/403.http\n errorfile 408 /etc/haproxy/errors/408.http\n errorfile 500 /etc/haproxy/errors/500.http\n errorfile 502 /etc/haproxy/errors/502.http\n errorfile 503 /etc/haproxy/errors/503.http\n errorfile 504 /etc/haproxy/errors/504.http\n\nfrontend http-revolver\n bind 111.111.1.11:80\n acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage\n use_backend admin-servers if url_is_wp_admin\n default_backend public-servers\n\nbackend public-servers\n server s1 111.111.1.12:80 check\n server s2 111.111.1.13:80 check\n\nbackend admin-servers\n server s3 111.111.1.14:80 check\n server s4 111.111.1.15:80 check\n\nlisten stats\n bind 111.111.1.11:1984\n stats enable\n stats scope http-revolver\n stats scope public-servers\n stats scope admin-servers\n stats uri /\n stats realm Haproxy\\ Statistics\n stats auth user:password\n</code></pre>\n\n<p><strong>2</strong>. Use <code>wpms.dev</code> as a demo domain and point it to <code>111.111.1.11</code> in <code>/etc/hosts</code> of host machine.</p>\n\n<p><strong>3</strong>. Install a base box with <code>ubuntu/trusty64</code> (LAMP stack + WP multisite) on server <code>111.111.1.12</code>.</p>\n\n<p>The most important step to avoid the problem #1 & #2 is, <strong>because some WordPress cookies depend on paths</strong>, we must make sure these constants are consistent in all servers:</p>\n\n<pre><code>define('WP_HOME', 'http://wpms.dev');\ndefine('WP_SITEURL', 'http://wpms.dev');\ndefine('DOMAIN_CURRENT_SITE', 'wpms.dev');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n\n<p>To do it, we just need to add it to <code>wp-config.php</code> in this base box.</p>\n\n<p><strong>4</strong>. Package the base box and duplicate it on other servers: <code>111.111.1.13</code>, <code>111.111.1.14</code> and <code>111.111.1.15</code>. Now <code>vagrant up</code> for all servers and check it out.</p>\n\n<p>If you have ssh authentication failure, you must point <code>config.ssh.private_key_path</code> to the <code>private_key</code> of the base box in <code>Vagrantfile</code>s of the duplicated boxes.</p>\n\n<p><strong>The problem #3</strong> is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-)</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9579/"
] |
I've got a Layer 7 Load Balancer setup using HAProxy for WordPress Multisite.
I'm looking to have anything related to the WordPress backend to be served from a specific group of servers (A/K/A anything in `/wp-admin/`) while serving the frontend of the WordPress websites from another group of servers.
Do I need to adjust something in `wp-config.php` to change cookie names so that they include the server ID? or check for the server ID in the WordPress cookie? I feel like problems #1 and #2 are cookie related. I have no idea why #3 is happening. My servers aren't lagging at all, and should be responding plenty fast.
**With my current configuration I'm facing a few problems here:**
1. It does indeed appear to be connecting me to the appropriate admin server. However, after a while in the dashboard. The WordPress
login form pops up asking me to re-login again.
2. Most admin pages work just fine however once in a while, again, same
as #1, the WordPress login for pops up and asks me to login again.
3. Every now in then I get a "504 Gateway Time-out - The server didn't
respond in time."
**Here's what my configuration looks like:**
```
defaults
log global
mode http
option httplog
option dontlognull
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
retries 3
option redispatch
maxconn 2000
timeout connect 5000
timeout check 5000
timeout client 30000
timeout server 30000
frontend http-in
bind *:80
option httplog
option http-server-close
acl has_domain hdr(host) -m found
acl has_www hdr_beg(host) -i www.
use_backend live_servers if has_domain has_www
acl has_admin path_beg /wp-admin
acl has_login path_beg /wp-login.php
acl has_custom_login path_beg /manage
use_backend admin_servers if has_admin or has_login or has_custom_login
default_backend live_servers
backend live_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
server s2 2.2.2.2:80 check cookie s2
backend admin_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
```
I'm willing to provide a pretty hefty bounty for this. If there's any settings which I'm missing or you think you could improve upon my configuration, please provide a full configuration including all appropriate settings in your answer.
Edit: I am currently using HAProxy 1.6.x and willing to upgrade to latest version if that's what it takes to get a valid solution.
|
**The problem #1 & #2**:
Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:
This is what I have tried on vagrant boxes and with default WordPress structure:
**1**. Prepare 6 separate servers
* `111.111.1.10` - MySQL server
* `111.111.1.11` - HAProxy server
* `111.111.1.12` & `111.111.1.13` - for admin URLs
* `111.111.1.14` & `111.111.1.15` - for non-admin URLs
HAProxy (v1.6) configurations:
```
defaults
log global
mode http
option httplog
option forwardfor
option dontlognull
option http-server-close
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend http-revolver
bind 111.111.1.11:80
acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage
use_backend admin-servers if url_is_wp_admin
default_backend public-servers
backend public-servers
server s1 111.111.1.12:80 check
server s2 111.111.1.13:80 check
backend admin-servers
server s3 111.111.1.14:80 check
server s4 111.111.1.15:80 check
listen stats
bind 111.111.1.11:1984
stats enable
stats scope http-revolver
stats scope public-servers
stats scope admin-servers
stats uri /
stats realm Haproxy\ Statistics
stats auth user:password
```
**2**. Use `wpms.dev` as a demo domain and point it to `111.111.1.11` in `/etc/hosts` of host machine.
**3**. Install a base box with `ubuntu/trusty64` (LAMP stack + WP multisite) on server `111.111.1.12`.
The most important step to avoid the problem #1 & #2 is, **because some WordPress cookies depend on paths**, we must make sure these constants are consistent in all servers:
```
define('WP_HOME', 'http://wpms.dev');
define('WP_SITEURL', 'http://wpms.dev');
define('DOMAIN_CURRENT_SITE', 'wpms.dev');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
To do it, we just need to add it to `wp-config.php` in this base box.
**4**. Package the base box and duplicate it on other servers: `111.111.1.13`, `111.111.1.14` and `111.111.1.15`. Now `vagrant up` for all servers and check it out.
If you have ssh authentication failure, you must point `config.ssh.private_key_path` to the `private_key` of the base box in `Vagrantfile`s of the duplicated boxes.
**The problem #3** is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-)
|
237,913 |
<p>I need to override the 404 code for a very specific scenario and it's not yet fully working.</p>
<p>I am linking day archives with <code>rel=prev/next</code>, and the chain is supposed to be intact start-to-end. For this reason, at least one post needs to be published everyday, best right at midnight. This should not be a problem editorially, with at least 10 posts being expected even on a slow news day.</p>
<p>However, accidents may happen - like downtime or unwarranted deletions or whatnot. Even in these cases, things should be repaired from the publishing end as soon as noticed (with at least one post forth/backdated to cover for the empty day).</p>
<p>Still, I wouldn't want the prev/next chain to ever be broken, so I'm thinking this as the ultimate fallback - ideally never triggered.</p>
<p>I have added the following to the functions.php template:</p>
<pre><code>add_action( 'template_redirect', 'empty_day', 0 );
function empty_day() {
global $wp_query;
if ($wp_query->post_count == 0 && $wp_query->query['day'] ) {
status_header( '200' );
$wp_query->is_404 = false;
$wp_query->is_day = true;
$wp_query->is_date = true;
$wp_query->is_archive = true;
}
}
</code></pre>
<p>It works nicely redirecting the empty page to the archive template, prev/next tags in place.</p>
<p>However, functions stop working outside the loop completely (no return), so I can't <a href="https://codex.wordpress.org/Function_Reference/get_the_time" rel="nofollow noreferrer"><code>get_the_time</code></a> nor <a href="https://codex.wordpress.org/Function_Reference/get_the_date" rel="nofollow noreferrer"><code>get_the_date</code></a> to output anything.</p>
<p>I already tried the solutions suggested <a href="https://wordpress.stackexchange.com/questions/104991/preventing-404-error-on-empty-date-archive">here</a> or <a href="https://wordpress.org/support/topic/empty-archives-returning-404" rel="nofollow noreferrer">here</a>, but they still fail to get the date with the <code>template_redirect</code> filter or redirect the template altogether with <code>404_template</code>.</p>
<p>Any Idea on how to have them working again?</p>
|
[
{
"answer_id": 238745,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Most of your question seem to be server related and would be off topic here, but here's my five cents on the WordPress related part.</p>\n\n<p>WP has a <a href=\"https://codex.wordpress.org/WordPress_Cookies\" rel=\"nofollow noreferrer\">pretty simple login cookies</a> system. It stores three cookies, one for the main url, one for the <code>wp-admin</code> directory and one for <code>wp-content\\plugins</code>. They contain just the user name and a double hashed password. Nothing server related. So, if the install is found at the right url, those cookies are not going to block anything unless they expire, an <a href=\"https://wordpress.stackexchange.com/questions/515/whats-the-easiest-way-to-stop-wp-from-ever-logging-me-out\">event that is plugin controlable</a>.</p>\n\n<p>You seem to report irregular logouts. From the above it follows that two things could be happening. Either a plugin is messing with the cookie expiration time or the url doesn't match.</p>\n\n<p>Concerning the first. Plenty of (e-commerce) plugins use <a href=\"http://silvermapleweb.com/using-the-php-session-in-wordpress/\" rel=\"nofollow noreferrer\">PHP sessions</a> to store data. That data may be stored server side. If the plugin somehow logs the user out when some session data is missing, you will be logged out when your load balancer decides to redirect you to a different server. This would explain irregular logouts.</p>\n\n<p>Concerning the second. That would involve some redirecting to a different url between servers. To me this seems less likely.</p>\n"
},
{
"answer_id": 239029,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p><strong>The problem #1 & #2</strong>:</p>\n\n<p>Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:</p>\n\n<p>This is what I have tried on vagrant boxes and with default WordPress structure:</p>\n\n<p><strong>1</strong>. Prepare 6 separate servers</p>\n\n<ul>\n<li><code>111.111.1.10</code> - MySQL server</li>\n<li><code>111.111.1.11</code> - HAProxy server</li>\n<li><code>111.111.1.12</code> & <code>111.111.1.13</code> - for admin URLs</li>\n<li><code>111.111.1.14</code> & <code>111.111.1.15</code> - for non-admin URLs</li>\n</ul>\n\n<p>HAProxy (v1.6) configurations:</p>\n\n<pre><code>defaults\n log global\n mode http\n option httplog\n option forwardfor \n option dontlognull\n option http-server-close\n timeout connect 5000\n timeout client 50000\n timeout server 50000\n errorfile 400 /etc/haproxy/errors/400.http\n errorfile 403 /etc/haproxy/errors/403.http\n errorfile 408 /etc/haproxy/errors/408.http\n errorfile 500 /etc/haproxy/errors/500.http\n errorfile 502 /etc/haproxy/errors/502.http\n errorfile 503 /etc/haproxy/errors/503.http\n errorfile 504 /etc/haproxy/errors/504.http\n\nfrontend http-revolver\n bind 111.111.1.11:80\n acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage\n use_backend admin-servers if url_is_wp_admin\n default_backend public-servers\n\nbackend public-servers\n server s1 111.111.1.12:80 check\n server s2 111.111.1.13:80 check\n\nbackend admin-servers\n server s3 111.111.1.14:80 check\n server s4 111.111.1.15:80 check\n\nlisten stats\n bind 111.111.1.11:1984\n stats enable\n stats scope http-revolver\n stats scope public-servers\n stats scope admin-servers\n stats uri /\n stats realm Haproxy\\ Statistics\n stats auth user:password\n</code></pre>\n\n<p><strong>2</strong>. Use <code>wpms.dev</code> as a demo domain and point it to <code>111.111.1.11</code> in <code>/etc/hosts</code> of host machine.</p>\n\n<p><strong>3</strong>. Install a base box with <code>ubuntu/trusty64</code> (LAMP stack + WP multisite) on server <code>111.111.1.12</code>.</p>\n\n<p>The most important step to avoid the problem #1 & #2 is, <strong>because some WordPress cookies depend on paths</strong>, we must make sure these constants are consistent in all servers:</p>\n\n<pre><code>define('WP_HOME', 'http://wpms.dev');\ndefine('WP_SITEURL', 'http://wpms.dev');\ndefine('DOMAIN_CURRENT_SITE', 'wpms.dev');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n\n<p>To do it, we just need to add it to <code>wp-config.php</code> in this base box.</p>\n\n<p><strong>4</strong>. Package the base box and duplicate it on other servers: <code>111.111.1.13</code>, <code>111.111.1.14</code> and <code>111.111.1.15</code>. Now <code>vagrant up</code> for all servers and check it out.</p>\n\n<p>If you have ssh authentication failure, you must point <code>config.ssh.private_key_path</code> to the <code>private_key</code> of the base box in <code>Vagrantfile</code>s of the duplicated boxes.</p>\n\n<p><strong>The problem #3</strong> is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-)</p>\n"
}
] |
2016/09/01
|
[
"https://wordpress.stackexchange.com/questions/237913",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70333/"
] |
I need to override the 404 code for a very specific scenario and it's not yet fully working.
I am linking day archives with `rel=prev/next`, and the chain is supposed to be intact start-to-end. For this reason, at least one post needs to be published everyday, best right at midnight. This should not be a problem editorially, with at least 10 posts being expected even on a slow news day.
However, accidents may happen - like downtime or unwarranted deletions or whatnot. Even in these cases, things should be repaired from the publishing end as soon as noticed (with at least one post forth/backdated to cover for the empty day).
Still, I wouldn't want the prev/next chain to ever be broken, so I'm thinking this as the ultimate fallback - ideally never triggered.
I have added the following to the functions.php template:
```
add_action( 'template_redirect', 'empty_day', 0 );
function empty_day() {
global $wp_query;
if ($wp_query->post_count == 0 && $wp_query->query['day'] ) {
status_header( '200' );
$wp_query->is_404 = false;
$wp_query->is_day = true;
$wp_query->is_date = true;
$wp_query->is_archive = true;
}
}
```
It works nicely redirecting the empty page to the archive template, prev/next tags in place.
However, functions stop working outside the loop completely (no return), so I can't [`get_the_time`](https://codex.wordpress.org/Function_Reference/get_the_time) nor [`get_the_date`](https://codex.wordpress.org/Function_Reference/get_the_date) to output anything.
I already tried the solutions suggested [here](https://wordpress.stackexchange.com/questions/104991/preventing-404-error-on-empty-date-archive) or [here](https://wordpress.org/support/topic/empty-archives-returning-404), but they still fail to get the date with the `template_redirect` filter or redirect the template altogether with `404_template`.
Any Idea on how to have them working again?
|
**The problem #1 & #2**:
Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:
This is what I have tried on vagrant boxes and with default WordPress structure:
**1**. Prepare 6 separate servers
* `111.111.1.10` - MySQL server
* `111.111.1.11` - HAProxy server
* `111.111.1.12` & `111.111.1.13` - for admin URLs
* `111.111.1.14` & `111.111.1.15` - for non-admin URLs
HAProxy (v1.6) configurations:
```
defaults
log global
mode http
option httplog
option forwardfor
option dontlognull
option http-server-close
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend http-revolver
bind 111.111.1.11:80
acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage
use_backend admin-servers if url_is_wp_admin
default_backend public-servers
backend public-servers
server s1 111.111.1.12:80 check
server s2 111.111.1.13:80 check
backend admin-servers
server s3 111.111.1.14:80 check
server s4 111.111.1.15:80 check
listen stats
bind 111.111.1.11:1984
stats enable
stats scope http-revolver
stats scope public-servers
stats scope admin-servers
stats uri /
stats realm Haproxy\ Statistics
stats auth user:password
```
**2**. Use `wpms.dev` as a demo domain and point it to `111.111.1.11` in `/etc/hosts` of host machine.
**3**. Install a base box with `ubuntu/trusty64` (LAMP stack + WP multisite) on server `111.111.1.12`.
The most important step to avoid the problem #1 & #2 is, **because some WordPress cookies depend on paths**, we must make sure these constants are consistent in all servers:
```
define('WP_HOME', 'http://wpms.dev');
define('WP_SITEURL', 'http://wpms.dev');
define('DOMAIN_CURRENT_SITE', 'wpms.dev');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
To do it, we just need to add it to `wp-config.php` in this base box.
**4**. Package the base box and duplicate it on other servers: `111.111.1.13`, `111.111.1.14` and `111.111.1.15`. Now `vagrant up` for all servers and check it out.
If you have ssh authentication failure, you must point `config.ssh.private_key_path` to the `private_key` of the base box in `Vagrantfile`s of the duplicated boxes.
**The problem #3** is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-)
|
237,947 |
<p>My organization has a website powered by wordpress. We are using pagebuilder to design pages. We also have some assets (pdf files, ppts) etc. Currently everyone can access these files. </p>
<p>I need to modify them so that there is some access control. So the first suggestion to provide the access control was “register” each user that wants to access the files. Based on the type of user (normal, HR, Finance etc) each of them can have access to a specific set of files. </p>
<p>Could anyone suggest how the above can be done. </p>
|
[
{
"answer_id": 238745,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Most of your question seem to be server related and would be off topic here, but here's my five cents on the WordPress related part.</p>\n\n<p>WP has a <a href=\"https://codex.wordpress.org/WordPress_Cookies\" rel=\"nofollow noreferrer\">pretty simple login cookies</a> system. It stores three cookies, one for the main url, one for the <code>wp-admin</code> directory and one for <code>wp-content\\plugins</code>. They contain just the user name and a double hashed password. Nothing server related. So, if the install is found at the right url, those cookies are not going to block anything unless they expire, an <a href=\"https://wordpress.stackexchange.com/questions/515/whats-the-easiest-way-to-stop-wp-from-ever-logging-me-out\">event that is plugin controlable</a>.</p>\n\n<p>You seem to report irregular logouts. From the above it follows that two things could be happening. Either a plugin is messing with the cookie expiration time or the url doesn't match.</p>\n\n<p>Concerning the first. Plenty of (e-commerce) plugins use <a href=\"http://silvermapleweb.com/using-the-php-session-in-wordpress/\" rel=\"nofollow noreferrer\">PHP sessions</a> to store data. That data may be stored server side. If the plugin somehow logs the user out when some session data is missing, you will be logged out when your load balancer decides to redirect you to a different server. This would explain irregular logouts.</p>\n\n<p>Concerning the second. That would involve some redirecting to a different url between servers. To me this seems less likely.</p>\n"
},
{
"answer_id": 239029,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p><strong>The problem #1 & #2</strong>:</p>\n\n<p>Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:</p>\n\n<p>This is what I have tried on vagrant boxes and with default WordPress structure:</p>\n\n<p><strong>1</strong>. Prepare 6 separate servers</p>\n\n<ul>\n<li><code>111.111.1.10</code> - MySQL server</li>\n<li><code>111.111.1.11</code> - HAProxy server</li>\n<li><code>111.111.1.12</code> & <code>111.111.1.13</code> - for admin URLs</li>\n<li><code>111.111.1.14</code> & <code>111.111.1.15</code> - for non-admin URLs</li>\n</ul>\n\n<p>HAProxy (v1.6) configurations:</p>\n\n<pre><code>defaults\n log global\n mode http\n option httplog\n option forwardfor \n option dontlognull\n option http-server-close\n timeout connect 5000\n timeout client 50000\n timeout server 50000\n errorfile 400 /etc/haproxy/errors/400.http\n errorfile 403 /etc/haproxy/errors/403.http\n errorfile 408 /etc/haproxy/errors/408.http\n errorfile 500 /etc/haproxy/errors/500.http\n errorfile 502 /etc/haproxy/errors/502.http\n errorfile 503 /etc/haproxy/errors/503.http\n errorfile 504 /etc/haproxy/errors/504.http\n\nfrontend http-revolver\n bind 111.111.1.11:80\n acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage\n use_backend admin-servers if url_is_wp_admin\n default_backend public-servers\n\nbackend public-servers\n server s1 111.111.1.12:80 check\n server s2 111.111.1.13:80 check\n\nbackend admin-servers\n server s3 111.111.1.14:80 check\n server s4 111.111.1.15:80 check\n\nlisten stats\n bind 111.111.1.11:1984\n stats enable\n stats scope http-revolver\n stats scope public-servers\n stats scope admin-servers\n stats uri /\n stats realm Haproxy\\ Statistics\n stats auth user:password\n</code></pre>\n\n<p><strong>2</strong>. Use <code>wpms.dev</code> as a demo domain and point it to <code>111.111.1.11</code> in <code>/etc/hosts</code> of host machine.</p>\n\n<p><strong>3</strong>. Install a base box with <code>ubuntu/trusty64</code> (LAMP stack + WP multisite) on server <code>111.111.1.12</code>.</p>\n\n<p>The most important step to avoid the problem #1 & #2 is, <strong>because some WordPress cookies depend on paths</strong>, we must make sure these constants are consistent in all servers:</p>\n\n<pre><code>define('WP_HOME', 'http://wpms.dev');\ndefine('WP_SITEURL', 'http://wpms.dev');\ndefine('DOMAIN_CURRENT_SITE', 'wpms.dev');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n\n<p>To do it, we just need to add it to <code>wp-config.php</code> in this base box.</p>\n\n<p><strong>4</strong>. Package the base box and duplicate it on other servers: <code>111.111.1.13</code>, <code>111.111.1.14</code> and <code>111.111.1.15</code>. Now <code>vagrant up</code> for all servers and check it out.</p>\n\n<p>If you have ssh authentication failure, you must point <code>config.ssh.private_key_path</code> to the <code>private_key</code> of the base box in <code>Vagrantfile</code>s of the duplicated boxes.</p>\n\n<p><strong>The problem #3</strong> is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-)</p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/237947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102068/"
] |
My organization has a website powered by wordpress. We are using pagebuilder to design pages. We also have some assets (pdf files, ppts) etc. Currently everyone can access these files.
I need to modify them so that there is some access control. So the first suggestion to provide the access control was “register” each user that wants to access the files. Based on the type of user (normal, HR, Finance etc) each of them can have access to a specific set of files.
Could anyone suggest how the above can be done.
|
**The problem #1 & #2**:
Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:
This is what I have tried on vagrant boxes and with default WordPress structure:
**1**. Prepare 6 separate servers
* `111.111.1.10` - MySQL server
* `111.111.1.11` - HAProxy server
* `111.111.1.12` & `111.111.1.13` - for admin URLs
* `111.111.1.14` & `111.111.1.15` - for non-admin URLs
HAProxy (v1.6) configurations:
```
defaults
log global
mode http
option httplog
option forwardfor
option dontlognull
option http-server-close
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend http-revolver
bind 111.111.1.11:80
acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage
use_backend admin-servers if url_is_wp_admin
default_backend public-servers
backend public-servers
server s1 111.111.1.12:80 check
server s2 111.111.1.13:80 check
backend admin-servers
server s3 111.111.1.14:80 check
server s4 111.111.1.15:80 check
listen stats
bind 111.111.1.11:1984
stats enable
stats scope http-revolver
stats scope public-servers
stats scope admin-servers
stats uri /
stats realm Haproxy\ Statistics
stats auth user:password
```
**2**. Use `wpms.dev` as a demo domain and point it to `111.111.1.11` in `/etc/hosts` of host machine.
**3**. Install a base box with `ubuntu/trusty64` (LAMP stack + WP multisite) on server `111.111.1.12`.
The most important step to avoid the problem #1 & #2 is, **because some WordPress cookies depend on paths**, we must make sure these constants are consistent in all servers:
```
define('WP_HOME', 'http://wpms.dev');
define('WP_SITEURL', 'http://wpms.dev');
define('DOMAIN_CURRENT_SITE', 'wpms.dev');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
To do it, we just need to add it to `wp-config.php` in this base box.
**4**. Package the base box and duplicate it on other servers: `111.111.1.13`, `111.111.1.14` and `111.111.1.15`. Now `vagrant up` for all servers and check it out.
If you have ssh authentication failure, you must point `config.ssh.private_key_path` to the `private_key` of the base box in `Vagrantfile`s of the duplicated boxes.
**The problem #3** is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-)
|
237,957 |
<p>I am trying to fetch a post based on the following meta keys.</p>
<ul>
<li><code>post_code</code> with <code>432C</code></li>
<li><code>location</code> with <code>XYZ</code>
Both belong to a CPT. I'm trying to fetch the Post with both these meta_values. </li>
</ul>
<p>I Don't Want an OR relation, I want a AND relation, I have tried several <code>WP_Query</code> objects and still haven't found a solution after hours of looking. </p>
|
[
{
"answer_id": 237958,
"author": "Manthan Dave",
"author_id": 83209,
"author_profile": "https://wordpress.stackexchange.com/users/83209",
"pm_score": -1,
"selected": false,
"text": "<p>Tried below object parametes</p>\n\n<pre><code>array(\n 'key' => 'post_code',\n 'value' =>'432C',\n 'compare' => '='\n ),\n array(\n 'relation' =>'AND',\n array(\n\n 'key' => 'location',\n 'value' => 'XYZ',\n 'compare' => '=',\n\n ),\n )\n</code></pre>\n"
},
{
"answer_id": 237959,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 4,
"selected": false,
"text": "<p>This should do it. The default relation is AND so that won't need to be specified.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'wpse_cpt',\n 'meta_query' => array(\n array(\n 'key' => 'post_code',\n 'value' => '432C',\n ),\n array(\n 'key' => 'location',\n 'value' => 'XYZ',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 237993,
"author": "Chiranjib Khanra",
"author_id": 102086,
"author_profile": "https://wordpress.stackexchange.com/users/102086",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$args = array(\n 'post_type' => 'wpse_cpt',\n 'meta_query' => array(\n 'relation' => 'AND' //**** Use AND or OR as per your required Where Clause\n array(\n 'key' => 'post_code',\n 'value' => '432C',\n ),\n array(\n 'key' => 'location',\n 'value' => 'XYZ',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 273468,
"author": "Sheraz Ahmed",
"author_id": 89206,
"author_profile": "https://wordpress.stackexchange.com/users/89206",
"pm_score": 2,
"selected": true,
"text": "<p><strong>SOLUTION</strong></p>\n\n<p>The Solution Accepted below worked, however, I wanted to know how is it working?</p>\n\n<p>This is how it's working</p>\n\n<pre><code>SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2\n WHERE p.ID = m1.post_id and p.ID = m2.post_id\n AND m1.meta_key = 'key1' AND m1.meta_value = 'value1'\n AND m2.meta_key = 'key2' AND m2.meta_value = 'value2'\n AND p.post_type = 'cpt' AND p.post_status = 'published'\n</code></pre>\n"
},
{
"answer_id": 337400,
"author": "Eric Shoberg",
"author_id": 167629,
"author_profile": "https://wordpress.stackexchange.com/users/167629",
"pm_score": 2,
"selected": false,
"text": "<p>Edit Again: Ah, I didn't answer the question. You would select <code>a.*</code> to get all columns of the posts with the matching key values, instead of selecting <code>c.meta_value</code>.</p>\n\n<p>The below sql/<code>$wpdb</code> query will select all meta_value<code>%s</code> of a post with post_type of <code>$postType</code> and a meta_key value of <code>$metaKey</code>. Therefore selecting all the different values of a given meta_key (via '$metaKey'). The <code>term_relationships</code> table is wordpress' helper table for relationship connections in tables. <code>wp_posts</code> is the wordpress 'posts' table, and, <code>wp_postmeta</code> is the wordpress 'postmeta' table. (Note: If you are using custom tables these table names would differ.) </p>\n\n<p>~ Edited to add 'doing' notes, requested by @MikeNGarrett</p>\n\n<pre><code>/* $wpdb is a global var provided by the wordpress 'engine'\n** for query'ing wordpress database tables. \n*/\nglobal $wpdb; \n$postType = 'mycustomposttype';\n$metaKey = 'mymetakey';\n$query = \"\n SELECT c.meta_value \n FROM wp_posts a \n LEFT JOIN wp_term_relationships b \n ON (a.ID = b.object_id) \n LEFT JOIN wp_postmeta c \n ON (a.ID = c.post_id) \n WHERE a.post_type = %s AND c.meta_key = %s\";\n\n$metaValues = $wpdb->prepare(query, [$postType, $metaKey]);\n$metaValues = $wpdb->get_results($metaValues);\n</code></pre>\n\n<p>Notes: I am just reusing the $metaValues variable. There is no other reason to write the results of $metaValues <code>prepare()</code> back to the $metaValues variable. You do however have to pass $metaValues to <code>get_resluts()</code>. </p>\n"
},
{
"answer_id": 395530,
"author": "breadwild",
"author_id": 153797,
"author_profile": "https://wordpress.stackexchange.com/users/153797",
"pm_score": 0,
"selected": false,
"text": "<p>I tried using the WP_Query solution suggested above, but got an empty result. The one suggested by Sheraz Ahmed works fine. Here's my own take for what it's worth:</p>\n<pre><code>//database\nwp_posts\n+---------+--------------------+--------------+\n| ID | post_title | post_type |\n+---------+--------------------+--------------+\n| 8567 | Intro to MySQL | talk |\n+---------+--------------------+--------------+\n| 8590 | Intro to PHP | talk |\n+---------+--------------------+--------------+\n\nwp_postmeta\n+---------------+------------+----------------+\n| post_id | meta_key | meta_value |\n+---------------+------------+----------------+\n| 8567 | speaker | John Doe |\n+---------------+------------+----------------+\n| 8567 | year_of | 2021 |\n+---------------+------------+----------------+\n| 8590 | speaker | John Doe |\n+---------------+------------+----------------+\n| 8590 | year_of | 2021 |\n+---------------+------------+----------------+\n\n\n//search by speaker and Year\n$speaker = "John Doe";\n$year_of = "2021";\n\n$talks = $wpdb->get_results( \n $wpdb->prepare( \n 'SELECT post_title, meta_value AS speaker \n FROM '.$wpdb->prefix.'posts AS pt, '.$wpdb->prefix.'postmeta AS pm \n WHERE post_type = %s AND pm.post_id = pt.id AND ( meta_key = %s AND meta_value = %s ) \n AND post_id IN ( SELECT post_id FROM nm_postmeta WHERE meta_key = %s AND meta_value = %s )',\n array( 'talk', \n 'speaker', \n $speaker, \n 'year_of', \n $year_of )\n )\n);\n \nforeach ( $talks as $talk ) {\n echo "<p>".$talk->speaker.': '.$talk_homily->post_title."</p>";\n}\n</code></pre>\n<p>John Doe: Intro to MySQL</p>\n<p>John Doe: Intro to PHP</p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/237957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89206/"
] |
I am trying to fetch a post based on the following meta keys.
* `post_code` with `432C`
* `location` with `XYZ`
Both belong to a CPT. I'm trying to fetch the Post with both these meta\_values.
I Don't Want an OR relation, I want a AND relation, I have tried several `WP_Query` objects and still haven't found a solution after hours of looking.
|
**SOLUTION**
The Solution Accepted below worked, however, I wanted to know how is it working?
This is how it's working
```
SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2
WHERE p.ID = m1.post_id and p.ID = m2.post_id
AND m1.meta_key = 'key1' AND m1.meta_value = 'value1'
AND m2.meta_key = 'key2' AND m2.meta_value = 'value2'
AND p.post_type = 'cpt' AND p.post_status = 'published'
```
|
237,986 |
<p>I have three files: <code>submit.php</code> (a page), <code>validation.php</code>, <code>script.php</code></p>
<p>I am trying to use the fields as a front end submission area via the <code>wp_insert_post()</code> function.</p>
<p>However, I don't know exactly where to put the function, as where I try either is before the <code>validation.php</code> file or if I put it in that file it causes an error since it can't pass wordpress functions.</p>
<p>I have tried playing with the <code>success</code> in the <code>$.ajax</code> but since the <code>die()</code> functions all result in it being successful can't trigger a create post.</p>
<p>Does anyone have a better solution?</p>
<p>In the <code>submit.php</code> I have a form:</p>
<pre><code><div class="" id="response"></div>
<form id="form_ticket_submit" method="post">
<label for="form_ticket_subject">Subject of issue</label>
<input id="form_ticket_subject" name="form_ticket_subject" type="text">
<label for="form_ticket_content">Post</label>
<textarea id="form_ticket_content" name="form_ticket_content"></textarea>
<label for="form_ticket_tax_stage">Select Stage</label>
<select id="form_ticket_tax_stage" name="form_ticket_tax_stage">
<option value="">Select one</option>
<?php foreach ($form_ticket_tax_cat_stage as $form_cat_stage) { echo '<option value="' . $form_cat_stage->slug . '">'. $form_cat_stage->name . '</option>'; } ?>
</select>
<input hidden="hidden" id="form_ticket_meta_date" name="form_ticket_meta_date" type="text" readonly="readonly" value="<?php echo get_date_from_gmt( date( 'Y-m-d H:i:s' ), 'jS \of F, Y H:i:s' ); ?>">
<input hidden="hidden" id="form_ticket_meta_user_name" name="form_ticket_meta_user_name" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_name; ?>">
<input hidden="hidden" id="form_ticket_meta_user_email" name="form_ticket_meta_user_email" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_email; ?>">
<input name="submit" type="submit" value="Submit Ticket" />
</form>
</code></pre>
<p>In the <code>script.js</code> I have:</p>
<pre><code><script>
$(function(){
$("#mb_ticket_submit").submit(function(a){
a.preventDefault();
$.ajax({
method: "POST",
url: "validation.php",
data: {
mb_ticket_subject: $("#mb_ticket_subject").val(),
mb_ticket_content: $("#mb_ticket_content").val(),
mb_ticket_tax_stage: $("#mb_ticket_tax_stage option:selected").val(),
mb_ticket_tax_application: $("#mb_ticket_tax_application option:selected").val(),
mb_ticket_meta_date: $("#mb_ticket_meta_date").val(),
mb_ticket_meta_user_name: $("#mb_ticket_meta_user_name").val(),
mb_ticket_meta_user_email: $("#mb_ticket_meta_user_email").val(),
},
success: function(a){ $("div#response").show().html(a); },
});
})
});
</script>
</code></pre>
<p>Then finally the <code>validation.php</code> has the following (the $var are cleaned up, and validated from their <code>$_POST[]</code>:</p>
<pre><code> if( empty($form_ticket_meta_user_name) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( empty($form_ticket_meta_user_email) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( !empty($form_ticket_meta_user_email) ){ if( !filter_var($form_ticket_meta_user_email, FILTER_VALIDATE_EMAIL) ) { die( 'Doesn\'t look like your email address is formatted properly. Contact your administrator.' ); } }
if( empty($form_ticket_subject) ) { die( 'No subject' ); }
if( empty($form_ticket_content) ) { die( 'No content' ); }
if( empty($form_ticket_tax_stage) ) { die( 'No stage'); }
if( empty($form_ticket_tax_application) ) { die( 'No app' ); }
if( empty($form_ticket_tax_priority) ) { die( 'No priority' ); }
if( empty($form_ticket_tax_location) ) { die( 'No location' ); }
</code></pre>
<p>Thanks :)</p>
|
[
{
"answer_id": 237958,
"author": "Manthan Dave",
"author_id": 83209,
"author_profile": "https://wordpress.stackexchange.com/users/83209",
"pm_score": -1,
"selected": false,
"text": "<p>Tried below object parametes</p>\n\n<pre><code>array(\n 'key' => 'post_code',\n 'value' =>'432C',\n 'compare' => '='\n ),\n array(\n 'relation' =>'AND',\n array(\n\n 'key' => 'location',\n 'value' => 'XYZ',\n 'compare' => '=',\n\n ),\n )\n</code></pre>\n"
},
{
"answer_id": 237959,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 4,
"selected": false,
"text": "<p>This should do it. The default relation is AND so that won't need to be specified.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'wpse_cpt',\n 'meta_query' => array(\n array(\n 'key' => 'post_code',\n 'value' => '432C',\n ),\n array(\n 'key' => 'location',\n 'value' => 'XYZ',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 237993,
"author": "Chiranjib Khanra",
"author_id": 102086,
"author_profile": "https://wordpress.stackexchange.com/users/102086",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$args = array(\n 'post_type' => 'wpse_cpt',\n 'meta_query' => array(\n 'relation' => 'AND' //**** Use AND or OR as per your required Where Clause\n array(\n 'key' => 'post_code',\n 'value' => '432C',\n ),\n array(\n 'key' => 'location',\n 'value' => 'XYZ',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 273468,
"author": "Sheraz Ahmed",
"author_id": 89206,
"author_profile": "https://wordpress.stackexchange.com/users/89206",
"pm_score": 2,
"selected": true,
"text": "<p><strong>SOLUTION</strong></p>\n\n<p>The Solution Accepted below worked, however, I wanted to know how is it working?</p>\n\n<p>This is how it's working</p>\n\n<pre><code>SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2\n WHERE p.ID = m1.post_id and p.ID = m2.post_id\n AND m1.meta_key = 'key1' AND m1.meta_value = 'value1'\n AND m2.meta_key = 'key2' AND m2.meta_value = 'value2'\n AND p.post_type = 'cpt' AND p.post_status = 'published'\n</code></pre>\n"
},
{
"answer_id": 337400,
"author": "Eric Shoberg",
"author_id": 167629,
"author_profile": "https://wordpress.stackexchange.com/users/167629",
"pm_score": 2,
"selected": false,
"text": "<p>Edit Again: Ah, I didn't answer the question. You would select <code>a.*</code> to get all columns of the posts with the matching key values, instead of selecting <code>c.meta_value</code>.</p>\n\n<p>The below sql/<code>$wpdb</code> query will select all meta_value<code>%s</code> of a post with post_type of <code>$postType</code> and a meta_key value of <code>$metaKey</code>. Therefore selecting all the different values of a given meta_key (via '$metaKey'). The <code>term_relationships</code> table is wordpress' helper table for relationship connections in tables. <code>wp_posts</code> is the wordpress 'posts' table, and, <code>wp_postmeta</code> is the wordpress 'postmeta' table. (Note: If you are using custom tables these table names would differ.) </p>\n\n<p>~ Edited to add 'doing' notes, requested by @MikeNGarrett</p>\n\n<pre><code>/* $wpdb is a global var provided by the wordpress 'engine'\n** for query'ing wordpress database tables. \n*/\nglobal $wpdb; \n$postType = 'mycustomposttype';\n$metaKey = 'mymetakey';\n$query = \"\n SELECT c.meta_value \n FROM wp_posts a \n LEFT JOIN wp_term_relationships b \n ON (a.ID = b.object_id) \n LEFT JOIN wp_postmeta c \n ON (a.ID = c.post_id) \n WHERE a.post_type = %s AND c.meta_key = %s\";\n\n$metaValues = $wpdb->prepare(query, [$postType, $metaKey]);\n$metaValues = $wpdb->get_results($metaValues);\n</code></pre>\n\n<p>Notes: I am just reusing the $metaValues variable. There is no other reason to write the results of $metaValues <code>prepare()</code> back to the $metaValues variable. You do however have to pass $metaValues to <code>get_resluts()</code>. </p>\n"
},
{
"answer_id": 395530,
"author": "breadwild",
"author_id": 153797,
"author_profile": "https://wordpress.stackexchange.com/users/153797",
"pm_score": 0,
"selected": false,
"text": "<p>I tried using the WP_Query solution suggested above, but got an empty result. The one suggested by Sheraz Ahmed works fine. Here's my own take for what it's worth:</p>\n<pre><code>//database\nwp_posts\n+---------+--------------------+--------------+\n| ID | post_title | post_type |\n+---------+--------------------+--------------+\n| 8567 | Intro to MySQL | talk |\n+---------+--------------------+--------------+\n| 8590 | Intro to PHP | talk |\n+---------+--------------------+--------------+\n\nwp_postmeta\n+---------------+------------+----------------+\n| post_id | meta_key | meta_value |\n+---------------+------------+----------------+\n| 8567 | speaker | John Doe |\n+---------------+------------+----------------+\n| 8567 | year_of | 2021 |\n+---------------+------------+----------------+\n| 8590 | speaker | John Doe |\n+---------------+------------+----------------+\n| 8590 | year_of | 2021 |\n+---------------+------------+----------------+\n\n\n//search by speaker and Year\n$speaker = "John Doe";\n$year_of = "2021";\n\n$talks = $wpdb->get_results( \n $wpdb->prepare( \n 'SELECT post_title, meta_value AS speaker \n FROM '.$wpdb->prefix.'posts AS pt, '.$wpdb->prefix.'postmeta AS pm \n WHERE post_type = %s AND pm.post_id = pt.id AND ( meta_key = %s AND meta_value = %s ) \n AND post_id IN ( SELECT post_id FROM nm_postmeta WHERE meta_key = %s AND meta_value = %s )',\n array( 'talk', \n 'speaker', \n $speaker, \n 'year_of', \n $year_of )\n )\n);\n \nforeach ( $talks as $talk ) {\n echo "<p>".$talk->speaker.': '.$talk_homily->post_title."</p>";\n}\n</code></pre>\n<p>John Doe: Intro to MySQL</p>\n<p>John Doe: Intro to PHP</p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/237986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17411/"
] |
I have three files: `submit.php` (a page), `validation.php`, `script.php`
I am trying to use the fields as a front end submission area via the `wp_insert_post()` function.
However, I don't know exactly where to put the function, as where I try either is before the `validation.php` file or if I put it in that file it causes an error since it can't pass wordpress functions.
I have tried playing with the `success` in the `$.ajax` but since the `die()` functions all result in it being successful can't trigger a create post.
Does anyone have a better solution?
In the `submit.php` I have a form:
```
<div class="" id="response"></div>
<form id="form_ticket_submit" method="post">
<label for="form_ticket_subject">Subject of issue</label>
<input id="form_ticket_subject" name="form_ticket_subject" type="text">
<label for="form_ticket_content">Post</label>
<textarea id="form_ticket_content" name="form_ticket_content"></textarea>
<label for="form_ticket_tax_stage">Select Stage</label>
<select id="form_ticket_tax_stage" name="form_ticket_tax_stage">
<option value="">Select one</option>
<?php foreach ($form_ticket_tax_cat_stage as $form_cat_stage) { echo '<option value="' . $form_cat_stage->slug . '">'. $form_cat_stage->name . '</option>'; } ?>
</select>
<input hidden="hidden" id="form_ticket_meta_date" name="form_ticket_meta_date" type="text" readonly="readonly" value="<?php echo get_date_from_gmt( date( 'Y-m-d H:i:s' ), 'jS \of F, Y H:i:s' ); ?>">
<input hidden="hidden" id="form_ticket_meta_user_name" name="form_ticket_meta_user_name" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_name; ?>">
<input hidden="hidden" id="form_ticket_meta_user_email" name="form_ticket_meta_user_email" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_email; ?>">
<input name="submit" type="submit" value="Submit Ticket" />
</form>
```
In the `script.js` I have:
```
<script>
$(function(){
$("#mb_ticket_submit").submit(function(a){
a.preventDefault();
$.ajax({
method: "POST",
url: "validation.php",
data: {
mb_ticket_subject: $("#mb_ticket_subject").val(),
mb_ticket_content: $("#mb_ticket_content").val(),
mb_ticket_tax_stage: $("#mb_ticket_tax_stage option:selected").val(),
mb_ticket_tax_application: $("#mb_ticket_tax_application option:selected").val(),
mb_ticket_meta_date: $("#mb_ticket_meta_date").val(),
mb_ticket_meta_user_name: $("#mb_ticket_meta_user_name").val(),
mb_ticket_meta_user_email: $("#mb_ticket_meta_user_email").val(),
},
success: function(a){ $("div#response").show().html(a); },
});
})
});
</script>
```
Then finally the `validation.php` has the following (the $var are cleaned up, and validated from their `$_POST[]`:
```
if( empty($form_ticket_meta_user_name) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( empty($form_ticket_meta_user_email) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( !empty($form_ticket_meta_user_email) ){ if( !filter_var($form_ticket_meta_user_email, FILTER_VALIDATE_EMAIL) ) { die( 'Doesn\'t look like your email address is formatted properly. Contact your administrator.' ); } }
if( empty($form_ticket_subject) ) { die( 'No subject' ); }
if( empty($form_ticket_content) ) { die( 'No content' ); }
if( empty($form_ticket_tax_stage) ) { die( 'No stage'); }
if( empty($form_ticket_tax_application) ) { die( 'No app' ); }
if( empty($form_ticket_tax_priority) ) { die( 'No priority' ); }
if( empty($form_ticket_tax_location) ) { die( 'No location' ); }
```
Thanks :)
|
**SOLUTION**
The Solution Accepted below worked, however, I wanted to know how is it working?
This is how it's working
```
SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2
WHERE p.ID = m1.post_id and p.ID = m2.post_id
AND m1.meta_key = 'key1' AND m1.meta_value = 'value1'
AND m2.meta_key = 'key2' AND m2.meta_value = 'value2'
AND p.post_type = 'cpt' AND p.post_status = 'published'
```
|
238,005 |
<p>I've been using an added function to load a modified rss template.
Works fine, but now I need to add a custom template for a CPT.</p>
<p>I have code for each,which works ok, but can't be used together because one over-rides the other.</p>
<p>I don't know enough php to modify.</p>
<p>Here's the code I'm using...</p>
<pre><code>remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', function() {
if ( $rss_template = locate_template( '/feeds/notes-feed.php' ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
}, 10, 1 );
</code></pre>
<p>and</p>
<pre><code>remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
</code></pre>
<p>Not knowing enough, I'm wondering if I can use this...</p>
<pre><code>remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
$rss_template_notes = get_template_directory() . '/feeds/notes-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
elseif( get_query_var( 'post' ) and file_exists( $rss_template_notes ) )
load_template( $rss_template_notes );
else
do_feed_rss2(); // Call default function
</code></pre>
|
[
{
"answer_id": 238022,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Just combine the logic for the two together. :)</p>\n\n<p>Use a single callback and depending on current context override with either one template or another.</p>\n\n<p>Another option would be to handle differences <em>inside</em> the template, not my favorite approach but some prefer it.</p>\n"
},
{
"answer_id": 238563,
"author": "gulliver",
"author_id": 63350,
"author_profile": "https://wordpress.stackexchange.com/users/63350",
"pm_score": 1,
"selected": false,
"text": "<p>Answering my own question, I’ll add this in case it’s of use to someone.</p>\n\n<p>It seems to work ok with…</p>\n\n<pre><code>// This delivers valid feeds, with the correct templates.\nremove_all_actions( 'do_feed_rss2' );\nadd_action( 'do_feed_rss2', function() {\n$rss_template = get_template_directory() . '/feeds/item-feed.php';\n$rss_template2 = get_template_directory() . '/feeds/notes-feed.php';\n//if ( $post_type = 'item' )\nif( get_query_var( 'post_type' ) == 'item' and file_exists($rss_template ) )\nload_template($rss_template);\nelseif ( $post_type = 'post' )\nload_template($rss_template2);\nelse\ndo_feed_rss2(); // Call default function\n}, 10, 1 );\n</code></pre>\n\n<p>This enables use of a custom template for the feed of normal posts, and use of a different custom template for the feed of the CPT ‘item’.</p>\n\n<p>The feeds differ in channel title/link/description.</p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/238005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] |
I've been using an added function to load a modified rss template.
Works fine, but now I need to add a custom template for a CPT.
I have code for each,which works ok, but can't be used together because one over-rides the other.
I don't know enough php to modify.
Here's the code I'm using...
```
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', function() {
if ( $rss_template = locate_template( '/feeds/notes-feed.php' ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
}, 10, 1 );
```
and
```
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
```
Not knowing enough, I'm wondering if I can use this...
```
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
$rss_template_notes = get_template_directory() . '/feeds/notes-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
elseif( get_query_var( 'post' ) and file_exists( $rss_template_notes ) )
load_template( $rss_template_notes );
else
do_feed_rss2(); // Call default function
```
|
Answering my own question, I’ll add this in case it’s of use to someone.
It seems to work ok with…
```
// This delivers valid feeds, with the correct templates.
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', function() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
$rss_template2 = get_template_directory() . '/feeds/notes-feed.php';
//if ( $post_type = 'item' )
if( get_query_var( 'post_type' ) == 'item' and file_exists($rss_template ) )
load_template($rss_template);
elseif ( $post_type = 'post' )
load_template($rss_template2);
else
do_feed_rss2(); // Call default function
}, 10, 1 );
```
This enables use of a custom template for the feed of normal posts, and use of a different custom template for the feed of the CPT ‘item’.
The feeds differ in channel title/link/description.
|
238,006 |
<p>just wondering if anyone came across this: I have a front page featuring artists in a square grid, now the client asks for a switch button to reorder the artist from A-Z (based on artist name) to the conventional newest post first - but this shall happen without reloading the page.</p>
<p>I found a solution with giving a parameter and then reload the page updating the query, but client wants this happing "on the fly" like here: <a href="http://selectiveartists.com/" rel="nofollow">http://selectiveartists.com/</a></p>
<p>Probably there is a solution to change order of posts with help of some JQuery (Plugin)?</p>
|
[
{
"answer_id": 238009,
"author": "EBennett",
"author_id": 91050,
"author_profile": "https://wordpress.stackexchange.com/users/91050",
"pm_score": 1,
"selected": false,
"text": "<p>With WordPress you can utilise a function called <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">wp_localize_script()</a> which allows you to pass in a script, and a variable you would like that script to have access too. </p>\n\n<p>Perhaps by assigning the new query to a variable, and then accessing it within jQuery would help you solve your problem. </p>\n\n<p>The example provided by WordPress explains it pretty clearly:</p>\n\n<pre><code><?php\n // Register the script\n wp_register_script( 'some_handle', 'path/to/myscript.js' );\n\n // Localize the script with new data\n $translation_array = array(\n 'some_string' => __( 'Some string to translate', 'plugin-domain' ),\n 'a_value' => '10');\n\n wp_localize_script( 'some_handle', 'object_name', $translation_array );\n\n // Enqueued script with localized data.\n wp_enqueue_script( 'some_handle' );\n?>\n</code></pre>\n\n<p>And then access like so:</p>\n\n<pre><code><script>\n // alerts 'Some string to translate'\n alert( object_name.some_string);\n</script>\n</code></pre>\n\n<p>So as you can see Javascript is now getting access to the variable translation_array variable by getting hold of the object_name which is tied to the variable $translation_array and is then pulling the value of some_string from the array.</p>\n\n<p>So we could write something along the lines of:</p>\n\n<pre><code><?php \n $args = array('order' => 'ASC');\n $get_artists = get_posts($args);\n\n wp_register_script('artists', 'path/to/artists.js');\n wp_localize_script('artists', 'artist_sort', $get_artists);\n\n wp_enqueue_script('artists');\n?>\n</code></pre>\n\n<p>And then access the variable within our artists.js script.</p>\n\n<p><em>[ No Idea if this works, as I haven't tested it, just purely an example in how you might be able to go about it ]</em></p>\n"
},
{
"answer_id": 238092,
"author": "Oliwa",
"author_id": 83211,
"author_profile": "https://wordpress.stackexchange.com/users/83211",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your answer EBennett, i just found that handy jQuery snippet which allows me to sort list item ascending and descending via the posts title. If anyone is interested, here is the code i adapted to fit my needs: \n<a href=\"http://fiddle.jshell.net/PmE2t/88/light/\" rel=\"nofollow\">http://fiddle.jshell.net/PmE2t/88/light/</a></p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/238006",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83211/"
] |
just wondering if anyone came across this: I have a front page featuring artists in a square grid, now the client asks for a switch button to reorder the artist from A-Z (based on artist name) to the conventional newest post first - but this shall happen without reloading the page.
I found a solution with giving a parameter and then reload the page updating the query, but client wants this happing "on the fly" like here: <http://selectiveartists.com/>
Probably there is a solution to change order of posts with help of some JQuery (Plugin)?
|
With WordPress you can utilise a function called [wp\_localize\_script()](https://codex.wordpress.org/Function_Reference/wp_localize_script) which allows you to pass in a script, and a variable you would like that script to have access too.
Perhaps by assigning the new query to a variable, and then accessing it within jQuery would help you solve your problem.
The example provided by WordPress explains it pretty clearly:
```
<?php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'some_string' => __( 'Some string to translate', 'plugin-domain' ),
'a_value' => '10');
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
?>
```
And then access like so:
```
<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script>
```
So as you can see Javascript is now getting access to the variable translation\_array variable by getting hold of the object\_name which is tied to the variable $translation\_array and is then pulling the value of some\_string from the array.
So we could write something along the lines of:
```
<?php
$args = array('order' => 'ASC');
$get_artists = get_posts($args);
wp_register_script('artists', 'path/to/artists.js');
wp_localize_script('artists', 'artist_sort', $get_artists);
wp_enqueue_script('artists');
?>
```
And then access the variable within our artists.js script.
*[ No Idea if this works, as I haven't tested it, just purely an example in how you might be able to go about it ]*
|
238,010 |
<p>I've added additional tabs to my product pages within my functions.php file and now need to wrap that in an if statement so the additional tabs only show on products within the category of "Models." I've tried every way of doing it that I can find, and none of them work. They all get rid of the additional tabs on every page, even if it's in the category specified.</p>
<p>I've tried everything mentioned on <a href="https://wordpress.stackexchange.com/questions/75906/how-to-check-if-the-product-is-in-a-certain-category-on-a-single-product-php-in">this question</a>, and I'm assuming none of them have worked because that person is making edits to their single-product.php file, and I'm editing my functions.php file?</p>
<pre><code>if ( is_product() && has_term( 'Models', 'product_cat' ) ) {
////Add Custom Tabs
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds a compare tab
$tabs['compare'] = array(
'title' => __( 'Compare', 'woocommerce' ),
'id' => 'compare',
'priority' => 50,
'callback' => 'woo_compare_tab_content'
);
// Adds a warranty tab
$tabs['warranty'] = array(
'title' => __( 'Warranty', 'woocommerce' ),
'id' => 'warranty',
'priority' => 50,
'callback' => 'woo_warranty_tab_content'
);
return $tabs;
}
function woo_warranty_tab_content() {
$warranty = get_post_meta( get_the_ID(), 'wpcf-warranty', true );
// Warranty Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Warranty</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$warranty";
}
function woo_compare_tab_content() {
$compare = get_post_meta( get_the_ID(), 'wpcf-compare', true );
// Comparison Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Compare</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$compare";
}
}
</code></pre>
|
[
{
"answer_id": 238009,
"author": "EBennett",
"author_id": 91050,
"author_profile": "https://wordpress.stackexchange.com/users/91050",
"pm_score": 1,
"selected": false,
"text": "<p>With WordPress you can utilise a function called <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">wp_localize_script()</a> which allows you to pass in a script, and a variable you would like that script to have access too. </p>\n\n<p>Perhaps by assigning the new query to a variable, and then accessing it within jQuery would help you solve your problem. </p>\n\n<p>The example provided by WordPress explains it pretty clearly:</p>\n\n<pre><code><?php\n // Register the script\n wp_register_script( 'some_handle', 'path/to/myscript.js' );\n\n // Localize the script with new data\n $translation_array = array(\n 'some_string' => __( 'Some string to translate', 'plugin-domain' ),\n 'a_value' => '10');\n\n wp_localize_script( 'some_handle', 'object_name', $translation_array );\n\n // Enqueued script with localized data.\n wp_enqueue_script( 'some_handle' );\n?>\n</code></pre>\n\n<p>And then access like so:</p>\n\n<pre><code><script>\n // alerts 'Some string to translate'\n alert( object_name.some_string);\n</script>\n</code></pre>\n\n<p>So as you can see Javascript is now getting access to the variable translation_array variable by getting hold of the object_name which is tied to the variable $translation_array and is then pulling the value of some_string from the array.</p>\n\n<p>So we could write something along the lines of:</p>\n\n<pre><code><?php \n $args = array('order' => 'ASC');\n $get_artists = get_posts($args);\n\n wp_register_script('artists', 'path/to/artists.js');\n wp_localize_script('artists', 'artist_sort', $get_artists);\n\n wp_enqueue_script('artists');\n?>\n</code></pre>\n\n<p>And then access the variable within our artists.js script.</p>\n\n<p><em>[ No Idea if this works, as I haven't tested it, just purely an example in how you might be able to go about it ]</em></p>\n"
},
{
"answer_id": 238092,
"author": "Oliwa",
"author_id": 83211,
"author_profile": "https://wordpress.stackexchange.com/users/83211",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your answer EBennett, i just found that handy jQuery snippet which allows me to sort list item ascending and descending via the posts title. If anyone is interested, here is the code i adapted to fit my needs: \n<a href=\"http://fiddle.jshell.net/PmE2t/88/light/\" rel=\"nofollow\">http://fiddle.jshell.net/PmE2t/88/light/</a></p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/238010",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85805/"
] |
I've added additional tabs to my product pages within my functions.php file and now need to wrap that in an if statement so the additional tabs only show on products within the category of "Models." I've tried every way of doing it that I can find, and none of them work. They all get rid of the additional tabs on every page, even if it's in the category specified.
I've tried everything mentioned on [this question](https://wordpress.stackexchange.com/questions/75906/how-to-check-if-the-product-is-in-a-certain-category-on-a-single-product-php-in), and I'm assuming none of them have worked because that person is making edits to their single-product.php file, and I'm editing my functions.php file?
```
if ( is_product() && has_term( 'Models', 'product_cat' ) ) {
////Add Custom Tabs
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds a compare tab
$tabs['compare'] = array(
'title' => __( 'Compare', 'woocommerce' ),
'id' => 'compare',
'priority' => 50,
'callback' => 'woo_compare_tab_content'
);
// Adds a warranty tab
$tabs['warranty'] = array(
'title' => __( 'Warranty', 'woocommerce' ),
'id' => 'warranty',
'priority' => 50,
'callback' => 'woo_warranty_tab_content'
);
return $tabs;
}
function woo_warranty_tab_content() {
$warranty = get_post_meta( get_the_ID(), 'wpcf-warranty', true );
// Warranty Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Warranty</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$warranty";
}
function woo_compare_tab_content() {
$compare = get_post_meta( get_the_ID(), 'wpcf-compare', true );
// Comparison Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Compare</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$compare";
}
}
```
|
With WordPress you can utilise a function called [wp\_localize\_script()](https://codex.wordpress.org/Function_Reference/wp_localize_script) which allows you to pass in a script, and a variable you would like that script to have access too.
Perhaps by assigning the new query to a variable, and then accessing it within jQuery would help you solve your problem.
The example provided by WordPress explains it pretty clearly:
```
<?php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'some_string' => __( 'Some string to translate', 'plugin-domain' ),
'a_value' => '10');
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
?>
```
And then access like so:
```
<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script>
```
So as you can see Javascript is now getting access to the variable translation\_array variable by getting hold of the object\_name which is tied to the variable $translation\_array and is then pulling the value of some\_string from the array.
So we could write something along the lines of:
```
<?php
$args = array('order' => 'ASC');
$get_artists = get_posts($args);
wp_register_script('artists', 'path/to/artists.js');
wp_localize_script('artists', 'artist_sort', $get_artists);
wp_enqueue_script('artists');
?>
```
And then access the variable within our artists.js script.
*[ No Idea if this works, as I haven't tested it, just purely an example in how you might be able to go about it ]*
|
238,011 |
<p>I had been assuming that <code>ID</code> in <code>wp_posts</code> is the primary key and that <code>post_id</code> in <code>wp_postmeta</code> is the foreign key but there is no relationship between them.</p>
<p>How does these two tables relate each other? There is a <code>meta_key</code> and <code>meta_value</code> column where <code>meta_key</code> data are <code>_sku</code>, <code>_price</code>, and <code>_stock</code>. How can I use the <code>SELECT</code> or <code>UPDATE</code> query on <code>_sku</code>, <code>_price</code>, <code>_stock</code> if they are all in the same column?</p>
|
[
{
"answer_id": 238020,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>post_id</code> column in the <code>wp_postmeta</code> table <em>is</em> a reference to the <code>ID</code> column in the <code>wp_posts</code> table.</p>\n\n<p>I'd suggest using the native <a href=\"https://codex.wordpress.org/Function_Reference/update_post_meta\" rel=\"nofollow\">update_post_meta()</a> function in WordPress to update the meta data.</p>\n\n<p>E.g. (Post ID is 123 in this example, and we're updating the price to 100.00):</p>\n\n<pre><code>update_post_meta(123, '_price', '100.00');\n</code></pre>\n\n<p>Here is the SQL equivalent:</p>\n\n<pre><code>UPDATE wp_postmeta\nSET meta_value = 100.00\nWHERE meta_key like '_price' AND post_id = 123;\n</code></pre>\n"
},
{
"answer_id": 407827,
"author": "Camillo Borges",
"author_id": 224202,
"author_profile": "https://wordpress.stackexchange.com/users/224202",
"pm_score": 0,
"selected": false,
"text": "<p>Me ajudou muiiitooo\nfiz assim com um exemplo :</p>\n<pre><code><?php\n</code></pre>\n<p>include 'confi.php';</p>\n<p>$post_id = $_POST["post_id"];\n$amount_affiliate = $_POST["amount_affiliate"];</p>\n<p>// Create connection\n$conn = new mysqli($servername, $username, $password, $dbname);\n// Check connection\nif ($conn->connect_error) {\ndie("Connection failed: " . $conn->connect_error);\n}</p>\n<p>$sql = "UPDATE wp_postmeta SET meta_value='0.70' WHERE meta_key like 'amount_affiliate' AND post_id='$post_id'";</p>\n<p>if ($conn->query($sql) === TRUE) {\necho "Pedido Com Sucesso";\n} else {\necho "Error updating record: " . $conn->error;\n}</p>\n<p>$conn->close();\n?></p>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/238011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102107/"
] |
I had been assuming that `ID` in `wp_posts` is the primary key and that `post_id` in `wp_postmeta` is the foreign key but there is no relationship between them.
How does these two tables relate each other? There is a `meta_key` and `meta_value` column where `meta_key` data are `_sku`, `_price`, and `_stock`. How can I use the `SELECT` or `UPDATE` query on `_sku`, `_price`, `_stock` if they are all in the same column?
|
The `post_id` column in the `wp_postmeta` table *is* a reference to the `ID` column in the `wp_posts` table.
I'd suggest using the native [update\_post\_meta()](https://codex.wordpress.org/Function_Reference/update_post_meta) function in WordPress to update the meta data.
E.g. (Post ID is 123 in this example, and we're updating the price to 100.00):
```
update_post_meta(123, '_price', '100.00');
```
Here is the SQL equivalent:
```
UPDATE wp_postmeta
SET meta_value = 100.00
WHERE meta_key like '_price' AND post_id = 123;
```
|
238,038 |
<p>I have recently add this function found in <a href="https://wordpress.stackexchange.com/questions/89767/how-to-increase-the-character-limit-for-post-name-of-200">this post</a> to increase my posts title limit of charcters from 200 to custom length, the problem now is that when I click publish, the posts are saved as drafts and I can't publish it cause I have only 2 choices </p>
<ul>
<li>Pending review</li>
<li>Draft</li>
</ul>
<p>Here is the function I have added to my functions file:</p>
<pre><code><?php
remove_filter( 'sanitize_title', 'sanitize_title_with_dashes' );
// add our custom hook
add_filter( 'sanitize_title', 'wpse8170_sanitize_title_with_dashes', 10, 3 );
function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 1000); // <--- here is the trick!
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// grave accent, acute accent, macron, caron
'%cc%80', '%cc%81', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
} ?>
</code></pre>
|
[
{
"answer_id": 238042,
"author": "iyrin",
"author_id": 33393,
"author_profile": "https://wordpress.stackexchange.com/users/33393",
"pm_score": 1,
"selected": false,
"text": "<p>You simply need to copy the current function <code>sanitize_title_with_dashes</code> from <a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/formatting.php#L1948\" rel=\"nofollow\">https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/formatting.php#L1948</a> and change the following line: </p>\n\n<pre><code>$title = utf8_uri_encode($title, 200);\n</code></pre>\n\n<p>To this: </p>\n\n<pre><code>$title = utf8_uri_encode($title, 1000);\n</code></pre>\n\n<p><strong>Minor edit: Always refer to the source for the same version of WordPress you have installed. In most cases, it should be the current version.</strong></p>\n\n<p>The script you are using does not match the current function from formatting.php (<a href=\"https://www.diffchecker.com/3Jo4HfsD\" rel=\"nofollow\">compare differences here</a>). Particularly, the following two lines appear after the <code>if ( 'save' == $context )</code> condition is triggered in the original function: </p>\n\n<pre><code>$title = preg_replace('/&.+?;/', '', $title); // kill entities\n$title = str_replace('.', '-', $title);\n</code></pre>\n\n<hr>\n\n<h2>Example</h2>\n\n<p>Below is the same function as <code>sanitize_title_with_dashes</code> renamed as your new function <code>wpse8170_sanitize_title_with_dashes</code>. Only the value in <code>utf8_uri_encode()</code> has been changed: </p>\n\n<pre><code>function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {\n $title = strip_tags($title);\n // Preserve escaped octets.\n $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);\n // Remove percent signs that are not part of an octet.\n $title = str_replace('%', '', $title);\n // Restore octets.\n $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);\n if (seems_utf8($title)) {\n if (function_exists('mb_strtolower')) {\n $title = mb_strtolower($title, 'UTF-8');\n }\n $title = utf8_uri_encode($title, 1000);\n }\n $title = strtolower($title);\n if ( 'save' == $context ) {\n // Convert nbsp, ndash and mdash to hyphens\n $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );\n // Convert nbsp, ndash and mdash HTML entities to hyphens\n $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', $title );\n // Strip these characters entirely\n $title = str_replace( array(\n // iexcl and iquest\n '%c2%a1', '%c2%bf',\n // angle quotes\n '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',\n // curly quotes\n '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',\n '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',\n // copy, reg, deg, hellip and trade\n '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',\n // acute accents\n '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',\n // grave accent, macron, caron\n '%cc%80', '%cc%84', '%cc%8c',\n ), '', $title );\n // Convert times to x\n $title = str_replace( '%c3%97', 'x', $title );\n }\n $title = preg_replace('/&.+?;/', '', $title); // kill entities\n $title = str_replace('.', '-', $title);\n $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);\n $title = preg_replace('/\\s+/', '-', $title);\n $title = preg_replace('|-+|', '-', $title);\n $title = trim($title, '-');\n return $title;\n}\n</code></pre>\n"
},
{
"answer_id": 238046,
"author": "Messi Adrinho",
"author_id": 98757,
"author_profile": "https://wordpress.stackexchange.com/users/98757",
"pm_score": 0,
"selected": false,
"text": "<p>i have fix it, the problem was that post_name column in posts table set at varchar(200) so i have change that to LONGTEXT cause the permalink always gets post_name from there when its set to postname, i have just add this to my functions file and then deactivate then activate my them</p>\n\n<pre><code>function change_tab_length() {\n global $wpdb;\n $table_name = $wpdb->prefix. \"posts\";\n global $charset_collate;\n $charset_collate = $wpdb->get_charset_collate();\n global $db_version;\n\n $wpdb->get_var(\"alter table \".$table_name.\" change post_name post_name LONGTEXT CHARACTER SET utf8\");\n}\nadd_action( 'init', 'change_tab_length');\n</code></pre>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/238038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98757/"
] |
I have recently add this function found in [this post](https://wordpress.stackexchange.com/questions/89767/how-to-increase-the-character-limit-for-post-name-of-200) to increase my posts title limit of charcters from 200 to custom length, the problem now is that when I click publish, the posts are saved as drafts and I can't publish it cause I have only 2 choices
* Pending review
* Draft
Here is the function I have added to my functions file:
```
<?php
remove_filter( 'sanitize_title', 'sanitize_title_with_dashes' );
// add our custom hook
add_filter( 'sanitize_title', 'wpse8170_sanitize_title_with_dashes', 10, 3 );
function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 1000); // <--- here is the trick!
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// grave accent, acute accent, macron, caron
'%cc%80', '%cc%81', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
} ?>
```
|
You simply need to copy the current function `sanitize_title_with_dashes` from <https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/formatting.php#L1948> and change the following line:
```
$title = utf8_uri_encode($title, 200);
```
To this:
```
$title = utf8_uri_encode($title, 1000);
```
**Minor edit: Always refer to the source for the same version of WordPress you have installed. In most cases, it should be the current version.**
The script you are using does not match the current function from formatting.php ([compare differences here](https://www.diffchecker.com/3Jo4HfsD)). Particularly, the following two lines appear after the `if ( 'save' == $context )` condition is triggered in the original function:
```
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
```
---
Example
-------
Below is the same function as `sanitize_title_with_dashes` renamed as your new function `wpse8170_sanitize_title_with_dashes`. Only the value in `utf8_uri_encode()` has been changed:
```
function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 1000);
}
$title = strtolower($title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Convert nbsp, ndash and mdash HTML entities to hyphens
$title = str_replace( array( ' ', ' ', '–', '–', '—', '—' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// acute accents
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
// grave accent, macron, caron
'%cc%80', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
```
|
238,039 |
<p>I'm wondering how to change the admin theme based on a user's role. Currently I can change the admin theme using a plugin (ex: <a href="https://wordpress.org/plugins/blue-admin/" rel="nofollow">Blue Admin</a>) - but I'm not sure how to make those changes based on a role (subscriber etc).</p>
<p>Would also like to have specific menu items / etc shown only for certain roles.</p>
<p>I have no problem diving into <code>functions.php</code> or anything else that may be needed to accomplish this - just hoping to be pointed in the right direction first.</p>
|
[
{
"answer_id": 238041,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>The admin color scheme is stored in <code>user_meta</code> as <code>admin_color</code> (default is '<em>fresh</em>').</p>\n\n<p>You could write a callback that fires on <code>user_registration</code> that would set it depending on role.</p>\n\n<pre><code>add_action( 'user_register', 'wpse_registration_save', 10, 1 );\n\nfunction wpse_registration_save( $user_id ) {\n # ...get the user role\n # ...write switch statement based on role\n # ... update_user_meta($user_id, 'admin_color', 'funky');\n\n}\n</code></pre>\n\n<p>I'm not sure how this plays with Blue Admin, but this would be the way to do it without using any plugins. If it's smart, Blue Admin would store its theme info in <code>user_meta</code>, too, so it might be a very similar approach either way.</p>\n"
},
{
"answer_id": 238120,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 2,
"selected": false,
"text": "<p>You can <s>set</s> force a specific Admin Color Scheme pro user role through a function.<br />\n<em>Personally I would first take away the option to select the scheme from profile.php (Back-end Users/Your Profile)</em><br /></p>\n\n<p>Below is just an example function which does set a specific color scheme for specific user roles.<br />\n<em>Please make first make a backup of the functions.php before adding this function.</em></p>\n\n<pre><code>/**\n * Set Admin Color Scheme by Role\n * Codex: {@link https://codex.wordpress.org/Roles_and_Capabilities}\n * {@link https://codex.wordpress.org/Function_Reference/wp_get_current_user}\n * @version WordPress 4.6 \n */\nadd_filter( 'get_user_option_admin_color', 'wpse_238039_set_admin_color' );\nfunction wpse_238039_set_admin_color()\n{\n $current_user = wp_get_current_user();\n\n // Check for the user role\n if ( user_can( $current_user, 'subscriber' ) )\n {\n // Remove the Admin Color Scheme picker\n remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );\n\n // Set the Admin Color Scheme you want for this role\n return 'light';\n }\n\n if ( user_can( $current_user, 'contributor' ) )\n {\n remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );\n return 'coffee';\n }\n\n} // end function\n</code></pre>\n\n<p>It is of course possible to leave the Admin Color Scheme option on the user Profile Page by removing those lines from the function.</p>\n\n<blockquote>\n <p>Would also like to have specific menu items / etc shown only for\n certain roles.</p>\n</blockquote>\n\n<p>It is possible to add/remove items within another function with the same kind of IF statement blocks. Just be aware of what you do/want in a specific function, and use the correct <a href=\"https://developer.wordpress.org/reference/hooks/\" rel=\"nofollow\">hooks</a><br /></p>\n\n<blockquote>\n <p><strong>Note:</strong> see the @link urls in the function above for references.</p>\n</blockquote>\n"
}
] |
2016/09/02
|
[
"https://wordpress.stackexchange.com/questions/238039",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41269/"
] |
I'm wondering how to change the admin theme based on a user's role. Currently I can change the admin theme using a plugin (ex: [Blue Admin](https://wordpress.org/plugins/blue-admin/)) - but I'm not sure how to make those changes based on a role (subscriber etc).
Would also like to have specific menu items / etc shown only for certain roles.
I have no problem diving into `functions.php` or anything else that may be needed to accomplish this - just hoping to be pointed in the right direction first.
|
You can ~~set~~ force a specific Admin Color Scheme pro user role through a function.
*Personally I would first take away the option to select the scheme from profile.php (Back-end Users/Your Profile)*
Below is just an example function which does set a specific color scheme for specific user roles.
*Please make first make a backup of the functions.php before adding this function.*
```
/**
* Set Admin Color Scheme by Role
* Codex: {@link https://codex.wordpress.org/Roles_and_Capabilities}
* {@link https://codex.wordpress.org/Function_Reference/wp_get_current_user}
* @version WordPress 4.6
*/
add_filter( 'get_user_option_admin_color', 'wpse_238039_set_admin_color' );
function wpse_238039_set_admin_color()
{
$current_user = wp_get_current_user();
// Check for the user role
if ( user_can( $current_user, 'subscriber' ) )
{
// Remove the Admin Color Scheme picker
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
// Set the Admin Color Scheme you want for this role
return 'light';
}
if ( user_can( $current_user, 'contributor' ) )
{
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
return 'coffee';
}
} // end function
```
It is of course possible to leave the Admin Color Scheme option on the user Profile Page by removing those lines from the function.
>
> Would also like to have specific menu items / etc shown only for
> certain roles.
>
>
>
It is possible to add/remove items within another function with the same kind of IF statement blocks. Just be aware of what you do/want in a specific function, and use the correct [hooks](https://developer.wordpress.org/reference/hooks/)
>
> **Note:** see the @link urls in the function above for references.
>
>
>
|
238,057 |
<pre><code>function dwwp_admin_enqueue_scripts_mlm() {
wp_enqueue_style( 'dwwp-admin-css', plugins_url( 'css/admin-users.css', __FILE__ ) );
wp_enqueue_script( 'admin-users', plugins_url( 'js/admin-users.js', __FILE__ ) );
wp_enqueue_script( 'jquery', 'http://code.jquery.com/jquery-1.10.2.js' );
wp_enqueue_script( 'jquery-ui', 'http://code.jquery.com/ui/1.10.4/jquery-ui.js' );
wp_enqueue_style( 'jquery-style', 'http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css' );}
add_action( 'admin_enqueue_scripts', 'dwwp_admin_enqueue_scripts_mlm' );
</code></pre>
|
[
{
"answer_id": 238068,
"author": "theodorhanu",
"author_id": 36255,
"author_profile": "https://wordpress.stackexchange.com/users/36255",
"pm_score": 1,
"selected": true,
"text": "<p>No. As wordpress codex states, you should use jquery and other javascript files provided by them. As for css files I think you can use yours.</p>\n\n<p>Please check <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow\">this link</a>( scroll down) for a list of already defined javascript files.</p>\n\n<p>Also, you have to use local files as much as possible, unless you have no other way. So for example, if you have a js library, you should download it and include it in your theme/plugin files and not enqueue it using CDN or any other external link. Wordpress team will refuse to publish your theme/plugin if you include external js files without a good reason.</p>\n\n<p>LE: for jquery-ui you only have to use this </p>\n\n<pre><code> wp_enqueue_script( 'jquery-ui')\n</code></pre>\n\n<p>or add it as a dependency of your own script like this</p>\n\n<pre><code>wp_enqueue_script('my-script', 'url-to-scrip', array('jquery-ui'))\n</code></pre>\n"
},
{
"answer_id": 238070,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Do not try to overwrite the libraries (jQuery, jQuery UI) that are already provided by WordPress. This will either fail or result in conflicts with other plugins.</li>\n<li><a href=\"https://wordpress.stackexchange.com/a/143164/73\"><strong>Register</strong> your assets early</a>, <strong>enqueue</strong> them by their handle only.</li>\n<li>Use the <strong>dependency</strong> parameter to make sure assets are loaded in the order you need.</li>\n</ol>\n\n<p>So, you should do something like this:</p>\n\n<pre><code>if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) )\n{\n add_action(\n 'wp_loaded',\n function() {\n wp_register_script(\n 'admin-users',\n plugins_url( 'js/admin-users.js', __FILE__ ),\n [ 'jquery-ui-core' ] // Let WP handle the rest.\n );\n wp_register_style(\n 'jquery-style',\n 'http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css'\n );\n wp_register_style(\n 'dwwp-admin-css',\n plugins_url( 'css/admin-users.css', __FILE__ ),\n [ 'jquery-style' ]\n );\n }\n );\n add_action( \n 'admin_enqueue_scripts', \n function() {\n wp_enqueue_script( 'admin-users' );\n // jquery-style will be loaded automatically.\n wp_enqueue_style( 'dwwp-admin-css' );\n }\n );\n}\n</code></pre>\n"
}
] |
2016/09/03
|
[
"https://wordpress.stackexchange.com/questions/238057",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101387/"
] |
```
function dwwp_admin_enqueue_scripts_mlm() {
wp_enqueue_style( 'dwwp-admin-css', plugins_url( 'css/admin-users.css', __FILE__ ) );
wp_enqueue_script( 'admin-users', plugins_url( 'js/admin-users.js', __FILE__ ) );
wp_enqueue_script( 'jquery', 'http://code.jquery.com/jquery-1.10.2.js' );
wp_enqueue_script( 'jquery-ui', 'http://code.jquery.com/ui/1.10.4/jquery-ui.js' );
wp_enqueue_style( 'jquery-style', 'http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css' );}
add_action( 'admin_enqueue_scripts', 'dwwp_admin_enqueue_scripts_mlm' );
```
|
No. As wordpress codex states, you should use jquery and other javascript files provided by them. As for css files I think you can use yours.
Please check [this link](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)( scroll down) for a list of already defined javascript files.
Also, you have to use local files as much as possible, unless you have no other way. So for example, if you have a js library, you should download it and include it in your theme/plugin files and not enqueue it using CDN or any other external link. Wordpress team will refuse to publish your theme/plugin if you include external js files without a good reason.
LE: for jquery-ui you only have to use this
```
wp_enqueue_script( 'jquery-ui')
```
or add it as a dependency of your own script like this
```
wp_enqueue_script('my-script', 'url-to-scrip', array('jquery-ui'))
```
|
238,107 |
<p>I am using WordPress Media Library in my plugin in the backend. How to change the upload path for it dynamically? Can it be done during the enqueue, or when creating it in JavaScript?</p>
<p>I am using <code>wp_enqueue_media()</code> in <code>admin_enqueue_scripts</code> action, and later creating the media frame in Javascript using <code>wp.media</code>.</p>
<p>I've managed to change the directory when uploading using <code>plupload_default_params</code> filter, but I don't know how to hook into the <code>query-attachments</code> action that queries the files into the library.</p>
<p><strong>Update:</strong> After hours of tinkering I gave up and I went with a different solution. I am adding a new setting on plugin's edit page and resetting it otherwise. This way I can access the option in ajax calls.</p>
<pre><code>function change_upload_dir( $args ) {
$user_id = get_current_user_id();
$form = false;
if( defined('DOING_AJAX') && DOING_AJAX ) {
$form = get_option( 'test_edit_' . $user_id );
}
if($form || isset($_GET['type']) || isset($_POST['subfolder'])) {
// change upload path
</code></pre>
<p>And in the plugin construct: </p>
<pre><code> if( !(defined('DOING_AJAX') && DOING_AJAX)
&& false === strpos($_SERVER['REQUEST_URI'], 'wp-content') ) {
$edit = get_option( 'test_edit_' . get_current_user_id() );
if ( $edit && $edit != '' ) {
update_option( 'test_edit_' . get_current_user_id(), '' );
}
}
</code></pre>
<p>This works fine, unless the user opens a new tab and the setting gets reset.
It's fine for now, but I'd really like to know if there is an easier way to do that.</p>
|
[
{
"answer_id": 238979,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>Might wanna look at</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_upload_dir/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_upload_dir/</a></p>\n\n<p>In definition there is a hook <code>upload_dir</code>, you can use that to change <code>path</code>.</p>\n\n<p>Haven't tried or tested it, but you can give it a try.</p>\n"
},
{
"answer_id": 239486,
"author": "Mark Wilson",
"author_id": 102532,
"author_profile": "https://wordpress.stackexchange.com/users/102532",
"pm_score": 0,
"selected": false,
"text": "<p>In order to change the default media upload location, you need to edit the wp-config.php file located in the root directory of your WordPress installation. If you want upload directory to be wp-content/files then you will need to place the following code in <code>wp-config.php</code></p>\n\n<pre><code>define( 'UPLOADS', 'wp-content/'.'files' );\n</code></pre>\n\n<p>If you want the upload directory to be outside wp-content, like <code>http://www.example.com/files/</code> then you need to set upload path in <code>wp-config.php</code> like this:</p>\n\n<pre><code>define( 'UPLOADS', ''.'files' );\n</code></pre>\n\n<p>Remember you can still choose whether or not you want uploaded files to be organized in month/year folders in <strong>Settings » Media</strong>.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_upload_dir/\" rel=\"nofollow\">Function Reference /wp_upload_dir – WordPress Codex</a></p>\n"
}
] |
2016/09/03
|
[
"https://wordpress.stackexchange.com/questions/238107",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75841/"
] |
I am using WordPress Media Library in my plugin in the backend. How to change the upload path for it dynamically? Can it be done during the enqueue, or when creating it in JavaScript?
I am using `wp_enqueue_media()` in `admin_enqueue_scripts` action, and later creating the media frame in Javascript using `wp.media`.
I've managed to change the directory when uploading using `plupload_default_params` filter, but I don't know how to hook into the `query-attachments` action that queries the files into the library.
**Update:** After hours of tinkering I gave up and I went with a different solution. I am adding a new setting on plugin's edit page and resetting it otherwise. This way I can access the option in ajax calls.
```
function change_upload_dir( $args ) {
$user_id = get_current_user_id();
$form = false;
if( defined('DOING_AJAX') && DOING_AJAX ) {
$form = get_option( 'test_edit_' . $user_id );
}
if($form || isset($_GET['type']) || isset($_POST['subfolder'])) {
// change upload path
```
And in the plugin construct:
```
if( !(defined('DOING_AJAX') && DOING_AJAX)
&& false === strpos($_SERVER['REQUEST_URI'], 'wp-content') ) {
$edit = get_option( 'test_edit_' . get_current_user_id() );
if ( $edit && $edit != '' ) {
update_option( 'test_edit_' . get_current_user_id(), '' );
}
}
```
This works fine, unless the user opens a new tab and the setting gets reset.
It's fine for now, but I'd really like to know if there is an easier way to do that.
|
Might wanna look at
<https://developer.wordpress.org/reference/functions/wp_upload_dir/>
In definition there is a hook `upload_dir`, you can use that to change `path`.
Haven't tried or tested it, but you can give it a try.
|
238,129 |
<p>I am trying to access post meta for custom post type and taxonomy using WP_Query and then query the posts with that specific post meta.
<br />
So far I have tied the following code:</p>
<pre><code>$hot_args = array(
'post_type' => 'video',
'posts_per_page' => '6',
"order" => "DESC",
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '1 week ago'
)
),
"post__not_in" => $posts__not_in,
'tax_query' => array(
array(
'taxonomy' => 'video_cat',
'field' => 'slug',
'terms' => "all"
)
),
);
$hot_query = new WP_Query( $hot_args );
</code></pre>
<p>This code doesn't work and not returning any results.<br /><br />
For normal posts this piece of code works but for custom post type doesn't, How can I make it work for custom post types?</p>
|
[
{
"answer_id": 238115,
"author": "rayrutjes",
"author_id": 99248,
"author_profile": "https://wordpress.stackexchange.com/users/99248",
"pm_score": 2,
"selected": false,
"text": "<p>Moving a WordPress website is fairly easy, here are the steps:</p>\n\n<ul>\n<li>Backup your mysql database and re-import it in the new environment,</li>\n<li>Move all the files to the new environment,</li>\n<li>Update the <code>wp-config.php</code> file to reflect the new database connection information,</li>\n<li>(*)Replace all occurrences of your domain name with the new one if it has changed</li>\n</ul>\n\n<p>(*) This is the step that is confusing most of the time. People sometimes think it is enough to simply replace the few options in the database where the domain name appears but that is unfortunately not enough. </p>\n\n<p>Indeed WordPress uses the PHP serialize/unserialize functions to store arrays in the the database. The problem here is that if you simply replace the domain name contained in a serialized object, you corrupt the data and will be unable to deserialize it because PHP serialization will add the length of every variable as part of the data. So unless you actually replace your domain name with another of the same size, you can not simply do a database search and replace.</p>\n\n<p><strong>Fortunately there are 2 easy solutions:</strong></p>\n\n<ol>\n<li>This script: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a>\nYou simply deploy the folder in the root of your install and access it over http. <strong>Do not forget to delete the folder once you are finished</strong></li>\n<li>This CLI: <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">http://wp-cli.org/commands/search-replace/</a>\nSolution that I personally prefer because it does far more than just search & replace and can help you keeping a healthy WordPress instance.</li>\n</ol>\n"
},
{
"answer_id": 238116,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 1,
"selected": false,
"text": "<p>Here are my notes that I use whenever moving a WP site from dev to test or to production:</p>\n\n<p><strong>At the current host/domain:</strong></p>\n\n<ol>\n<li><p>Either gzip then download, or just download all the web folder content to your local computer.</p></li>\n<li><p>From SSH (e.g. Putty) session: Dump the database.</p>\n\n<p>$mysqldump -u username -p wp_databasename > mydump.sql</p>\n\n<p>(Alternatively, use phpmyadmin ‘export’ facility)</p></li>\n<li><p>Download the database dump to your local computer.</p></li>\n</ol>\n\n<p><strong>At the new host/domain:</strong></p>\n\n<ol start=\"4\">\n<li><p>Create new database using SSH $mysql commands, or CPanel.</p></li>\n<li><p>Upload the database dump from step 2.</p></li>\n<li><p>From SSH session: Import the database dump into the new database.</p>\n\n<p>$mysql -u username -p wp_databasename < mydump.sql</p>\n\n<p>(Alternatively, use phpmyadmin ‘import’ facility)</p></li>\n<li><p>Upload the PHP utility “database search and replace” from <code>interconnectit.com</code>.</p>\n\n<p>(Note: this utility handles serialized data correctly)<br>\n(Note: when uploading assure file permissions 644 folder 755)</p></li>\n<li><p>Run the search/replace utility and replace the prior site URL with the new URL.</p></li>\n<li><p>Upload the web folder content from step 1. Assure file permissions 644 and folder permissions 755.</p></li>\n<li><p>Update <code>wp-config.php</code> as needed (e.g. DB connection settings are probably different). Check <code>.htaccess</code> in case any localized items there to deal with, as well.</p></li>\n<li><p>Delete the “database search and replace” utility.</p></li>\n</ol>\n"
},
{
"answer_id": 238118,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>When I'm ready to migrate from my <code>localhost</code> to a live server and new domain, these are the steps that I take:</p>\n\n<p><strong>Preparing for <a href=\"/questions/tagged/migration\" class=\"post-tag\" title=\"show questions tagged 'migration'\" rel=\"tag\">migration</a></strong></p>\n\n<ol>\n<li>Based on your profile, I going to assume that you know how to export your database on <code>phpMyAdmin</code> to prepare for migration\n\n<ul>\n<li><em>If not</em>, <a href=\"https://wpengine.com/support/exporting-database/\" rel=\"nofollow noreferrer\">here's a nice guide to follow</a></li>\n</ul></li>\n<li>While some people grab their entire WordPress directory, I prefer just the <code>/wp-content/</code> folder and you'll see why in the next few steps</li>\n<li>Have a fresh install of WordPress set up on your live server\n\n<ul>\n<li>Nowadays, most hosting providers offer a one-click-install of the latest version of WordPress for you, saving you time with setting it up</li>\n</ul></li>\n<li>Get access to your new database and host</li>\n</ol>\n\n<p><strong>Migrating to new server</strong></p>\n\n<ol>\n<li>With your fresh install of WordPress created on your new host, connect to it via FTP with a program such as <a href=\"https://filezilla-project.org/\" rel=\"nofollow noreferrer\">FileZilla</a></li>\n<li>Delete the <code>wp-content</code> folder and drop in your <code>localhost</code> copy of the <code>wp-content</code> instead\n\n<ul>\n<li>Depending on how big your folder is, it may take a few minutes to transfer it all</li>\n</ul></li>\n<li>Go to your new database (via <code>phpMyAdmin</code>) and drop all of the tables that were initially created by the fresh install of WordPress and import your local copy instead</li>\n</ol>\n\n<p><strong>Updating to your new domain</strong></p>\n\n<p>While the migration is complete in terms of all of your files and data, this doesn't mane that it will be functional, because all of the links will be pointing to your <code>localhost</code>. Changing the <code>home</code> and <code>siteurl</code> values in your <code>wp_options</code> table (in your database) is not enough unfortunately.</p>\n\n<p>You will still have your post and page content with your <code>localhost</code> URL (<code>http://localhost/wordpress</code>) causing your website to not display properly.</p>\n\n<p>Once you've downloaded and imported your database to your localhost. Follow these steps:</p>\n\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search & Replace Script here</a></li>\n<li>Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://example.com/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>It should be pretty self-explanatory up to this point: enter your <code>localhost</code> URL in the <strong><code>search for…</code></strong> field and the new URL in the <strong><code>replace with…</code></strong> field</li>\n</ol>\n\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder. Check your website to make sure nothing else is out of place and you should be good to go.</p>\n"
},
{
"answer_id": 238244,
"author": "Adrian Lambertz",
"author_id": 102229,
"author_profile": "https://wordpress.stackexchange.com/users/102229",
"pm_score": -1,
"selected": false,
"text": "<p>I always use the popular plugin \"Duplicator\" (<a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">in WP Plugin Directory</a>).</p>\n\n<p>Never had any problems with it. Install, create an archive. You'll receive a .ZIP file with all of your contents and a installer.php file. Upload both to your server and access the installer.php. Follow the install wizard and have fun. Works like a charm and it is really user-friendly.</p>\n\n<p>The installer script takes care of all data, putting it in your ne empty database, changing the the URL in the database, changing the wp-config.php file etc...</p>\n\n<p>After the migration, log into your wordpress and save your permalinks to activate the rewrite. That's it.</p>\n"
}
] |
2016/09/04
|
[
"https://wordpress.stackexchange.com/questions/238129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76334/"
] |
I am trying to access post meta for custom post type and taxonomy using WP\_Query and then query the posts with that specific post meta.
So far I have tied the following code:
```
$hot_args = array(
'post_type' => 'video',
'posts_per_page' => '6',
"order" => "DESC",
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '1 week ago'
)
),
"post__not_in" => $posts__not_in,
'tax_query' => array(
array(
'taxonomy' => 'video_cat',
'field' => 'slug',
'terms' => "all"
)
),
);
$hot_query = new WP_Query( $hot_args );
```
This code doesn't work and not returning any results.
For normal posts this piece of code works but for custom post type doesn't, How can I make it work for custom post types?
|
Moving a WordPress website is fairly easy, here are the steps:
* Backup your mysql database and re-import it in the new environment,
* Move all the files to the new environment,
* Update the `wp-config.php` file to reflect the new database connection information,
* (\*)Replace all occurrences of your domain name with the new one if it has changed
(\*) This is the step that is confusing most of the time. People sometimes think it is enough to simply replace the few options in the database where the domain name appears but that is unfortunately not enough.
Indeed WordPress uses the PHP serialize/unserialize functions to store arrays in the the database. The problem here is that if you simply replace the domain name contained in a serialized object, you corrupt the data and will be unable to deserialize it because PHP serialization will add the length of every variable as part of the data. So unless you actually replace your domain name with another of the same size, you can not simply do a database search and replace.
**Fortunately there are 2 easy solutions:**
1. This script: <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>
You simply deploy the folder in the root of your install and access it over http. **Do not forget to delete the folder once you are finished**
2. This CLI: <http://wp-cli.org/commands/search-replace/>
Solution that I personally prefer because it does far more than just search & replace and can help you keeping a healthy WordPress instance.
|
238,141 |
<p>I am Creating a Multi row , 2 Columns blog Post like this </p>
<pre><code>Post #1 | Post #4
Post #2 | Post #5
Post #3 | Post #6
</code></pre>
<p>I have found some post useful</p>
<p><a href="https://digwp.com/2010/03/wordpress-post-content-multiple-columns/" rel="nofollow noreferrer">https://digwp.com/2010/03/wordpress-post-content-multiple-columns/</a></p>
<p>Based on the post I have Created Code as follows</p>
<pre><code><?php
// Some sample styles for the images
echo "<style type='text/css'>
div#left-column {
width: 150px;
float: left;
clear: none;
}
div#right-column {
width: 150px;
float: left;
clear: none;
}
</style>\n";
?>
<div class="container">
<div class="row">
<div class="span6">
<div class="span4">
<?php if (have_posts()) :
while(have_posts()) :
$i++; ?>
<?php if(($i % 2) !== 0) :?>
<div id="left-column" class="col-xs-6">
<?php $wp_query->next_post();the_excerpt();?>
</div>
<div id="right-column" class="col-xs-6">
<?php else : the_post(); the_excerpt();?>
</div>
<?php endif; endwhile; else: ?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
</div>
</div>
</code></pre>
<p>But this Code giving me Output like </p>
<p><a href="https://i.stack.imgur.com/Lm9lY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lm9lY.png" alt="enter image description here"></a></p>
<p>Either it is posting odd or even posts , and in distorted manner ...I Tried lot of things , But not able to get alternate post in horizontal direction , Either i am getting completely vertical or hoirizontal . Can anyone suggest what I am msssing , Any suggestion will be helpful</p>
|
[
{
"answer_id": 238115,
"author": "rayrutjes",
"author_id": 99248,
"author_profile": "https://wordpress.stackexchange.com/users/99248",
"pm_score": 2,
"selected": false,
"text": "<p>Moving a WordPress website is fairly easy, here are the steps:</p>\n\n<ul>\n<li>Backup your mysql database and re-import it in the new environment,</li>\n<li>Move all the files to the new environment,</li>\n<li>Update the <code>wp-config.php</code> file to reflect the new database connection information,</li>\n<li>(*)Replace all occurrences of your domain name with the new one if it has changed</li>\n</ul>\n\n<p>(*) This is the step that is confusing most of the time. People sometimes think it is enough to simply replace the few options in the database where the domain name appears but that is unfortunately not enough. </p>\n\n<p>Indeed WordPress uses the PHP serialize/unserialize functions to store arrays in the the database. The problem here is that if you simply replace the domain name contained in a serialized object, you corrupt the data and will be unable to deserialize it because PHP serialization will add the length of every variable as part of the data. So unless you actually replace your domain name with another of the same size, you can not simply do a database search and replace.</p>\n\n<p><strong>Fortunately there are 2 easy solutions:</strong></p>\n\n<ol>\n<li>This script: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a>\nYou simply deploy the folder in the root of your install and access it over http. <strong>Do not forget to delete the folder once you are finished</strong></li>\n<li>This CLI: <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">http://wp-cli.org/commands/search-replace/</a>\nSolution that I personally prefer because it does far more than just search & replace and can help you keeping a healthy WordPress instance.</li>\n</ol>\n"
},
{
"answer_id": 238116,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 1,
"selected": false,
"text": "<p>Here are my notes that I use whenever moving a WP site from dev to test or to production:</p>\n\n<p><strong>At the current host/domain:</strong></p>\n\n<ol>\n<li><p>Either gzip then download, or just download all the web folder content to your local computer.</p></li>\n<li><p>From SSH (e.g. Putty) session: Dump the database.</p>\n\n<p>$mysqldump -u username -p wp_databasename > mydump.sql</p>\n\n<p>(Alternatively, use phpmyadmin ‘export’ facility)</p></li>\n<li><p>Download the database dump to your local computer.</p></li>\n</ol>\n\n<p><strong>At the new host/domain:</strong></p>\n\n<ol start=\"4\">\n<li><p>Create new database using SSH $mysql commands, or CPanel.</p></li>\n<li><p>Upload the database dump from step 2.</p></li>\n<li><p>From SSH session: Import the database dump into the new database.</p>\n\n<p>$mysql -u username -p wp_databasename < mydump.sql</p>\n\n<p>(Alternatively, use phpmyadmin ‘import’ facility)</p></li>\n<li><p>Upload the PHP utility “database search and replace” from <code>interconnectit.com</code>.</p>\n\n<p>(Note: this utility handles serialized data correctly)<br>\n(Note: when uploading assure file permissions 644 folder 755)</p></li>\n<li><p>Run the search/replace utility and replace the prior site URL with the new URL.</p></li>\n<li><p>Upload the web folder content from step 1. Assure file permissions 644 and folder permissions 755.</p></li>\n<li><p>Update <code>wp-config.php</code> as needed (e.g. DB connection settings are probably different). Check <code>.htaccess</code> in case any localized items there to deal with, as well.</p></li>\n<li><p>Delete the “database search and replace” utility.</p></li>\n</ol>\n"
},
{
"answer_id": 238118,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>When I'm ready to migrate from my <code>localhost</code> to a live server and new domain, these are the steps that I take:</p>\n\n<p><strong>Preparing for <a href=\"/questions/tagged/migration\" class=\"post-tag\" title=\"show questions tagged 'migration'\" rel=\"tag\">migration</a></strong></p>\n\n<ol>\n<li>Based on your profile, I going to assume that you know how to export your database on <code>phpMyAdmin</code> to prepare for migration\n\n<ul>\n<li><em>If not</em>, <a href=\"https://wpengine.com/support/exporting-database/\" rel=\"nofollow noreferrer\">here's a nice guide to follow</a></li>\n</ul></li>\n<li>While some people grab their entire WordPress directory, I prefer just the <code>/wp-content/</code> folder and you'll see why in the next few steps</li>\n<li>Have a fresh install of WordPress set up on your live server\n\n<ul>\n<li>Nowadays, most hosting providers offer a one-click-install of the latest version of WordPress for you, saving you time with setting it up</li>\n</ul></li>\n<li>Get access to your new database and host</li>\n</ol>\n\n<p><strong>Migrating to new server</strong></p>\n\n<ol>\n<li>With your fresh install of WordPress created on your new host, connect to it via FTP with a program such as <a href=\"https://filezilla-project.org/\" rel=\"nofollow noreferrer\">FileZilla</a></li>\n<li>Delete the <code>wp-content</code> folder and drop in your <code>localhost</code> copy of the <code>wp-content</code> instead\n\n<ul>\n<li>Depending on how big your folder is, it may take a few minutes to transfer it all</li>\n</ul></li>\n<li>Go to your new database (via <code>phpMyAdmin</code>) and drop all of the tables that were initially created by the fresh install of WordPress and import your local copy instead</li>\n</ol>\n\n<p><strong>Updating to your new domain</strong></p>\n\n<p>While the migration is complete in terms of all of your files and data, this doesn't mane that it will be functional, because all of the links will be pointing to your <code>localhost</code>. Changing the <code>home</code> and <code>siteurl</code> values in your <code>wp_options</code> table (in your database) is not enough unfortunately.</p>\n\n<p>You will still have your post and page content with your <code>localhost</code> URL (<code>http://localhost/wordpress</code>) causing your website to not display properly.</p>\n\n<p>Once you've downloaded and imported your database to your localhost. Follow these steps:</p>\n\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search & Replace Script here</a></li>\n<li>Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://example.com/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>It should be pretty self-explanatory up to this point: enter your <code>localhost</code> URL in the <strong><code>search for…</code></strong> field and the new URL in the <strong><code>replace with…</code></strong> field</li>\n</ol>\n\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder. Check your website to make sure nothing else is out of place and you should be good to go.</p>\n"
},
{
"answer_id": 238244,
"author": "Adrian Lambertz",
"author_id": 102229,
"author_profile": "https://wordpress.stackexchange.com/users/102229",
"pm_score": -1,
"selected": false,
"text": "<p>I always use the popular plugin \"Duplicator\" (<a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">in WP Plugin Directory</a>).</p>\n\n<p>Never had any problems with it. Install, create an archive. You'll receive a .ZIP file with all of your contents and a installer.php file. Upload both to your server and access the installer.php. Follow the install wizard and have fun. Works like a charm and it is really user-friendly.</p>\n\n<p>The installer script takes care of all data, putting it in your ne empty database, changing the the URL in the database, changing the wp-config.php file etc...</p>\n\n<p>After the migration, log into your wordpress and save your permalinks to activate the rewrite. That's it.</p>\n"
}
] |
2016/09/04
|
[
"https://wordpress.stackexchange.com/questions/238141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102175/"
] |
I am Creating a Multi row , 2 Columns blog Post like this
```
Post #1 | Post #4
Post #2 | Post #5
Post #3 | Post #6
```
I have found some post useful
<https://digwp.com/2010/03/wordpress-post-content-multiple-columns/>
Based on the post I have Created Code as follows
```
<?php
// Some sample styles for the images
echo "<style type='text/css'>
div#left-column {
width: 150px;
float: left;
clear: none;
}
div#right-column {
width: 150px;
float: left;
clear: none;
}
</style>\n";
?>
<div class="container">
<div class="row">
<div class="span6">
<div class="span4">
<?php if (have_posts()) :
while(have_posts()) :
$i++; ?>
<?php if(($i % 2) !== 0) :?>
<div id="left-column" class="col-xs-6">
<?php $wp_query->next_post();the_excerpt();?>
</div>
<div id="right-column" class="col-xs-6">
<?php else : the_post(); the_excerpt();?>
</div>
<?php endif; endwhile; else: ?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
</div>
</div>
```
But this Code giving me Output like
[](https://i.stack.imgur.com/Lm9lY.png)
Either it is posting odd or even posts , and in distorted manner ...I Tried lot of things , But not able to get alternate post in horizontal direction , Either i am getting completely vertical or hoirizontal . Can anyone suggest what I am msssing , Any suggestion will be helpful
|
Moving a WordPress website is fairly easy, here are the steps:
* Backup your mysql database and re-import it in the new environment,
* Move all the files to the new environment,
* Update the `wp-config.php` file to reflect the new database connection information,
* (\*)Replace all occurrences of your domain name with the new one if it has changed
(\*) This is the step that is confusing most of the time. People sometimes think it is enough to simply replace the few options in the database where the domain name appears but that is unfortunately not enough.
Indeed WordPress uses the PHP serialize/unserialize functions to store arrays in the the database. The problem here is that if you simply replace the domain name contained in a serialized object, you corrupt the data and will be unable to deserialize it because PHP serialization will add the length of every variable as part of the data. So unless you actually replace your domain name with another of the same size, you can not simply do a database search and replace.
**Fortunately there are 2 easy solutions:**
1. This script: <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>
You simply deploy the folder in the root of your install and access it over http. **Do not forget to delete the folder once you are finished**
2. This CLI: <http://wp-cli.org/commands/search-replace/>
Solution that I personally prefer because it does far more than just search & replace and can help you keeping a healthy WordPress instance.
|
238,146 |
<p>I have 2 taxonomy sets <strong><code>product_cat</code></strong> and <strong><code>tvshows_cat</code></strong>.</p>
<p>There are 12 terms for each of them. A product may get 1 or 12 terms applied.</p>
<p>I use this code to show the term list in the product page:</p>
<pre>
$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', '');
$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', '');
if (!empty($cats)){
echo strip_tags($cats, ' ');
}elseif(!empty($tvcats)){
echo strip_tags($tvcats, ' ');
}
</pre>
<p>The result is: </p>
<p><b><i>Action, Drama, Adventure, Biography, Animation</I></b></p>
<p>The problem is it doesn't have enough space to show all of the terms. </p>
<p>I need to limit number of terms to 2 terms.</p>
<p>Question</p>
<p>How can I limit the number of terms applied to two?</p>
|
[
{
"answer_id": 238149,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>We can limit the number of displayed terms with</p>\n\n<pre><code>// Add filter\nadd_filter( 'get_the_terms', 'wpse_limit_terms' );\n\n// Get terms\n$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', ''); \n$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', ''); \n\n// Remove filter\nremove_filter( 'get_the_terms', 'wpse_limit_terms' );\n</code></pre>\n\n<p>where we define the filter callback as:</p>\n\n<pre><code>function wpse_limit_terms( $terms )\n{\n // Adjust to your needs\n $length = 2;\n\n // Slice the terms array\n if( is_array( $terms ) && count( $terms ) > $length ) \n $terms = array_slice( $terms, $offset = 0, $length );\n\n return $terms;\n}\n</code></pre>\n\n<h2>Update:</h2>\n\n<p>It looks like OP only wants to get a comma separated list of term names. </p>\n\n<p>We can alternatively do the following: </p>\n\n<pre><code>$taxonomy = 'product_cat'; // Adjust to your needs\n$terms = get_the_terms( get_the_ID(), $taxonomy );\nif( is_array( $terms ) && ! empty( $terms ) )\n echo join( ',', wp_list_pluck( array_slice( $terms, 0, 2 ), 'name' ) \n</code></pre>\n\n<p>We could also create a general wrapper for this. Here's an untested suggestion:</p>\n\n<pre><code>/**\n * Custom wrapper\n *\n * @return string Comma seperated term attribute values\n */\nfunction get_wpse_terms_attribute_csv( $post_id, $taxonomy, $attribute, $length = 0 )\n{\n $csv = '';\n\n // Nothing to do for non-attributes \n if( ! in_array( $attribute, [ 'name', 'term_id', 'slug' ] ) )\n return $csv;\n\n // Nothing to do if taxonomy doesn't exists\n if( ! taxonomy_exists( $taxonomy ) )\n return $csv;\n\n // Fetch terms\n $terms = get_the_terms( $post_id, $taxonomy );\n\n // Nothing to do if we don't have a non-empty array of terms \n if( ! is_array( $terms ) || empty( $terms ) )\n return $csv;\n\n // Slice the array if needed\n if( (int) $length > 0 )\n $terms = array_slice( $terms, 0, (int) $length )\n\n // Pluck the terms array \n $terms = wp_list_pluck( $terms, $attribute );\n\n // Generate a list of comma separated term attribute values \n $csv = join( ',', $terms );\n\n return $csv; \n ) \n</code></pre>\n\n<p>We can then use this within the loop like:</p>\n\n<pre><code>echo get_wpse_terms_attribute_csv( \n $post_id = get_the_ID(), \n $taxonomy = 'product_cat', \n $attribute = 'name', \n $length = 2 \n);\n</code></pre>\n\n<p>Hopefully you can adjust this further to your needs!</p>\n"
},
{
"answer_id": 244243,
"author": "Mostafa AHmadi",
"author_id": 101903,
"author_profile": "https://wordpress.stackexchange.com/users/101903",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p><strong>Instead using <code>get_the_term_list()</code> function, you should use <code>get_the_terms()</code> which will give you directly an array of terms</strong> <em>(as <code>get_the_term_list()</code> is using <code>get_the_terms()</code> herself if you look to the source code of the function)</em>. </p>\n</blockquote>\n\n<p>Then that you can build a <strong>custom function</strong> to get what you want <em>(I will <strong>not use implode() function</strong> or <strong>any other one</strong> php function as we want only 2 terms.)</em></p>\n\n<p><strong>Note:</strong> You don't need <code>strip_tags()</code> function here</p>\n\n<p>So your code will be:</p>\n\n<pre>\n// This function goes first\nfunction get_my_terms( $post_id, $taxonomy ){\n $cats = get_the_terms( $post_id, $taxonomy );\n\n foreach($cats as $cat) $cats_arr[] = $cat->name;\n\n if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms\n elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term\n else $cats_str = '';\n\n return $cats_str;\n}\n</pre>\n\n<p><i>This code goes in function.php file of your active child theme (or theme) or any plugin files… </i></p>\n\n<p>Then below is your code:</p>\n\n<pre>\n$cats = get_my_terms( $post->ID, 'product_cat' ); \n$tvcats = get_my_terms( $post->ID, 'tvshows_cat' ); \n\n// Displaying 2 categories terms max\necho $cats . $tvcats;\n</pre>\n\n<p><i>This code goes on your php templates file</i></p>\n\n<blockquote>\n <p><strong>— update —</strong> Or without function, your code will be:</p>\n</blockquote>\n\n<pre>\n// Product categories\n$cats = get_the_terms( $post->ID, 'product_cat' );\n\nforeach($cats as $cat) $cats_arr[] = $cat->name;\n\nif ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms\nelseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term\nelse $cats_str = '';\n\n// TV shows categories\n$tvcats = get_the_terms( $post->ID, 'tvshows_cat' );\n\nforeach($tvcats as $tvcat) $tvcat_arr[] = $tvcat->name;\n\nif ( count($tvcat_arr) > 1) $tvcats_str = $tvcat_arr[0] . ', ' . $tvcat_arr[1]; // return first 2 terms\nelseif ( count($tvcat_arr) == 1) $tvcats_str = $tvcat_arr[0]; // return one term\nelse $tvcats_str = '';\n\n// The Display of 2 categories\necho $cats_str . $tvcats_str;\n</pre>\n\n<p>This code goes on your <strong>php templates</strong> files</p>\n"
}
] |
2016/09/04
|
[
"https://wordpress.stackexchange.com/questions/238146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101903/"
] |
I have 2 taxonomy sets **`product_cat`** and **`tvshows_cat`**.
There are 12 terms for each of them. A product may get 1 or 12 terms applied.
I use this code to show the term list in the product page:
```
$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', '');
$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', '');
if (!empty($cats)){
echo strip_tags($cats, ' ');
}elseif(!empty($tvcats)){
echo strip_tags($tvcats, ' ');
}
```
The result is:
***Action, Drama, Adventure, Biography, Animation***
The problem is it doesn't have enough space to show all of the terms.
I need to limit number of terms to 2 terms.
Question
How can I limit the number of terms applied to two?
|
>
> **Instead using `get_the_term_list()` function, you should use `get_the_terms()` which will give you directly an array of terms** *(as `get_the_term_list()` is using `get_the_terms()` herself if you look to the source code of the function)*.
>
>
>
Then that you can build a **custom function** to get what you want *(I will **not use implode() function** or **any other one** php function as we want only 2 terms.)*
**Note:** You don't need `strip_tags()` function here
So your code will be:
```
// This function goes first
function get_my_terms( $post_id, $taxonomy ){
$cats = get_the_terms( $post_id, $taxonomy );
foreach($cats as $cat) $cats_arr[] = $cat->name;
if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms
elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term
else $cats_str = '';
return $cats_str;
}
```
*This code goes in function.php file of your active child theme (or theme) or any plugin files…*
Then below is your code:
```
$cats = get_my_terms( $post->ID, 'product_cat' );
$tvcats = get_my_terms( $post->ID, 'tvshows_cat' );
// Displaying 2 categories terms max
echo $cats . $tvcats;
```
*This code goes on your php templates file*
>
> **— update —** Or without function, your code will be:
>
>
>
```
// Product categories
$cats = get_the_terms( $post->ID, 'product_cat' );
foreach($cats as $cat) $cats_arr[] = $cat->name;
if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms
elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term
else $cats_str = '';
// TV shows categories
$tvcats = get_the_terms( $post->ID, 'tvshows_cat' );
foreach($tvcats as $tvcat) $tvcat_arr[] = $tvcat->name;
if ( count($tvcat_arr) > 1) $tvcats_str = $tvcat_arr[0] . ', ' . $tvcat_arr[1]; // return first 2 terms
elseif ( count($tvcat_arr) == 1) $tvcats_str = $tvcat_arr[0]; // return one term
else $tvcats_str = '';
// The Display of 2 categories
echo $cats_str . $tvcats_str;
```
This code goes on your **php templates** files
|
238,170 |
<p>So i'm working on a plugin where I assign a default avatar to anyone that comments. The line i'm stuck on contains a theme directory reference but I want to reference the image in the plugin directory instead. Thanks in advance!</p>
<pre><code>$new_avatar_url = get_bloginfo( 'plugin_directory' ) . '/avatar-1.jpg';
</code></pre>
|
[
{
"answer_id": 238172,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Try <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow\"><code>plugin_dir_url()</code></a>:</p>\n\n<pre><code>$new_avatar_url = plugin_dir_url( __FILE__ ) . '/avatar-1.jpg';\n</code></pre>\n"
},
{
"answer_id": 238173,
"author": "montrealist",
"author_id": 8105,
"author_profile": "https://wordpress.stackexchange.com/users/8105",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>plugin_dir_path()</code> (<a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_path/#user-contributed-notes\" rel=\"nofollow\">link to doc</a>):</p>\n\n<pre><code>$dir = plugin_dir_path( __FILE__ ); // returns \"/var/www/wp/wp-content/plugins/my-plugin/\"\n</code></pre>\n\n<p>Or, if you only need the path inside your plugin, <code>plugin_basename()</code> is your friend (<a href=\"https://developer.wordpress.org/reference/functions/plugin_basename/#user-contributed-notes\" rel=\"nofollow\">link to doc</a>):</p>\n\n<pre><code>$dir = plugin_basename( __FILE__ ); // returns \"my-plugin/my-plugin.php\"\n</code></pre>\n"
}
] |
2016/09/04
|
[
"https://wordpress.stackexchange.com/questions/238170",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102192/"
] |
So i'm working on a plugin where I assign a default avatar to anyone that comments. The line i'm stuck on contains a theme directory reference but I want to reference the image in the plugin directory instead. Thanks in advance!
```
$new_avatar_url = get_bloginfo( 'plugin_directory' ) . '/avatar-1.jpg';
```
|
Try [`plugin_dir_url()`](https://codex.wordpress.org/Function_Reference/plugin_dir_url):
```
$new_avatar_url = plugin_dir_url( __FILE__ ) . '/avatar-1.jpg';
```
|
238,191 |
<p>We have a section on the homepage where we'd like to show a different (random) post every 3 days.</p>
<p>I'm trying to figure out a way to do it. This would give us a weekly post, but I don't know how to get a post every 3 days...:</p>
<pre><code><?php
global $post;
$args = array(
'post_type' => 'girls_tips',
'posts_per_page' => 1,
'no_found_rows' => true,
'offset' => (date( 'W' ) - 1)
);
$posts = get_posts($args);
foreach($posts as $post):
setup_postdata($post);
?>
<h2><?php the_title(); ?></h2>
<?php endforeach; ?>
</code></pre>
<p>Any help would be appreciated!
Cheers,</p>
|
[
{
"answer_id": 238188,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 3,
"selected": true,
"text": "<p>No script of function necessary. It's actually built into WordPress. Simply go to your page to edit and on the right hand side you should see a widget labeled <em>Publish</em>.</p>\n\n<p>On the third line down, you will see an <em>Edit</em> button and you can set the date and time on when you want the page to be shown:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4WRRU.png\" alt=\"Publish\"></p>\n"
},
{
"answer_id": 238243,
"author": "Adrian Lambertz",
"author_id": 102229,
"author_profile": "https://wordpress.stackexchange.com/users/102229",
"pm_score": 1,
"selected": false,
"text": "<p>Please have in mind that this feature sometimes doesn't work if you use some caching plugins. Especially caching plugins that offer static page HDD-Cache.</p>\n\n<p>WordPress uses a HTTP-Cron to publish planned posts (and to do some other stuff). This cron (wp-cron.php) is executed everytime a user visits your site. If you use a page cache, the WordPress-Machinery doesn't start up because the user is directly redirected to a static html file \"outside\" of the WordPress. This behaviour \"breaks\" the HTTP-Cron of WordPress. </p>\n\n<p>Alternatively you can access your wp-cron with your server crontab:</p>\n\n<pre><code>*/10 * * * * curl http://example.com/wp-cron.php > /dev/null 2>&1\n</code></pre>\n\n<p>This ensures that the wp-cron runs without any problems when you use page cache.</p>\n"
}
] |
2016/09/04
|
[
"https://wordpress.stackexchange.com/questions/238191",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23411/"
] |
We have a section on the homepage where we'd like to show a different (random) post every 3 days.
I'm trying to figure out a way to do it. This would give us a weekly post, but I don't know how to get a post every 3 days...:
```
<?php
global $post;
$args = array(
'post_type' => 'girls_tips',
'posts_per_page' => 1,
'no_found_rows' => true,
'offset' => (date( 'W' ) - 1)
);
$posts = get_posts($args);
foreach($posts as $post):
setup_postdata($post);
?>
<h2><?php the_title(); ?></h2>
<?php endforeach; ?>
```
Any help would be appreciated!
Cheers,
|
No script of function necessary. It's actually built into WordPress. Simply go to your page to edit and on the right hand side you should see a widget labeled *Publish*.
On the third line down, you will see an *Edit* button and you can set the date and time on when you want the page to be shown:

|
238,210 |
<p>I'm trying to display a list of categories in a PHP enabled text widget. On child category pages I need to get the id of the current category's parent category and then use that to return a list of all that category's child categories except the current category.</p>
<p>I tried the following code but it's not working:</p>
<pre><code><?php if (is_category( )) {
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $catid->category_parent;
$catlist = get_categories(
array(
'child_of' => $parent,
'orderby' => 'id',
'order' => 'DESC',
'exclude' => $catid,
'hide_empty' => '0'
) );
} ?>
</code></pre>
<p>This displays both the parent categories and child categories.</p>
|
[
{
"answer_id": 238215,
"author": "jrcollins",
"author_id": 68414,
"author_profile": "https://wordpress.stackexchange.com/users/68414",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to be working:</p>\n\n<pre><code><?php if (is_category( )) {\n\n$thiscat = get_category( get_query_var( 'cat' ) );\n$catid = $thiscat->cat_ID;\n//create array from get_category_parents\n$parent_list = (explode (',',get_category_parents($catid,false,',')));\n$parent_name = ($parent_list[0]);\n$parent = get_cat_ID( $parent_name );\n\n$catlist = get_categories(\n array(\n 'child_of' => $parent,\n 'orderby' => 'id',\n 'order' => 'DESC',\n 'exclude' => $catid,\n 'hide_empty' => '0'\n ) );\n //check if current category is parent category\n if ( $catid == $parent ) {\n echo '<span>this is a parent category page</span>';\n }\n else {\n echo '<span>this is a child category page</span>';\n }\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 238229,
"author": "jrcollins",
"author_id": 68414,
"author_profile": "https://wordpress.stackexchange.com/users/68414",
"pm_score": 2,
"selected": false,
"text": "<p>I now realize there's an easier way to do this:</p>\n\n<pre><code><?php if (is_category( )) {\n\n $thiscat = get_category( get_query_var( 'cat' ) );\n $catid = $thiscat->cat_ID;\n $parent = $thiscat->category_parent;\n\n if (!empty ($parent) ) {\n //child category pages\n\n $catlist = get_categories(\n array(\n 'child_of' => $parent,\n 'orderby' => 'id',\n 'order' => 'DESC',\n 'exclude' => $catid,\n 'hide_empty' => '0'\n ) );\n}\n} ?>\n</code></pre>\n"
}
] |
2016/09/05
|
[
"https://wordpress.stackexchange.com/questions/238210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] |
I'm trying to display a list of categories in a PHP enabled text widget. On child category pages I need to get the id of the current category's parent category and then use that to return a list of all that category's child categories except the current category.
I tried the following code but it's not working:
```
<?php if (is_category( )) {
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $catid->category_parent;
$catlist = get_categories(
array(
'child_of' => $parent,
'orderby' => 'id',
'order' => 'DESC',
'exclude' => $catid,
'hide_empty' => '0'
) );
} ?>
```
This displays both the parent categories and child categories.
|
I now realize there's an easier way to do this:
```
<?php if (is_category( )) {
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $thiscat->category_parent;
if (!empty ($parent) ) {
//child category pages
$catlist = get_categories(
array(
'child_of' => $parent,
'orderby' => 'id',
'order' => 'DESC',
'exclude' => $catid,
'hide_empty' => '0'
) );
}
} ?>
```
|
238,235 |
<p>I'm trying to change the stylesheet for specific page/post while viewing in frontend, but I can't find the hook or filter for doing that ..</p>
<p>I've tried many hooks and pages and it doesn't work</p>
<p>Should I use <code>page_css_class</code> ?</p>
<pre><code>apply_filters( 'page_css_class', array $css_class, WP_Post $page, int $depth, array $args, int $current_page )
</code></pre>
|
[
{
"answer_id": 238236,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 0,
"selected": false,
"text": "<p>Look around for \"child theme\" of the theme you are using. Create something new. The basics for child themes is <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">here</a></p>\n"
},
{
"answer_id": 238237,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The filter <a href=\"https://developer.wordpress.org/reference/hooks/page_css_class/\" rel=\"nofollow\"><code>page_css_class</code></a> allows you to change the classes on all pages, when they are listed. This is not what you are looking for.</p>\n\n<p>In stead, you'll want to enqueue different style sheets for different posts/pages. This you can do using conditionals. Include a function like this in your <code>functions.php</code> (example will load a special style for the page with slug \"about-us\"):</p>\n\n<pre><code>function wpse238235_conditional_load_style() {\n if (is_page('about-us')) {\n wp_register_style('wpse238235-about-us-style', get_template_directory_uri() . '/about-us-style.css');\n wp_enqueue_style('wpse238235-about-us-style');\n }\n else {\n wp_register_style('wpse238235-default-style', get_template_directory_uri() . '/default-style.css');\n wp_enqueue_style('wpse238235-default-style');\n }\n</code></pre>\n\n<p>Beware that this assumes the mandatory <code>style.css</code> is also loaded somewhere. </p>\n"
}
] |
2016/09/05
|
[
"https://wordpress.stackexchange.com/questions/238235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102188/"
] |
I'm trying to change the stylesheet for specific page/post while viewing in frontend, but I can't find the hook or filter for doing that ..
I've tried many hooks and pages and it doesn't work
Should I use `page_css_class` ?
```
apply_filters( 'page_css_class', array $css_class, WP_Post $page, int $depth, array $args, int $current_page )
```
|
The filter [`page_css_class`](https://developer.wordpress.org/reference/hooks/page_css_class/) allows you to change the classes on all pages, when they are listed. This is not what you are looking for.
In stead, you'll want to enqueue different style sheets for different posts/pages. This you can do using conditionals. Include a function like this in your `functions.php` (example will load a special style for the page with slug "about-us"):
```
function wpse238235_conditional_load_style() {
if (is_page('about-us')) {
wp_register_style('wpse238235-about-us-style', get_template_directory_uri() . '/about-us-style.css');
wp_enqueue_style('wpse238235-about-us-style');
}
else {
wp_register_style('wpse238235-default-style', get_template_directory_uri() . '/default-style.css');
wp_enqueue_style('wpse238235-default-style');
}
```
Beware that this assumes the mandatory `style.css` is also loaded somewhere.
|
238,271 |
<p>I have a custom post type of people with some custom taxonomy boxes, i want to hide these when on child pages. I have found remove_meta_box works fine but i just can't access the $post object within the action.</p>
<p>Currently i have</p>
<pre><code>function remove_post_custom_fields($post) {
global $post;
if( count($post->ancestors) > 0 ){
remove_meta_box( 'staff-typediv' , 'people' , 'normal' );
remove_meta_box( 'practice-areadiv' , 'people' , 'normal' );
}
}
add_action( 'admin_menu' , 'remove_post_custom_fields' );
</code></pre>
<p>I have tried <code>count($post->ancestors) > 0</code> and also just <code>$post->post_parent</code> but neither work.</p>
<p>Anyone any clue how to access $post variables within this action?</p>
|
[
{
"answer_id": 238255,
"author": "montrealist",
"author_id": 8105,
"author_profile": "https://wordpress.stackexchange.com/users/8105",
"pm_score": 3,
"selected": true,
"text": "<p>Newer hosting providers that cater specifically to WordPress usually have tools in place to ease this pain. I put my clients on Pantheon which has this <a href=\"https://pantheon.io/docs/pantheon-workflow/\" rel=\"nofollow\">neat Git-enabled workflow</a>, where code only moves up (from dev to staging to production) and DB stuff only moves down (vice versa from the code). Copying a database from production to staging is one click with their interface. Provided this workflow is respected, this pretty much eliminates the issue of ever messing up the production database, enabling me to always test my changes on a fresh clone of production DB data in either staging on development.</p>\n\n<p>One doesn't have to use Pantheon - you can adopt a similar approach in your process using your own tools (Git + a DB cloning plugin like WP Migrate DB). I just find this way works well for me.</p>\n\n<p>Question: why would you put your production site in maintenance mode while testing staging? There shouldn't be a need for that in a majority of cases. The only case I can think of is having some sort of very brittle system highly sensitive to additional user data being fed into it, with a catastrophic bug to boot - but that would likely be indicative of a different, larger, problem where one would need to rethink their product's entire architecture.</p>\n"
},
{
"answer_id": 238803,
"author": "marekeiba",
"author_id": 102550,
"author_profile": "https://wordpress.stackexchange.com/users/102550",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look at <a href=\"https://versionpress.net/\" rel=\"nofollow\">VersionPress</a> which brings GIT versioning to the whole process (files and database)</p>\n\n<p>As described on their site: </p>\n\n<blockquote>\n <p><strong>VersionPress provides painless staging</strong>. This means that you can easily\n create a safe testing environment for your changes and only merge them\n back when they are ready. Merge is the key word here – VersionPress\n handles situations where your live site had new content in the\n meantime seamlessly.</p>\n</blockquote>\n"
}
] |
2016/09/05
|
[
"https://wordpress.stackexchange.com/questions/238271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6123/"
] |
I have a custom post type of people with some custom taxonomy boxes, i want to hide these when on child pages. I have found remove\_meta\_box works fine but i just can't access the $post object within the action.
Currently i have
```
function remove_post_custom_fields($post) {
global $post;
if( count($post->ancestors) > 0 ){
remove_meta_box( 'staff-typediv' , 'people' , 'normal' );
remove_meta_box( 'practice-areadiv' , 'people' , 'normal' );
}
}
add_action( 'admin_menu' , 'remove_post_custom_fields' );
```
I have tried `count($post->ancestors) > 0` and also just `$post->post_parent` but neither work.
Anyone any clue how to access $post variables within this action?
|
Newer hosting providers that cater specifically to WordPress usually have tools in place to ease this pain. I put my clients on Pantheon which has this [neat Git-enabled workflow](https://pantheon.io/docs/pantheon-workflow/), where code only moves up (from dev to staging to production) and DB stuff only moves down (vice versa from the code). Copying a database from production to staging is one click with their interface. Provided this workflow is respected, this pretty much eliminates the issue of ever messing up the production database, enabling me to always test my changes on a fresh clone of production DB data in either staging on development.
One doesn't have to use Pantheon - you can adopt a similar approach in your process using your own tools (Git + a DB cloning plugin like WP Migrate DB). I just find this way works well for me.
Question: why would you put your production site in maintenance mode while testing staging? There shouldn't be a need for that in a majority of cases. The only case I can think of is having some sort of very brittle system highly sensitive to additional user data being fed into it, with a catastrophic bug to boot - but that would likely be indicative of a different, larger, problem where one would need to rethink their product's entire architecture.
|
238,293 |
<p>Similar to generating an array of the admin menu/submenu:</p>
<pre><code>global $menu;
foreach ( $menu as $group => $item ) {
echo '<pre>'; print_r( $item ); echo '</pre>';
}
</code></pre>
<p>How can I get an array of all of the available menu items in the toolbar? I tried using the <code>global $wp_admin_bar</code> variable, but that seems to not be the right one.</p>
<p><img src="https://i.stack.imgur.com/R1KMD.png" alt="Toolbar" /></p>
<p>The reason why I want to generate this array is to use this in a plugin of mine to provide an option to choose which items to hide from the toolbar, allowing users to customize their settings. Right now, I manually created an array called <code>$toolbar</code> to choose the items I want to hide myself:</p>
<pre><code>global $wp_admin_bar;
$toolbar = array(
'wp-logo', // WordPress logo
'comments', // Comments
'new-post', // New > Post
'search' // Search
);
foreach ( $toolbar as $item ) {
$wp_admin_bar -> remove_menu( $item );
}
</code></pre>
<hr />
<h3>Update [2016-09-16]</h3>
<p>I was able to get the entire list by using the following in my plugin settings page:</p>
<pre><code>global $wp_admin_bar;
echo '<pre>'; print_r( $wp_admin_bar ); echo '</pre>';
</code></pre>
<p>It's too long to paste in here, so you can view the entire list on this <a href="http://pastebin.com/QfSaE5Tk" rel="nofollow noreferrer">Pastebin link</a>. However, below is a snippet of how it starts. How can I get all of the values that are in <code>[id] =></code> and/or <code>[parent] =></code>? It looks like I would need to go through a few levels of <code>foreach</code>?</p>
<pre><code>WP_Admin_Bar Object (
[nodes:WP_Admin_Bar:private] => Array (
[user-actions] => stdClass Object (
[id] => user-actions
[title] =>
[parent] => my-account
[href] =>
[meta] => Array (
[class] => ab-submenu
)
[children] => Array (
[0] => stdClass Object (
[id] => user-info
[title] => Name
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
[tabindex] => -1
)
[children] => Array (
)
[type] => item
)
[1] => stdClass Object (
[id] => edit-profile
[title] => Edit My Profile
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
)
[children] => Array (
)
[type] => item
)
and so on...
</code></pre>
|
[
{
"answer_id": 238295,
"author": "Syed Fakhar Abbas",
"author_id": 90591,
"author_profile": "https://wordpress.stackexchange.com/users/90591",
"pm_score": 2,
"selected": false,
"text": "<p>There is an action hook <a href=\"https://developer.wordpress.org/?s=admin_bar_menu\" rel=\"nofollow\">admin_bar_menu</a> which will provide you an array of admin bar menu items.</p>\n\n<pre><code>\nadd_action('admin_bar_menu', 'get_admin_bar_header_array');<br/>\npublic function get_admin_bar_header_array($admin_bar){<br/>\n print_r($admin_bar);<br/>\n }<br/>\n</code></pre>\n\n<p>:)</p>\n"
},
{
"answer_id": 238886,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 1,
"selected": false,
"text": "<p>Hook into the action <code>admin_bar_menu</code>, and fetch the menu items with the method <code>get_nodes()</code>, because the item list is private and cannot be accessed directly:</p>\n\n<pre><code>add_action( 'admin_bar_menu', function( \\WP_Admin_Bar $wp_admin_bar ) {\n\n $items = $wp_admin_bar->get_nodes();\n\n if ( ! $items )\n return;\n\n print '<pre>';\n\n foreach ( $items as $id => $item )\n {\n print \"$id: \" . print_r( $item, TRUE ) . \"\\n\";\n }\n\n print '</pre>';\n}, PHP_INT_MAX );\n</code></pre>\n"
}
] |
2016/09/05
|
[
"https://wordpress.stackexchange.com/questions/238293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] |
Similar to generating an array of the admin menu/submenu:
```
global $menu;
foreach ( $menu as $group => $item ) {
echo '<pre>'; print_r( $item ); echo '</pre>';
}
```
How can I get an array of all of the available menu items in the toolbar? I tried using the `global $wp_admin_bar` variable, but that seems to not be the right one.

The reason why I want to generate this array is to use this in a plugin of mine to provide an option to choose which items to hide from the toolbar, allowing users to customize their settings. Right now, I manually created an array called `$toolbar` to choose the items I want to hide myself:
```
global $wp_admin_bar;
$toolbar = array(
'wp-logo', // WordPress logo
'comments', // Comments
'new-post', // New > Post
'search' // Search
);
foreach ( $toolbar as $item ) {
$wp_admin_bar -> remove_menu( $item );
}
```
---
### Update [2016-09-16]
I was able to get the entire list by using the following in my plugin settings page:
```
global $wp_admin_bar;
echo '<pre>'; print_r( $wp_admin_bar ); echo '</pre>';
```
It's too long to paste in here, so you can view the entire list on this [Pastebin link](http://pastebin.com/QfSaE5Tk). However, below is a snippet of how it starts. How can I get all of the values that are in `[id] =>` and/or `[parent] =>`? It looks like I would need to go through a few levels of `foreach`?
```
WP_Admin_Bar Object (
[nodes:WP_Admin_Bar:private] => Array (
[user-actions] => stdClass Object (
[id] => user-actions
[title] =>
[parent] => my-account
[href] =>
[meta] => Array (
[class] => ab-submenu
)
[children] => Array (
[0] => stdClass Object (
[id] => user-info
[title] => Name
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
[tabindex] => -1
)
[children] => Array (
)
[type] => item
)
[1] => stdClass Object (
[id] => edit-profile
[title] => Edit My Profile
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
)
[children] => Array (
)
[type] => item
)
and so on...
```
|
There is an action hook [admin\_bar\_menu](https://developer.wordpress.org/?s=admin_bar_menu) which will provide you an array of admin bar menu items.
```
add_action('admin_bar_menu', 'get_admin_bar_header_array');
public function get_admin_bar_header_array($admin_bar){
print_r($admin_bar);
}
```
:)
|
238,314 |
<p>I want to include a json manifest file in wordpress plugin but don't know how,
this is the file that i want to include in my plugin with <code>rel=manifest</code> and <code>href=manifest.json</code></p>
<p><code><link rel="manifest" href="/manifest.json"></code></p>
<p>How to do this in plugin ?</p>
|
[
{
"answer_id": 238319,
"author": "user3114253",
"author_id": 76325,
"author_profile": "https://wordpress.stackexchange.com/users/76325",
"pm_score": 2,
"selected": false,
"text": "<p>Include this in you plugin</p>\n\n<pre><code>add_action( 'wp_head', 'inc_manifest_link' );\n\n// Creates the link tag\nfunction inc_manifest_link() { \n echo '<link rel=\"manifest\" href=\"/manifest.json\">';\n}\n</code></pre>\n\n<p>what we are doing here is adding a hook to wp_head action.</p>\n"
},
{
"answer_id": 411963,
"author": "Antonio Tito",
"author_id": 228161,
"author_profile": "https://wordpress.stackexchange.com/users/228161",
"pm_score": 0,
"selected": false,
"text": "<p>After creating the file (manifest.json), add <code><link rel="manifest" href="/manifest.json"></code> to all the html pages of your Progressive Web App between <code><head>...</head> </code></p>\n<p>follow these instructions:</p>\n<p><a href=\"https://www.basezap.com/progressive-web-app-wordpress/\" rel=\"nofollow noreferrer\">https://www.basezap.com/progressive-web-app-wordpress/</a></p>\n<p>and let me know if you can....</p>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238314",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102268/"
] |
I want to include a json manifest file in wordpress plugin but don't know how,
this is the file that i want to include in my plugin with `rel=manifest` and `href=manifest.json`
`<link rel="manifest" href="/manifest.json">`
How to do this in plugin ?
|
Include this in you plugin
```
add_action( 'wp_head', 'inc_manifest_link' );
// Creates the link tag
function inc_manifest_link() {
echo '<link rel="manifest" href="/manifest.json">';
}
```
what we are doing here is adding a hook to wp\_head action.
|
238,330 |
<p>I tried the example in this link <a href="https://codex.wordpress.org/Function_Reference/wp_embed_register_handler" rel="nofollow">https://codex.wordpress.org/Function_Reference/wp_embed_register_handler</a> but it didn't work. This is my whole code:</p>
<pre><code>add_action('init', function() {
wp_embed_register_handler( 'forbes', '#http://(?:www|video)\.forbes\.com/(?:video/embed/embed\.html|embedvideo/)\?show=([\d]+)&format=frame&height=([\d]+)&width=([\d]+)&video=(.+?)($|&)#i', 'wp_embed_handler_forbes' );
});
function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr ) {
$embed = sprintf(
'<iframe src="http://www.forbes.com/video/embed/embed.html?show=%1$s&format=frame&height=%2$s&width=%3$s&video=%4$s&mode=render" width="%3$spx" height="%2$spx" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>',
esc_attr($matches[1]),
esc_attr($matches[2]),
esc_attr($matches[3]),
esc_attr($matches[4])
);
return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}
</code></pre>
<p>Any ideas why this is not working?</p>
|
[
{
"answer_id": 238351,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I modified the example you posted from the Codex:</p>\n\n<pre><code>/**\n * Embed support for Forbes videos\n *\n * Usage Example:\n *\n * http://www.forbes.com/video/5049647995001/\n */\nadd_action( 'init', function()\n{\n wp_embed_register_handler( \n 'forbes', \n '#http://www\\.forbes\\.com/video/([\\d]+)/?#i', \n 'wp_embed_handler_forbes' \n );\n\n} );\n\nfunction wp_embed_handler_forbes( $matches, $attr, $url, $rawattr )\n{\n $embed = sprintf(\n '<iframe class=\"forbes-video\" src=\"https://players.brightcove.net/2097119709001/598f142b-5fda-4057-8ece-b03c43222b3f_default/index.html?videoId=%1$s\" width=\"600\" height=\"400\" frameborder=\"0\" scrolling=\"no\"></iframe>',\n esc_attr( $matches[1] ) \n );\n\n return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );\n}\n</code></pre>\n\n<p>Currently the <code>iframe</code> has a fixed <em>height</em> and <em>width</em>. </p>\n\n<p>You can hopefully adjust it to your needs, e.g. using the theme's <code>$content_width</code> or pass on the height/width information directly from the pasted video url.</p>\n\n<p><strong>Update:</strong> I added a <a href=\"https://codex.wordpress.org/Function_Reference/wp_embed_register_handler#Examples\" rel=\"nofollow noreferrer\">warning to the Codex page</a>, until a better example is posted.</p>\n"
},
{
"answer_id": 373846,
"author": "mosne",
"author_id": 193786,
"author_profile": "https://wordpress.stackexchange.com/users/193786",
"pm_score": 0,
"selected": false,
"text": "<p>here un example with linkedin</p>\n<pre class=\"lang-php prettyprint-override\"><code>/** linkedin embed\n* example : https://www.linkedin.com/embed/feed/update/urn:li:share:6704370979721777152\n*/\nadd_action(\n 'init',\n function () {\n wp_embed_register_handler(\n 'linkedin',\n '#https://www\\.linkedin\\.com/embed/feed/update/urn:li:share:([\\d]+)/?#i',\n 'embed_handler_linkedin'\n );\n }\n);\n\nfunction embed_handler_linkedin( $matches, $attr, $url, $rawattr ) {\n\n $embed = sprintf(\n '<iframe src="https://www.linkedin.com/embed/feed/update/urn:li:share:%s" width="500" height="453" frameborder="0" scrolling="no" class="block__linkedin"></iframe>',\n esc_attr( $matches[1] )\n );\n\n return apply_filters( 'embed_linkedin', $embed, $matches, $attr, $url, $rawattr );\n}\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102275/"
] |
I tried the example in this link <https://codex.wordpress.org/Function_Reference/wp_embed_register_handler> but it didn't work. This is my whole code:
```
add_action('init', function() {
wp_embed_register_handler( 'forbes', '#http://(?:www|video)\.forbes\.com/(?:video/embed/embed\.html|embedvideo/)\?show=([\d]+)&format=frame&height=([\d]+)&width=([\d]+)&video=(.+?)($|&)#i', 'wp_embed_handler_forbes' );
});
function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr ) {
$embed = sprintf(
'<iframe src="http://www.forbes.com/video/embed/embed.html?show=%1$s&format=frame&height=%2$s&width=%3$s&video=%4$s&mode=render" width="%3$spx" height="%2$spx" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>',
esc_attr($matches[1]),
esc_attr($matches[2]),
esc_attr($matches[3]),
esc_attr($matches[4])
);
return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}
```
Any ideas why this is not working?
|
I modified the example you posted from the Codex:
```
/**
* Embed support for Forbes videos
*
* Usage Example:
*
* http://www.forbes.com/video/5049647995001/
*/
add_action( 'init', function()
{
wp_embed_register_handler(
'forbes',
'#http://www\.forbes\.com/video/([\d]+)/?#i',
'wp_embed_handler_forbes'
);
} );
function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr )
{
$embed = sprintf(
'<iframe class="forbes-video" src="https://players.brightcove.net/2097119709001/598f142b-5fda-4057-8ece-b03c43222b3f_default/index.html?videoId=%1$s" width="600" height="400" frameborder="0" scrolling="no"></iframe>',
esc_attr( $matches[1] )
);
return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}
```
Currently the `iframe` has a fixed *height* and *width*.
You can hopefully adjust it to your needs, e.g. using the theme's `$content_width` or pass on the height/width information directly from the pasted video url.
**Update:** I added a [warning to the Codex page](https://codex.wordpress.org/Function_Reference/wp_embed_register_handler#Examples), until a better example is posted.
|
238,347 |
<p>I have many duplicated post and I wanted remove them but Google already indexed them. So the idea is redirect all post with pattern [-number] in the end of the url to the same URL without number</p>
<p><code>www.domain.com/category/post-title[-number]</code> to <code>www.domain.com/category/post-title</code></p>
<p>Example:</p>
<pre><code>www.domain.com/category/post-title/
www.domain.com/category/post-title-1/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-2/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-3/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-4/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-5/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-6/ --> www.domain.com/category/post-title/
</code></pre>
<p>I have tried some Rewrite Rules on the .htaccess but didn't work at all.</p>
<p>For example this one:</p>
<pre><code>#RewriteRule ^/(.+)-[0-9]+/$ /$1 R=301
</code></pre>
<p><code>(.+)</code> --> it will match the letters of the 'post-title'</p>
<p><code>-[0-9]+/</code> --> It will match the '-' and the number of the tittle</p>
<p>Thanks!</p>
|
[
{
"answer_id": 238354,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>you can test this in the 404 template and do a redirection </p>\n\n<p>try this : </p>\n\n<pre><code>add_filter(\"404_template\", function ($template) {\n\n var_dump($GLOBALS[\"wp_query\"]->query);\n\n\n return $template;\n\n}, 10, 1);\n</code></pre>\n"
},
{
"answer_id": 239627,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": false,
"text": "<p>You're close. Add the following to your <code>.htaccess</code> file in between the <code><IfModule mod_rewrite.c></code> tags that were created by WordPress:</p>\n\n<pre><code>RewriteCond %{HTTP_HOST}\nRewriteRule ^(.+)-[0-9]+/$ /$1 [R=301]\n</code></pre>\n\n<p>Your <code>.htaccess</code> should looks like the following if it hasn't been modified by another plugin:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# Custom Rewrite\nRewriteCond %{HTTP_HOST}\nRewriteRule ^(.+)-[0-9]+/$ /$1 [R=301]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>As a result it will do the following:</p>\n\n<pre><code>http://example.com/category/post-title[-NUMBER]\n</code></pre>\n\n<p>Redirects to:</p>\n\n<pre><code>http://example.com/category/post-title\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65640/"
] |
I have many duplicated post and I wanted remove them but Google already indexed them. So the idea is redirect all post with pattern [-number] in the end of the url to the same URL without number
`www.domain.com/category/post-title[-number]` to `www.domain.com/category/post-title`
Example:
```
www.domain.com/category/post-title/
www.domain.com/category/post-title-1/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-2/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-3/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-4/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-5/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-6/ --> www.domain.com/category/post-title/
```
I have tried some Rewrite Rules on the .htaccess but didn't work at all.
For example this one:
```
#RewriteRule ^/(.+)-[0-9]+/$ /$1 R=301
```
`(.+)` --> it will match the letters of the 'post-title'
`-[0-9]+/` --> It will match the '-' and the number of the tittle
Thanks!
|
You're close. Add the following to your `.htaccess` file in between the `<IfModule mod_rewrite.c>` tags that were created by WordPress:
```
RewriteCond %{HTTP_HOST}
RewriteRule ^(.+)-[0-9]+/$ /$1 [R=301]
```
Your `.htaccess` should looks like the following if it hasn't been modified by another plugin:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# Custom Rewrite
RewriteCond %{HTTP_HOST}
RewriteRule ^(.+)-[0-9]+/$ /$1 [R=301]
</IfModule>
# END WordPress
```
As a result it will do the following:
```
http://example.com/category/post-title[-NUMBER]
```
Redirects to:
```
http://example.com/category/post-title
```
|
238,359 |
<p>I tried to figure out how to separate the custom post type taxonomies.</p>
<pre><code>$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, array( 'commitments', 'type' ) );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
</code></pre>
<p>Each taxonomies show correctly. However, I cannot separate them in comma. it shows "TaxonomyATaxonomyB" but I want to show it as "TaxonomyA, TaxonomyB"</p>
<p>How to do it? or is there any other way around?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 238362,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 4,
"selected": true,
"text": "<p>You can use a counter to determine if you need to add a comma or not :</p>\n\n<pre><code>$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );\n// init counter\n$i = 1;\nforeach ( $terms as $term ) {\n $term_link = get_term_link( $term, array( 'commitments', 'type' ) );\n if( is_wp_error( $term_link ) )\n continue;\n echo '<a href=\"' . $term_link . '\">' . $term->name . '</a>';\n // Add comma (except after the last theme)\n echo ($i < count($terms))? \", \" : \"\";\n // Increment counter\n $i++;\n}\n</code></pre>\n"
},
{
"answer_id": 238363,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>The cleanest way (IMO) to do anything like this in PHP, is build an array and then implode it:</p>\n\n<pre><code>$list = [];\nforeach ( $terms as $term ) {\n $term_link = get_term_link( $term /* no need for taxonomy arg if $term is an object */ );\n if ( ! is_wp_error( $term_link ) )\n $list[] = $term_link;\n}\n\necho implode( ', ', $list );\n</code></pre>\n"
},
{
"answer_id": 238364,
"author": "99teko",
"author_id": 69536,
"author_profile": "https://wordpress.stackexchange.com/users/69536",
"pm_score": 3,
"selected": false,
"text": "<p>Or you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"noreferrer\">get_the_term_list</a> function.</p>\n\n<pre><code><?php echo get_the_term_list( $post->ID, 'commitments', '', ', ' ); ?>\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35253/"
] |
I tried to figure out how to separate the custom post type taxonomies.
```
$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, array( 'commitments', 'type' ) );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
```
Each taxonomies show correctly. However, I cannot separate them in comma. it shows "TaxonomyATaxonomyB" but I want to show it as "TaxonomyA, TaxonomyB"
How to do it? or is there any other way around?
Thanks!
|
You can use a counter to determine if you need to add a comma or not :
```
$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
// init counter
$i = 1;
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, array( 'commitments', 'type' ) );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
// Add comma (except after the last theme)
echo ($i < count($terms))? ", " : "";
// Increment counter
$i++;
}
```
|
238,383 |
<p>My feed uses the excerpt, and I want to remove a line of code containing an image.</p>
<p>Example format is...</p>
<pre><code><img class="pagehead" src="/graphics/magazine/307/1.jpg" alt="" />
</code></pre>
|
[
{
"answer_id": 238384,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 1,
"selected": false,
"text": "<p>You can <a href=\"https://codex.wordpress.org/Customizing_Feeds\" rel=\"nofollow\">customize your feed like any other template</a> and use <a href=\"https://codex.wordpress.org/Template_Tags/the_excerpt_rss\" rel=\"nofollow\">the_excerpt_rss</a> function:</p>\n\n<pre><code><?php the_excerpt_rss( $cut, $encode_html ); ?>\n</code></pre>\n\n<p>Or maybe use PHP <a href=\"http://php.net/manual/fr/function.strip-tags.php\" rel=\"nofollow\">strip_tags</a> function :</p>\n\n<pre><code>// Autorise <p> et <a>\necho strip_tags( $text, '<p><a>' );\n</code></pre>\n"
},
{
"answer_id": 238562,
"author": "gulliver",
"author_id": 63350,
"author_profile": "https://wordpress.stackexchange.com/users/63350",
"pm_score": 2,
"selected": false,
"text": "<p>UPDATE...</p>\n\n<p>Answering my own question, I'll add this in the hope it'll be useful to someone...</p>\n\n<p>Whilst waiting for answers, I found a solution which seems to work fine.</p>\n\n<pre><code>function remove_images( $the_excerpt_rss ) {\n$postOutput = preg_replace('/<img[^>]+./','', $the_excerpt_rss);\nreturn $postOutput;}\nadd_filter( 'the_excerpt_rss', 'remove_images', 100 );\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238383",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] |
My feed uses the excerpt, and I want to remove a line of code containing an image.
Example format is...
```
<img class="pagehead" src="/graphics/magazine/307/1.jpg" alt="" />
```
|
UPDATE...
Answering my own question, I'll add this in the hope it'll be useful to someone...
Whilst waiting for answers, I found a solution which seems to work fine.
```
function remove_images( $the_excerpt_rss ) {
$postOutput = preg_replace('/<img[^>]+./','', $the_excerpt_rss);
return $postOutput;}
add_filter( 'the_excerpt_rss', 'remove_images', 100 );
```
|
238,386 |
<p>I downgraded to MAMP after trying MAMP pro, everything is fine except some of the links don’t have localhost port; eg…localhost/about, when it should be localhost:8888/about. Some of the links include the port, and some don’t, but I’m not sure why? Any ideas would be greatly appreciated. Thanks!</p>
|
[
{
"answer_id": 238384,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 1,
"selected": false,
"text": "<p>You can <a href=\"https://codex.wordpress.org/Customizing_Feeds\" rel=\"nofollow\">customize your feed like any other template</a> and use <a href=\"https://codex.wordpress.org/Template_Tags/the_excerpt_rss\" rel=\"nofollow\">the_excerpt_rss</a> function:</p>\n\n<pre><code><?php the_excerpt_rss( $cut, $encode_html ); ?>\n</code></pre>\n\n<p>Or maybe use PHP <a href=\"http://php.net/manual/fr/function.strip-tags.php\" rel=\"nofollow\">strip_tags</a> function :</p>\n\n<pre><code>// Autorise <p> et <a>\necho strip_tags( $text, '<p><a>' );\n</code></pre>\n"
},
{
"answer_id": 238562,
"author": "gulliver",
"author_id": 63350,
"author_profile": "https://wordpress.stackexchange.com/users/63350",
"pm_score": 2,
"selected": false,
"text": "<p>UPDATE...</p>\n\n<p>Answering my own question, I'll add this in the hope it'll be useful to someone...</p>\n\n<p>Whilst waiting for answers, I found a solution which seems to work fine.</p>\n\n<pre><code>function remove_images( $the_excerpt_rss ) {\n$postOutput = preg_replace('/<img[^>]+./','', $the_excerpt_rss);\nreturn $postOutput;}\nadd_filter( 'the_excerpt_rss', 'remove_images', 100 );\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102305/"
] |
I downgraded to MAMP after trying MAMP pro, everything is fine except some of the links don’t have localhost port; eg…localhost/about, when it should be localhost:8888/about. Some of the links include the port, and some don’t, but I’m not sure why? Any ideas would be greatly appreciated. Thanks!
|
UPDATE...
Answering my own question, I'll add this in the hope it'll be useful to someone...
Whilst waiting for answers, I found a solution which seems to work fine.
```
function remove_images( $the_excerpt_rss ) {
$postOutput = preg_replace('/<img[^>]+./','', $the_excerpt_rss);
return $postOutput;}
add_filter( 'the_excerpt_rss', 'remove_images', 100 );
```
|
238,395 |
<p>I'm converting an existing website to a WordPress theme. One of the pages is a gallery that uses JS <code>history.pushState</code> to create unique URLs for loading certain images. </p>
<p>E.g. page URL (non WP website): <code>http://www.good-deeds-day.org/gallery/</code></p>
<p>URL for a certain image: <code>http://www.good-deeds-day.org/gallery/img-35</code></p>
<p>I would like to preserve this functionality in WordPress. However, when loading the URL for a certain image, WordPress considers it as a different page and displays a 404 error.</p>
<p>Is there a way to configure WordPress or <code>.htaccess</code> so that when such image URLs are loaded it will keep the URL and load the gallery page, thus displaying the relevant image in the gallery page?</p>
|
[
{
"answer_id": 238399,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>But from your description it's <em>not</em> an URL to a gallery, but individual image of one. I would guess it should <em>consistently</em> show individual image for such URL, regardless if it's served by WP back-end or manipulated client-side.</p>\n\n<p>The easiest way to accomplish such in WP I can think of would be <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">rewrite endpoint</a>. It can rather easily latch onto existing permalink structure and it's easy to work with and modify output.</p>\n\n<p>Unfortunately your format <code>/img-35</code> isn't endpoint-friendly, but if changing it is an option <code>/img/35</code> would work with endpoint perfectly.</p>\n"
},
{
"answer_id": 249099,
"author": "Ido Schacham",
"author_id": 102311,
"author_profile": "https://wordpress.stackexchange.com/users/102311",
"pm_score": 3,
"selected": true,
"text": "<p>I ended up using add_rewrite_rule:</p>\n\n<pre><code>function bones_rewrite_rules() {\n $gallery_page_id = 395; \n add_rewrite_rule('^gallery/img-.*', 'index.php?page_id=' . $gallery_page_id, 'top');\n}\nadd_action('init', 'bones_rewrite_rules');\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102311/"
] |
I'm converting an existing website to a WordPress theme. One of the pages is a gallery that uses JS `history.pushState` to create unique URLs for loading certain images.
E.g. page URL (non WP website): `http://www.good-deeds-day.org/gallery/`
URL for a certain image: `http://www.good-deeds-day.org/gallery/img-35`
I would like to preserve this functionality in WordPress. However, when loading the URL for a certain image, WordPress considers it as a different page and displays a 404 error.
Is there a way to configure WordPress or `.htaccess` so that when such image URLs are loaded it will keep the URL and load the gallery page, thus displaying the relevant image in the gallery page?
|
I ended up using add\_rewrite\_rule:
```
function bones_rewrite_rules() {
$gallery_page_id = 395;
add_rewrite_rule('^gallery/img-.*', 'index.php?page_id=' . $gallery_page_id, 'top');
}
add_action('init', 'bones_rewrite_rules');
```
|
238,403 |
<p>Creating first wp plugin.</p>
<p>Using add action init with filter for the_content</p>
<p>I noticed that whenever I echo anything it appears twice in the header, and finally once in the body.</p>
<p>Why?</p>
<p>Or How can I avoid this?</p>
<p>kthxbai</p>
<p><strong>EDIT</strong> </p>
<pre><code>function my_module_init() {
//Filter this content
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
// function controller plug-in
function my_content_ctrlr($content) {
global $post;
//Get value of metabox from current id
$codeUnit = get_post_meta($post->ID, 'list_unit_meta_key', true);
//If none selected from metabox, skip it as its a regular page
if( $codeUnit == 'NULL' || !isset($codeUnit) || $codeUnit == '') {
return $content;
}
//if I add echo anything, it shows up twice in head and once in body
// WHY?
//echo $codeUnit;
ob_start();
//If photo included display grid view, else table view
if ($includePhoto == 'on') {
include(plugin_dir_path(__FILE__) . 'views/my-grid.php');
} else {
include(plugin_dir_path(__FILE__) . 'views/my-table.php');
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
</code></pre>
|
[
{
"answer_id": 238438,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I've pasted below, and I do not get duplicated content:</p>\n\n<pre><code>function my_module_init() {\n add_filter('the_content', 'my_content_ctrlr');\n}\nadd_action('init', 'my_module_init');\n\nfunction my_content_ctrlr( $content ) {\n ob_start(); \n\n // This file contains only the following simple text for testing purposes: ######### \n include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' ); \n\n $output = ob_get_contents();\n\n ob_end_clean();\n\n // Add our custom code before the existing content.\n return $output . $content;\n}\n</code></pre>\n\n<p>So, I think that we can rule out my original idea that content was being echoed instead of returned. </p>\n\n<p>Another possibility is that there are additional <code>apply_filters()</code> calls on <code>the_content</code> somewhere in your site via plugins or the theme. E.g.:</p>\n\n<pre><code>echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );\n</code></pre>\n\n<p>It's not uncommon for themes to do that kind of thing, and it would result in <code>my_content_ctrlr()</code> being called once for each additional occurrence.</p>\n\n<p>You can use some additional checks as illustrated by this snippet to resolve that problem (<a href=\"https://pippinsplugins.com/playing-nice-with-the-content-filter/\" rel=\"nofollow\">source</a>).</p>\n\n<pre><code>function pippin_filter_content_sample($content) {\n if( is_singular() && is_main_query() ) {\n $new_content = '<p>This is added to the bottom of all post and page content, as well as custom post types.</p>';\n $content .= $new_content; \n } \n return $content;\n}\nadd_filter('the_content', 'pippin_filter_content_sample');\n</code></pre>\n"
},
{
"answer_id": 238525,
"author": "MediaFormat",
"author_id": 87622,
"author_profile": "https://wordpress.stackexchange.com/users/87622",
"pm_score": -1,
"selected": false,
"text": "<p>Thanks @goto10, the <code>is_main_query</code> didn't work for me but set me in the right direction, adding additional conditional checks. I ended up using <code>in_the_loop</code>:</p>\n\n<pre><code>if (!in_the_loop()){\n return;\n}\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87622/"
] |
Creating first wp plugin.
Using add action init with filter for the\_content
I noticed that whenever I echo anything it appears twice in the header, and finally once in the body.
Why?
Or How can I avoid this?
kthxbai
**EDIT**
```
function my_module_init() {
//Filter this content
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
// function controller plug-in
function my_content_ctrlr($content) {
global $post;
//Get value of metabox from current id
$codeUnit = get_post_meta($post->ID, 'list_unit_meta_key', true);
//If none selected from metabox, skip it as its a regular page
if( $codeUnit == 'NULL' || !isset($codeUnit) || $codeUnit == '') {
return $content;
}
//if I add echo anything, it shows up twice in head and once in body
// WHY?
//echo $codeUnit;
ob_start();
//If photo included display grid view, else table view
if ($includePhoto == 'on') {
include(plugin_dir_path(__FILE__) . 'views/my-grid.php');
} else {
include(plugin_dir_path(__FILE__) . 'views/my-table.php');
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
```
|
I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I've pasted below, and I do not get duplicated content:
```
function my_module_init() {
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
function my_content_ctrlr( $content ) {
ob_start();
// This file contains only the following simple text for testing purposes: #########
include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' );
$output = ob_get_contents();
ob_end_clean();
// Add our custom code before the existing content.
return $output . $content;
}
```
So, I think that we can rule out my original idea that content was being echoed instead of returned.
Another possibility is that there are additional `apply_filters()` calls on `the_content` somewhere in your site via plugins or the theme. E.g.:
```
echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );
```
It's not uncommon for themes to do that kind of thing, and it would result in `my_content_ctrlr()` being called once for each additional occurrence.
You can use some additional checks as illustrated by this snippet to resolve that problem ([source](https://pippinsplugins.com/playing-nice-with-the-content-filter/)).
```
function pippin_filter_content_sample($content) {
if( is_singular() && is_main_query() ) {
$new_content = '<p>This is added to the bottom of all post and page content, as well as custom post types.</p>';
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'pippin_filter_content_sample');
```
|
238,422 |
<p>As a plugin developer, I want to ensure that my plugin doesn't leave any custom settings left behind from my plugin when upgrading from <code>v1.0</code> to <code>v2.0</code>.</p>
<p>Whenever a user uninstalls my plugin, I've created an <a href="https://developer.wordpress.org/plugins/the-basics/uninstall-methods/" rel="nofollow"><code>uninstall.php</code></a> file (standard practice) which automatically removes all of my plugin's settings for a clean removal:</p>
<pre><code>if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { // Exit if accessed directly
exit;
}
// Remove all plugin options with the prefix "myplugin_"
global $wpdb;
$plugin_options = $wpdb -> get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE 'myplugin_%'" );
foreach( $plugin_options as $option ) {
delete_option( $option -> option_name );
}
</code></pre>
<p>This script automatically removes all options that have the prefix of <code>myplugin_</code> such as:</p>
<pre><code>myplugin_some_option
myplugin_another_option_here
myplugin_yup_this_one_too
etc...
</code></pre>
<p>However, I am already working on a new version of my plugin with new options in my settings page. If a user has an older version of my plugin and is upgrading to the next version without uninstalling it, how do I ensure all of my old plugin options are removed for a clean upgrade? Does the <code>uninstall.php</code> file automatically run when a user is upgrading to a new version of my plugin?</p>
|
[
{
"answer_id": 238438,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I've pasted below, and I do not get duplicated content:</p>\n\n<pre><code>function my_module_init() {\n add_filter('the_content', 'my_content_ctrlr');\n}\nadd_action('init', 'my_module_init');\n\nfunction my_content_ctrlr( $content ) {\n ob_start(); \n\n // This file contains only the following simple text for testing purposes: ######### \n include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' ); \n\n $output = ob_get_contents();\n\n ob_end_clean();\n\n // Add our custom code before the existing content.\n return $output . $content;\n}\n</code></pre>\n\n<p>So, I think that we can rule out my original idea that content was being echoed instead of returned. </p>\n\n<p>Another possibility is that there are additional <code>apply_filters()</code> calls on <code>the_content</code> somewhere in your site via plugins or the theme. E.g.:</p>\n\n<pre><code>echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );\n</code></pre>\n\n<p>It's not uncommon for themes to do that kind of thing, and it would result in <code>my_content_ctrlr()</code> being called once for each additional occurrence.</p>\n\n<p>You can use some additional checks as illustrated by this snippet to resolve that problem (<a href=\"https://pippinsplugins.com/playing-nice-with-the-content-filter/\" rel=\"nofollow\">source</a>).</p>\n\n<pre><code>function pippin_filter_content_sample($content) {\n if( is_singular() && is_main_query() ) {\n $new_content = '<p>This is added to the bottom of all post and page content, as well as custom post types.</p>';\n $content .= $new_content; \n } \n return $content;\n}\nadd_filter('the_content', 'pippin_filter_content_sample');\n</code></pre>\n"
},
{
"answer_id": 238525,
"author": "MediaFormat",
"author_id": 87622,
"author_profile": "https://wordpress.stackexchange.com/users/87622",
"pm_score": -1,
"selected": false,
"text": "<p>Thanks @goto10, the <code>is_main_query</code> didn't work for me but set me in the right direction, adding additional conditional checks. I ended up using <code>in_the_loop</code>:</p>\n\n<pre><code>if (!in_the_loop()){\n return;\n}\n</code></pre>\n"
}
] |
2016/09/06
|
[
"https://wordpress.stackexchange.com/questions/238422",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] |
As a plugin developer, I want to ensure that my plugin doesn't leave any custom settings left behind from my plugin when upgrading from `v1.0` to `v2.0`.
Whenever a user uninstalls my plugin, I've created an [`uninstall.php`](https://developer.wordpress.org/plugins/the-basics/uninstall-methods/) file (standard practice) which automatically removes all of my plugin's settings for a clean removal:
```
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { // Exit if accessed directly
exit;
}
// Remove all plugin options with the prefix "myplugin_"
global $wpdb;
$plugin_options = $wpdb -> get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE 'myplugin_%'" );
foreach( $plugin_options as $option ) {
delete_option( $option -> option_name );
}
```
This script automatically removes all options that have the prefix of `myplugin_` such as:
```
myplugin_some_option
myplugin_another_option_here
myplugin_yup_this_one_too
etc...
```
However, I am already working on a new version of my plugin with new options in my settings page. If a user has an older version of my plugin and is upgrading to the next version without uninstalling it, how do I ensure all of my old plugin options are removed for a clean upgrade? Does the `uninstall.php` file automatically run when a user is upgrading to a new version of my plugin?
|
I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I've pasted below, and I do not get duplicated content:
```
function my_module_init() {
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
function my_content_ctrlr( $content ) {
ob_start();
// This file contains only the following simple text for testing purposes: #########
include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' );
$output = ob_get_contents();
ob_end_clean();
// Add our custom code before the existing content.
return $output . $content;
}
```
So, I think that we can rule out my original idea that content was being echoed instead of returned.
Another possibility is that there are additional `apply_filters()` calls on `the_content` somewhere in your site via plugins or the theme. E.g.:
```
echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );
```
It's not uncommon for themes to do that kind of thing, and it would result in `my_content_ctrlr()` being called once for each additional occurrence.
You can use some additional checks as illustrated by this snippet to resolve that problem ([source](https://pippinsplugins.com/playing-nice-with-the-content-filter/)).
```
function pippin_filter_content_sample($content) {
if( is_singular() && is_main_query() ) {
$new_content = '<p>This is added to the bottom of all post and page content, as well as custom post types.</p>';
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'pippin_filter_content_sample');
```
|
238,461 |
<p>I'm using the Toolset Types plugin to create various custom posts and custom taxonomies. </p>
<p>I have 2 custom post types (Schools, and Productions) that share a common taxonomy (School Subjects). However, on the Schools edit page, I want the title of that taxonomy meta box to say "Subject Wishlist", while leaving the default title on the Productions edit page. So I can't just rename the taxonomy as a whole, because that would change it everywhere.</p>
<p>Any ideas? I have considered the various other answers here covering removing and re-adding metaboxes (eg <a href="https://wordpress.stackexchange.com/questions/39446/change-the-title-of-a-meta-box">this answer</a>). I'm concerned that may not work though, since the Toolset Types plugin generates these metaboxes dynamically (I think?)...</p>
|
[
{
"answer_id": 238560,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>There is a filter called <code>register_taxonomy_args</code> in WP v4.4 that's a big help here. This tested and working example assumes that the post types <code>schools</code> and <code>productions</code> have already been created.</p>\n\n<pre><code>/**\n * Filter the arguments for registering a taxonomy.\n *\n * @since 4.4.0\n *\n * @param array $args Array of arguments for registering a taxonomy.\n * @param string $taxonomy Taxonomy key.\n * @param array $object_type Array of names of object types for the taxonomy.\n */\nadd_filter( 'register_taxonomy_args', 'wpse238461_taxonomy_school_subjects_title_changer', 10, 3 );\nfunction wpse238461_taxonomy_school_subjects_title_changer( $args, $taxonomy, $object_type ) {\n\n // We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.\n if ( ! isset( $_GET['post_type'] ) || ! $_GET['post_type'] ) {\n return $args;\n }\n $post_type = $_GET['post_type'];\n\n /*\n // Bonus code for anyone trying to do this on regular post or page edit screens,\n // $_GET['post_type'] is not set, so do something like this instead of/in addition to the above check\n\n // We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.\n if ( ! isset( $_GET['post'] ) || ! $_GET['post'] ) {\n return $args;\n }\n\n // Get the post type (post or page), bail if we can't. \n $post_type = get_post_type( $_GET['post'] );\n if ( ! $post_type ) {\n return $args;\n } \n */\n\n // Make sure we're looking at the right taxonomy since this filter runs for all of them.\n if ( 'school_subjects' !== $taxonomy ) {\n return $args;\n }\n\n // Check if we're viewing the appropriate post type, and modify the label.\n if ( 'schools' === $post_type ) {\n $args['labels']['name'] = _x( 'Subject Wishlists', 'taxonomy general name', 'textdomain' );\n\n // Alternate example for when taxonomy is using the label argument instead of the entire labels argument:\n // $args['label'] = 'Subject Wishlist';\n }\n\n return $args;\n}\n\n// Taxonomy registration code\nadd_action( 'init', 'create_taxonomy_school_subjects' );\nfunction create_taxonomy_school_subjects() {\n register_taxonomy(\n 'school_subjects',\n array( 'schools', 'productions' ),\n array(\n //'label' => __( 'School Subjects' ),\n 'labels' => array(\n 'name' => _x( 'School Subjects', 'taxonomy general name', 'textdomain' ),\n 'singular_name' => _x( 'School Subject', 'taxonomy singular name', 'textdomain' ),\n 'search_items' => __( 'Search School Subjects', 'textdomain' ),\n 'all_items' => __( 'All School Subjects', 'textdomain' ),\n 'parent_item' => __( 'Parent School Subject', 'textdomain' ),\n 'parent_item_colon' => __( 'Parent School Subject:', 'textdomain' ),\n 'edit_item' => __( 'Edit School Subject', 'textdomain' ),\n 'update_item' => __( 'Update School Subject', 'textdomain' ),\n 'add_new_item' => __( 'Add New School Subject', 'textdomain' ),\n 'new_item_name' => __( 'New School Subject Name', 'textdomain' ),\n 'menu_name' => __( 'School Subjects', 'textdomain' ),\n ),\n 'rewrite' => array( 'slug' => 'school_subjects' ),\n 'hierarchical' => true,\n )\n );\n}\n</code></pre>\n\n<h1>School - Subject Wishlists</h1>\n\n<p><a href=\"https://i.stack.imgur.com/DnqY4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DnqY4.png\" alt=\"School - Subject Wishlists\"></a></p>\n\n<h1>Production - School Subjects</h1>\n\n<p><a href=\"https://i.stack.imgur.com/dsKHd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dsKHd.png\" alt=\"Production - School Subjects\"></a></p>\n"
},
{
"answer_id": 238763,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>There should be no reason to use plugins for meta boxes :(. Using them means that you give away part of your ability to customize things your way.</p>\n\n<p>Still, think it is safe to assume that ids are unlikely to change even if they are dynamically generated so it will be safe to just remove and re-add, or target the label with some JS code.</p>\n\n<p>But.... for me all alarm bells go off when I hear \"It is the same, except for that small difference, so lets just change the label at that specific point\". This in many cases is just the first indication that it is not the same at all, and all you are trying to do is short cut a fuller solution. before doing any coding, you should ask yourself why is it that you want to confuse the admin by having the same information named differently when it is in the menu and when it is in the form? This sounds like at least a bad UX.</p>\n"
}
] |
2016/09/07
|
[
"https://wordpress.stackexchange.com/questions/238461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1118/"
] |
I'm using the Toolset Types plugin to create various custom posts and custom taxonomies.
I have 2 custom post types (Schools, and Productions) that share a common taxonomy (School Subjects). However, on the Schools edit page, I want the title of that taxonomy meta box to say "Subject Wishlist", while leaving the default title on the Productions edit page. So I can't just rename the taxonomy as a whole, because that would change it everywhere.
Any ideas? I have considered the various other answers here covering removing and re-adding metaboxes (eg [this answer](https://wordpress.stackexchange.com/questions/39446/change-the-title-of-a-meta-box)). I'm concerned that may not work though, since the Toolset Types plugin generates these metaboxes dynamically (I think?)...
|
There is a filter called `register_taxonomy_args` in WP v4.4 that's a big help here. This tested and working example assumes that the post types `schools` and `productions` have already been created.
```
/**
* Filter the arguments for registering a taxonomy.
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a taxonomy.
* @param string $taxonomy Taxonomy key.
* @param array $object_type Array of names of object types for the taxonomy.
*/
add_filter( 'register_taxonomy_args', 'wpse238461_taxonomy_school_subjects_title_changer', 10, 3 );
function wpse238461_taxonomy_school_subjects_title_changer( $args, $taxonomy, $object_type ) {
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post_type'] ) || ! $_GET['post_type'] ) {
return $args;
}
$post_type = $_GET['post_type'];
/*
// Bonus code for anyone trying to do this on regular post or page edit screens,
// $_GET['post_type'] is not set, so do something like this instead of/in addition to the above check
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post'] ) || ! $_GET['post'] ) {
return $args;
}
// Get the post type (post or page), bail if we can't.
$post_type = get_post_type( $_GET['post'] );
if ( ! $post_type ) {
return $args;
}
*/
// Make sure we're looking at the right taxonomy since this filter runs for all of them.
if ( 'school_subjects' !== $taxonomy ) {
return $args;
}
// Check if we're viewing the appropriate post type, and modify the label.
if ( 'schools' === $post_type ) {
$args['labels']['name'] = _x( 'Subject Wishlists', 'taxonomy general name', 'textdomain' );
// Alternate example for when taxonomy is using the label argument instead of the entire labels argument:
// $args['label'] = 'Subject Wishlist';
}
return $args;
}
// Taxonomy registration code
add_action( 'init', 'create_taxonomy_school_subjects' );
function create_taxonomy_school_subjects() {
register_taxonomy(
'school_subjects',
array( 'schools', 'productions' ),
array(
//'label' => __( 'School Subjects' ),
'labels' => array(
'name' => _x( 'School Subjects', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'School Subject', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search School Subjects', 'textdomain' ),
'all_items' => __( 'All School Subjects', 'textdomain' ),
'parent_item' => __( 'Parent School Subject', 'textdomain' ),
'parent_item_colon' => __( 'Parent School Subject:', 'textdomain' ),
'edit_item' => __( 'Edit School Subject', 'textdomain' ),
'update_item' => __( 'Update School Subject', 'textdomain' ),
'add_new_item' => __( 'Add New School Subject', 'textdomain' ),
'new_item_name' => __( 'New School Subject Name', 'textdomain' ),
'menu_name' => __( 'School Subjects', 'textdomain' ),
),
'rewrite' => array( 'slug' => 'school_subjects' ),
'hierarchical' => true,
)
);
}
```
School - Subject Wishlists
==========================
[](https://i.stack.imgur.com/DnqY4.png)
Production - School Subjects
============================
[](https://i.stack.imgur.com/dsKHd.png)
|
238,477 |
<p>I know we have the following command available in <code>WP-CLI</code> to remove transients</p>
<pre><code># Delete all transients
$ wp transient delete-all
</code></pre>
<p>However, my question is does it remove transients on all sites over multi sites? If not how can we remove transients on all sites?</p>
|
[
{
"answer_id": 238560,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>There is a filter called <code>register_taxonomy_args</code> in WP v4.4 that's a big help here. This tested and working example assumes that the post types <code>schools</code> and <code>productions</code> have already been created.</p>\n\n<pre><code>/**\n * Filter the arguments for registering a taxonomy.\n *\n * @since 4.4.0\n *\n * @param array $args Array of arguments for registering a taxonomy.\n * @param string $taxonomy Taxonomy key.\n * @param array $object_type Array of names of object types for the taxonomy.\n */\nadd_filter( 'register_taxonomy_args', 'wpse238461_taxonomy_school_subjects_title_changer', 10, 3 );\nfunction wpse238461_taxonomy_school_subjects_title_changer( $args, $taxonomy, $object_type ) {\n\n // We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.\n if ( ! isset( $_GET['post_type'] ) || ! $_GET['post_type'] ) {\n return $args;\n }\n $post_type = $_GET['post_type'];\n\n /*\n // Bonus code for anyone trying to do this on regular post or page edit screens,\n // $_GET['post_type'] is not set, so do something like this instead of/in addition to the above check\n\n // We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.\n if ( ! isset( $_GET['post'] ) || ! $_GET['post'] ) {\n return $args;\n }\n\n // Get the post type (post or page), bail if we can't. \n $post_type = get_post_type( $_GET['post'] );\n if ( ! $post_type ) {\n return $args;\n } \n */\n\n // Make sure we're looking at the right taxonomy since this filter runs for all of them.\n if ( 'school_subjects' !== $taxonomy ) {\n return $args;\n }\n\n // Check if we're viewing the appropriate post type, and modify the label.\n if ( 'schools' === $post_type ) {\n $args['labels']['name'] = _x( 'Subject Wishlists', 'taxonomy general name', 'textdomain' );\n\n // Alternate example for when taxonomy is using the label argument instead of the entire labels argument:\n // $args['label'] = 'Subject Wishlist';\n }\n\n return $args;\n}\n\n// Taxonomy registration code\nadd_action( 'init', 'create_taxonomy_school_subjects' );\nfunction create_taxonomy_school_subjects() {\n register_taxonomy(\n 'school_subjects',\n array( 'schools', 'productions' ),\n array(\n //'label' => __( 'School Subjects' ),\n 'labels' => array(\n 'name' => _x( 'School Subjects', 'taxonomy general name', 'textdomain' ),\n 'singular_name' => _x( 'School Subject', 'taxonomy singular name', 'textdomain' ),\n 'search_items' => __( 'Search School Subjects', 'textdomain' ),\n 'all_items' => __( 'All School Subjects', 'textdomain' ),\n 'parent_item' => __( 'Parent School Subject', 'textdomain' ),\n 'parent_item_colon' => __( 'Parent School Subject:', 'textdomain' ),\n 'edit_item' => __( 'Edit School Subject', 'textdomain' ),\n 'update_item' => __( 'Update School Subject', 'textdomain' ),\n 'add_new_item' => __( 'Add New School Subject', 'textdomain' ),\n 'new_item_name' => __( 'New School Subject Name', 'textdomain' ),\n 'menu_name' => __( 'School Subjects', 'textdomain' ),\n ),\n 'rewrite' => array( 'slug' => 'school_subjects' ),\n 'hierarchical' => true,\n )\n );\n}\n</code></pre>\n\n<h1>School - Subject Wishlists</h1>\n\n<p><a href=\"https://i.stack.imgur.com/DnqY4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DnqY4.png\" alt=\"School - Subject Wishlists\"></a></p>\n\n<h1>Production - School Subjects</h1>\n\n<p><a href=\"https://i.stack.imgur.com/dsKHd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dsKHd.png\" alt=\"Production - School Subjects\"></a></p>\n"
},
{
"answer_id": 238763,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>There should be no reason to use plugins for meta boxes :(. Using them means that you give away part of your ability to customize things your way.</p>\n\n<p>Still, think it is safe to assume that ids are unlikely to change even if they are dynamically generated so it will be safe to just remove and re-add, or target the label with some JS code.</p>\n\n<p>But.... for me all alarm bells go off when I hear \"It is the same, except for that small difference, so lets just change the label at that specific point\". This in many cases is just the first indication that it is not the same at all, and all you are trying to do is short cut a fuller solution. before doing any coding, you should ask yourself why is it that you want to confuse the admin by having the same information named differently when it is in the menu and when it is in the form? This sounds like at least a bad UX.</p>\n"
}
] |
2016/09/07
|
[
"https://wordpress.stackexchange.com/questions/238477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101396/"
] |
I know we have the following command available in `WP-CLI` to remove transients
```
# Delete all transients
$ wp transient delete-all
```
However, my question is does it remove transients on all sites over multi sites? If not how can we remove transients on all sites?
|
There is a filter called `register_taxonomy_args` in WP v4.4 that's a big help here. This tested and working example assumes that the post types `schools` and `productions` have already been created.
```
/**
* Filter the arguments for registering a taxonomy.
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a taxonomy.
* @param string $taxonomy Taxonomy key.
* @param array $object_type Array of names of object types for the taxonomy.
*/
add_filter( 'register_taxonomy_args', 'wpse238461_taxonomy_school_subjects_title_changer', 10, 3 );
function wpse238461_taxonomy_school_subjects_title_changer( $args, $taxonomy, $object_type ) {
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post_type'] ) || ! $_GET['post_type'] ) {
return $args;
}
$post_type = $_GET['post_type'];
/*
// Bonus code for anyone trying to do this on regular post or page edit screens,
// $_GET['post_type'] is not set, so do something like this instead of/in addition to the above check
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post'] ) || ! $_GET['post'] ) {
return $args;
}
// Get the post type (post or page), bail if we can't.
$post_type = get_post_type( $_GET['post'] );
if ( ! $post_type ) {
return $args;
}
*/
// Make sure we're looking at the right taxonomy since this filter runs for all of them.
if ( 'school_subjects' !== $taxonomy ) {
return $args;
}
// Check if we're viewing the appropriate post type, and modify the label.
if ( 'schools' === $post_type ) {
$args['labels']['name'] = _x( 'Subject Wishlists', 'taxonomy general name', 'textdomain' );
// Alternate example for when taxonomy is using the label argument instead of the entire labels argument:
// $args['label'] = 'Subject Wishlist';
}
return $args;
}
// Taxonomy registration code
add_action( 'init', 'create_taxonomy_school_subjects' );
function create_taxonomy_school_subjects() {
register_taxonomy(
'school_subjects',
array( 'schools', 'productions' ),
array(
//'label' => __( 'School Subjects' ),
'labels' => array(
'name' => _x( 'School Subjects', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'School Subject', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search School Subjects', 'textdomain' ),
'all_items' => __( 'All School Subjects', 'textdomain' ),
'parent_item' => __( 'Parent School Subject', 'textdomain' ),
'parent_item_colon' => __( 'Parent School Subject:', 'textdomain' ),
'edit_item' => __( 'Edit School Subject', 'textdomain' ),
'update_item' => __( 'Update School Subject', 'textdomain' ),
'add_new_item' => __( 'Add New School Subject', 'textdomain' ),
'new_item_name' => __( 'New School Subject Name', 'textdomain' ),
'menu_name' => __( 'School Subjects', 'textdomain' ),
),
'rewrite' => array( 'slug' => 'school_subjects' ),
'hierarchical' => true,
)
);
}
```
School - Subject Wishlists
==========================
[](https://i.stack.imgur.com/DnqY4.png)
Production - School Subjects
============================
[](https://i.stack.imgur.com/dsKHd.png)
|
238,530 |
<p>I have a custom <code>WP_Users_Query</code> that I have been using on a site.</p>
<p>It has worked fine for a while. I went to add some pagination to the query using the <code>number</code> parameter <a href="https://codex.wordpress.org/Class_Reference/WP_User_Query#Pagination_Parameters" rel="nofollow">as per the docs here</a>. But for some reason, when I add that parameter I get an SQL error, unless I set it to <code>-1</code> where it returns everything.</p>
<p>Here is my code that works:</p>
<pre><code>$user_fields = array( 'ID', 'display_name', 'user_email' );
$args = array(
'role__in' => array('Subcriber', 'Editor'),
'meta_query' => array(
array(
'key' => 'list_in_directory',
'value' => 1,
'compare' => '='
)
),
'fields' => $user_fields,
'paged' => get_query_var('paged')
); // End Args
if ($args){
$user_query = new WP_User_Query( $args );
}
</code></pre>
<p>If I add the line:<code>'number' => '2'</code> to my args array (I have tried it both as a string and an integer, both with the same result) I get this error in my log:</p>
<blockquote>
<p>WordPress database error You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near '-2, 2' at line 15 for query
<code>SELECT SQL_CALC_FOUND_ROWS wp_users.ID,wp_users.display_name,wp_users.user_email FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 AND (
(
(
( wp_usermeta.meta_key = 'list_in_directory' AND wp_usermeta.meta_value = '1' )
)
AND
(
(
( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Subcriber\"%' )
OR
( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Editor\"%' )
)
)
)
) ORDER BY user_login ASC LIMIT -2, 2 made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/pand/page-templates/membership-directory.php'), WP_User_Query->__construct, WP_User_Query->query</code></p>
</blockquote>
<p>Also, I have tried using different numbers in place of 2 all with the same result. The only time I don't get the error is if I set it to -1. Then it works just fine(but no pagination).</p>
<p>I'm scratching my head on this one so any help would be much appreciated!</p>
|
[
{
"answer_id": 238504,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p><code>$_SERVER['REQUEST_URI']</code> is your only option. wordpress failed parsing the url so not much you can get from the API</p>\n"
},
{
"answer_id": 238506,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>You can redirect specific <code>$_SERVER['REQUEST_URI']</code> to <code>yoursite.com/not_found</code></p>\n"
}
] |
2016/09/07
|
[
"https://wordpress.stackexchange.com/questions/238530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102389/"
] |
I have a custom `WP_Users_Query` that I have been using on a site.
It has worked fine for a while. I went to add some pagination to the query using the `number` parameter [as per the docs here](https://codex.wordpress.org/Class_Reference/WP_User_Query#Pagination_Parameters). But for some reason, when I add that parameter I get an SQL error, unless I set it to `-1` where it returns everything.
Here is my code that works:
```
$user_fields = array( 'ID', 'display_name', 'user_email' );
$args = array(
'role__in' => array('Subcriber', 'Editor'),
'meta_query' => array(
array(
'key' => 'list_in_directory',
'value' => 1,
'compare' => '='
)
),
'fields' => $user_fields,
'paged' => get_query_var('paged')
); // End Args
if ($args){
$user_query = new WP_User_Query( $args );
}
```
If I add the line:`'number' => '2'` to my args array (I have tried it both as a string and an integer, both with the same result) I get this error in my log:
>
> WordPress database error You have an error in your SQL syntax;
> check the manual that corresponds to your MySQL server version for the right syntax to use near '-2, 2' at line 15 for query
> `SELECT SQL_CALC_FOUND_ROWS wp_users.ID,wp_users.display_name,wp_users.user_email FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 AND (
> (
> (
> ( wp_usermeta.meta_key = 'list_in_directory' AND wp_usermeta.meta_value = '1' )
> )
> AND
> (
> (
> ( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Subcriber\"%' )
> OR
> ( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Editor\"%' )
> )
> )
> )
> ) ORDER BY user_login ASC LIMIT -2, 2 made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/pand/page-templates/membership-directory.php'), WP_User_Query->__construct, WP_User_Query->query`
>
>
>
Also, I have tried using different numbers in place of 2 all with the same result. The only time I don't get the error is if I set it to -1. Then it works just fine(but no pagination).
I'm scratching my head on this one so any help would be much appreciated!
|
`$_SERVER['REQUEST_URI']` is your only option. wordpress failed parsing the url so not much you can get from the API
|
238,535 |
<p>I'm using the <a href="https://wordpress.org/plugins/cpt-onomies/" rel="nofollow">CPT-onomies plugin</a> to make a CPT into a taxonomy. I have a hero image CPT (created with <em>CPT-onomies</em>) and the hero images post type is attached to the page post type. This allows me to select a hero image post that will be a term of a page post. All of this is working fine. When I visit the page with the hero image as a taxonomy the hero image appears as desired.</p>
<p>What I'm trying to accomplish is that if I'm on a page whose ancestor has a hero image attached, I want the page to show the hero image attached to the parent. Below is my code. I get an array of ancestors and iterate through the array. The image shows up as desired but above the image this error appears:</p>
<blockquote>
<p><strong>Notice: Undefined property</strong>: <code>stdClass::$data</code> in <code>.../wp-includes/category-template.php</code> on <em>line 1176</em></p>
</blockquote>
<pre><code>//Get the current Post ID
$current_post_id = get_the_id();
//Get the current Post's ancestor's ID's
$current_post_parents = get_ancestors($current_post_id, 'page');
foreach ( $current_post_parents as $post_parent ) {
//If a hero image ID is associated with the current post being viewed (or a parent post of the current post) assign that hero image ID value to $hero_image_id
$hero_image_id = isset( $post_parent ) && ( $assigned_hero_images = get_the_terms( $post_parent, 'hero_images' ) ) && is_array( $assigned_hero_images ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;
if ($hero_image_id)
break;
} //Code follows that displays the image based on the $hero_image_id
</code></pre>
<p>It's the <code>get_the_terms()</code> function that's throwing the error. Line 1176 of the <code>category-template.php</code> file is <code>$to_cache[ $key ] = $term->data;</code></p>
<p>To be clear, the notice only appears when I'm visiting a child page whose ancestor has a hero image attached. If I'm visiting the page on which the hero image is attached or visiting a page with no hero image attached on the page or any ancestor page then no error appears.</p>
|
[
{
"answer_id": 238543,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem lies with this line:</p>\n\n<p><code>$hero_image_id = isset( $post_parent ) && ( $assigned_hero_images = get_the_terms( $post_parent, 'hero_images' ) ) && is_array( $assigned_hero_images ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;</code></p>\n\n<p>I think I see what you're going for, but PHP is not processing it in the order you think it is.</p>\n\n<p>Let me try to break this down:</p>\n\n<pre><code>isset( $post_parent ) // This isn't necessary since it couldn't not exist and still get into this code block.\n\n$assigned_hero_images = get_the_terms( $post_parent, 'hero_images' )\n\nis_array( $assigned_hero_images ) // again, you just created it, so you don't need to check here.\n\n$hero_image = array_shift( $assigned_hero_images ) // You're trying to access the contents of the first element of the array, but this isn't the best approach.\n\n$hero_image->term_id\n</code></pre>\n\n<p>A cleaned up version that accomplishes what you're doing above would look like this:</p>\n\n<pre><code>$hero_image_id = get_the_terms( $post_parent, 'hero_images')[0]->$term_id;\n</code></pre>\n\n<p>The <code>[0]</code> gets you access to the first array element, and <code>->$term_id</code> gets that property from the object. You can do this without saving each to a variable by a process in php called <a href=\"http://php.net/manual/en/language.types.array.php\" rel=\"nofollow\">array dereferencing</a>.</p>\n\n<p>This is not tested so I may have missed something, but hopefully it gets you in the ballpark enough to troubleshoot it out from here.</p>\n"
},
{
"answer_id": 238607,
"author": "TKEz",
"author_id": 83438,
"author_profile": "https://wordpress.stackexchange.com/users/83438",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up using the <code>wp_get_object_terms()</code> function instead of <code>get_the_terms()</code>. The <code>get_the_terms()</code> function attempts to cache the terms where <code>wp_get_object_terms()</code> does not.</p>\n\n<p>The fixed code to get the hero images CPT's ID is: </p>\n\n<pre><code>$hero_image_id = ( $assigned_hero_images = wp_get_object_terms( $post_parent, 'hero_images' ) ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;\n</code></pre>\n"
}
] |
2016/09/07
|
[
"https://wordpress.stackexchange.com/questions/238535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83438/"
] |
I'm using the [CPT-onomies plugin](https://wordpress.org/plugins/cpt-onomies/) to make a CPT into a taxonomy. I have a hero image CPT (created with *CPT-onomies*) and the hero images post type is attached to the page post type. This allows me to select a hero image post that will be a term of a page post. All of this is working fine. When I visit the page with the hero image as a taxonomy the hero image appears as desired.
What I'm trying to accomplish is that if I'm on a page whose ancestor has a hero image attached, I want the page to show the hero image attached to the parent. Below is my code. I get an array of ancestors and iterate through the array. The image shows up as desired but above the image this error appears:
>
> **Notice: Undefined property**: `stdClass::$data` in `.../wp-includes/category-template.php` on *line 1176*
>
>
>
```
//Get the current Post ID
$current_post_id = get_the_id();
//Get the current Post's ancestor's ID's
$current_post_parents = get_ancestors($current_post_id, 'page');
foreach ( $current_post_parents as $post_parent ) {
//If a hero image ID is associated with the current post being viewed (or a parent post of the current post) assign that hero image ID value to $hero_image_id
$hero_image_id = isset( $post_parent ) && ( $assigned_hero_images = get_the_terms( $post_parent, 'hero_images' ) ) && is_array( $assigned_hero_images ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;
if ($hero_image_id)
break;
} //Code follows that displays the image based on the $hero_image_id
```
It's the `get_the_terms()` function that's throwing the error. Line 1176 of the `category-template.php` file is `$to_cache[ $key ] = $term->data;`
To be clear, the notice only appears when I'm visiting a child page whose ancestor has a hero image attached. If I'm visiting the page on which the hero image is attached or visiting a page with no hero image attached on the page or any ancestor page then no error appears.
|
I ended up using the `wp_get_object_terms()` function instead of `get_the_terms()`. The `get_the_terms()` function attempts to cache the terms where `wp_get_object_terms()` does not.
The fixed code to get the hero images CPT's ID is:
```
$hero_image_id = ( $assigned_hero_images = wp_get_object_terms( $post_parent, 'hero_images' ) ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;
```
|
238,547 |
<p>I want to dequeue a script ('enterprise-responsive-menu'), but the function I have in my template does not do that. Does anything look wrong? </p>
<p>Here is the enqueue in functions.php-</p>
<pre><code>//* Enqueue Scripts
add_action( 'wp_enqueue_scripts', 'enterprise_load_scripts' );
function enterprise_load_scripts() {
wp_enqueue_script( 'enterprise-responsive-menu', get_bloginfo( 'stylesheet_directory' ) . '/js/responsive-menu.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Lato:300,700,300italic|Titillium+Web:600', array(), CHILD_THEME_VERSION );
}'
</code></pre>
<p>Here is the dequeue code in my template -</p>
<pre><code>//Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
</code></pre>
|
[
{
"answer_id": 238549,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Move your <code>project_dequeue_unnecessary_scripts()</code> function to your <code>functions.php</code> file and add a conditional statement to determine if the appropriate template is being loaded. E.g.:</p>\n\n<pre><code>// Remove Mobile Header\nfunction project_dequeue_unnecessary_scripts() {\n if ( is_page_template( 'name-of-template.php' ) ) {\n wp_dequeue_script( 'enterprise-responsive-menu' );\n wp_deregister_script( 'enterprise-responsive-menu' );\n }\n}\nadd_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );\n</code></pre>\n\n<p>I suspect that your function is not working because it has been placed somewhere after the call to <code>get_header()</code> in the template file which means it would be too late to dequeue the script. Declaring functions in template files is not a good practice anyway, so use your <code>functions.php</code> file or another include. </p>\n"
},
{
"answer_id": 238552,
"author": "Rituparna sonowal",
"author_id": 71232,
"author_profile": "https://wordpress.stackexchange.com/users/71232",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action( 'wp_enqueue_scripts', 'enterprise_load_scripts' );\nfunction enterprise_load_scripts(){\n if ( !is_page_template( 'name-of-template.php' ) ) {\n wp_enqueue_script( 'enterprise-responsive-menu', get_bloginfo( 'stylesheet_directory' ) . '/js/responsive-menu.js', array( 'jquery' ), '1.0.0' );\n }\n wp_enqueue_style( 'dashicons' );\n wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Lato:300,700,300italic|Titillium+Web:600', array(), CHILD_THEME_VERSION ); \n}\n</code></pre>\n\n<p>Instead of dequeue, what if you put that specific script in a condition so that it loads only on pages with any template except those where you don't want to..</p>\n"
}
] |
2016/09/07
|
[
"https://wordpress.stackexchange.com/questions/238547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102397/"
] |
I want to dequeue a script ('enterprise-responsive-menu'), but the function I have in my template does not do that. Does anything look wrong?
Here is the enqueue in functions.php-
```
//* Enqueue Scripts
add_action( 'wp_enqueue_scripts', 'enterprise_load_scripts' );
function enterprise_load_scripts() {
wp_enqueue_script( 'enterprise-responsive-menu', get_bloginfo( 'stylesheet_directory' ) . '/js/responsive-menu.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Lato:300,700,300italic|Titillium+Web:600', array(), CHILD_THEME_VERSION );
}'
```
Here is the dequeue code in my template -
```
//Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
```
|
Move your `project_dequeue_unnecessary_scripts()` function to your `functions.php` file and add a conditional statement to determine if the appropriate template is being loaded. E.g.:
```
// Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
if ( is_page_template( 'name-of-template.php' ) ) {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
```
I suspect that your function is not working because it has been placed somewhere after the call to `get_header()` in the template file which means it would be too late to dequeue the script. Declaring functions in template files is not a good practice anyway, so use your `functions.php` file or another include.
|
238,555 |
<p>I set up and configured a WordPress site using WooCommerce. When I was developing, I imported the dummy data for testing.</p>
<p>How can I remove the dummy data to delivery?</p>
|
[
{
"answer_id": 238549,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Move your <code>project_dequeue_unnecessary_scripts()</code> function to your <code>functions.php</code> file and add a conditional statement to determine if the appropriate template is being loaded. E.g.:</p>\n\n<pre><code>// Remove Mobile Header\nfunction project_dequeue_unnecessary_scripts() {\n if ( is_page_template( 'name-of-template.php' ) ) {\n wp_dequeue_script( 'enterprise-responsive-menu' );\n wp_deregister_script( 'enterprise-responsive-menu' );\n }\n}\nadd_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );\n</code></pre>\n\n<p>I suspect that your function is not working because it has been placed somewhere after the call to <code>get_header()</code> in the template file which means it would be too late to dequeue the script. Declaring functions in template files is not a good practice anyway, so use your <code>functions.php</code> file or another include. </p>\n"
},
{
"answer_id": 238552,
"author": "Rituparna sonowal",
"author_id": 71232,
"author_profile": "https://wordpress.stackexchange.com/users/71232",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action( 'wp_enqueue_scripts', 'enterprise_load_scripts' );\nfunction enterprise_load_scripts(){\n if ( !is_page_template( 'name-of-template.php' ) ) {\n wp_enqueue_script( 'enterprise-responsive-menu', get_bloginfo( 'stylesheet_directory' ) . '/js/responsive-menu.js', array( 'jquery' ), '1.0.0' );\n }\n wp_enqueue_style( 'dashicons' );\n wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Lato:300,700,300italic|Titillium+Web:600', array(), CHILD_THEME_VERSION ); \n}\n</code></pre>\n\n<p>Instead of dequeue, what if you put that specific script in a condition so that it loads only on pages with any template except those where you don't want to..</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238555",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83673/"
] |
I set up and configured a WordPress site using WooCommerce. When I was developing, I imported the dummy data for testing.
How can I remove the dummy data to delivery?
|
Move your `project_dequeue_unnecessary_scripts()` function to your `functions.php` file and add a conditional statement to determine if the appropriate template is being loaded. E.g.:
```
// Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
if ( is_page_template( 'name-of-template.php' ) ) {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
```
I suspect that your function is not working because it has been placed somewhere after the call to `get_header()` in the template file which means it would be too late to dequeue the script. Declaring functions in template files is not a good practice anyway, so use your `functions.php` file or another include.
|
238,587 |
<p>I am configuring Git along with my WP development environment, and I was wondering what should be tracked and what should be ignored. If it makes sense to track plugins and for WP core. Create one repo for both theme & plugins?</p>
<p>Common sense would suggest that tracking WP as a whole, is overkill and unuseful, as I am not involved in core development and updates; of course, I want to track my theme/child-theme folder where my work is. Plugins?</p>
<p>So I wonder what is the suggested setup, how many repositories and what to track/ignore</p>
<p>References:</p>
<p><a href="https://wordpress.stackexchange.com/questions/128164/how-should-i-structure-a-wp-website-project-using-git-and-updating-from-wp-dashb">How should I structure a WP website project using git and updating from WP dashboard?</a></p>
<p><a href="https://wordpress.stackexchange.com/questions/205999/what-is-the-best-way-to-setup-wordpress-development-environment-for-freelancers">What is the best way to setup wordpress development environment for freelancers with version control?</a></p>
|
[
{
"answer_id": 238592,
"author": "Kenya Sullivan",
"author_id": 92563,
"author_profile": "https://wordpress.stackexchange.com/users/92563",
"pm_score": 2,
"selected": false,
"text": "<p>This is subjective and depends on what you are trying to achieve. A theme developer may have a different requirement than a plugin developer. Here is a good gist of a <a href=\"https://gist.github.com/salcode/9940509\" rel=\"nofollow noreferrer\">bare minimum .gitignore file for a WordPress install</a>.</p>\n\n<pre><code># -----------------------------------------------------------------\n# .gitignore for WordPress @salcode\n# ver 20160309\n#\n# From the root of your project run\n# curl -Ohttps://gist.githubusercontent.com/salcode/b515f520d3f8207ecd04/raw/.gitignore\n# to download this file\n#\n# By default all files are ignored. You'll need to whitelist\n# any mu-plugins, plugins, or themes you want to include in the repo.\n#\n# ignore everything in the root except the \"wp-content\" directory.\n/*\n!wp-content/\n\n# ignore everything in the \"wp-content\" directory, except:\n# mu-plugins, plugins, and themes directories\nwp-content/*\n!wp-content/mu-plugins/\n!wp-content/plugins/\n!wp-content/themes/\n\n# ignore all mu-plugins, plugins, and themes\n# unless explicitly whitelisted at the end of this file\nwp-content/mu-plugins/*\nwp-content/plugins/*\nwp-content/themes/*\n\n# ignore all files starting with . or ~\n.*\n~*\n\n# ignore node dependency directories (used by grunt)\nnode_modules/\n\n# ignore OS generated files\nehthumbs.db\nThumbs.db\n\n# ignore Editor files\n*.sublime-project\n*.sublime-workspace\n*.komodoproject\n\n# ignore log files and databases\n*.log\n*.sql\n*.sqlite\n\n# ignore compiled files\n*.com\n*.class\n*.dll\n*.exe\n*.o\n*.so\n\n# ignore packaged files\n*.7z\n*.dmg\n*.gz\n*.iso\n*.jar\n*.rar\n*.tar\n*.zip\n\n# -------------------------\n# BEGIN Whitelisted Files\n# -------------------------\n\n# track these files, if they exist\n!.gitignore\n!.editorconfig\n!README.md\n!CHANGELOG.md\n!composer.json\n\n# track these mu-plugins, plugins, and themes\n# add your own entries here\n!wp-content/mu-plugins/example-mu-plugin/\n!wp-content/plugins/example-plugin/\n!wp-content/themes/example-theme/\n</code></pre>\n"
},
{
"answer_id": 238593,
"author": "skndstry",
"author_id": 87327,
"author_profile": "https://wordpress.stackexchange.com/users/87327",
"pm_score": 3,
"selected": false,
"text": "<p>Basically ignore everything except your theme folder and custom plugins. sample .gitignore: </p>\n\n<pre><code>wp-admin/\nwp-includes/\n.htaccess\nindex.php\nlicense.txt\nliesmich.html\nreadme.html\nwp-activate.php\nwp-blog-header.php\nwp-comments-post.php\nwp-config.php\nwp-config-sample.php\nwp-config-stage.php\nwp-config-live.php\nwp-config-dev.php\nwp-config-production.php\nwp-cron.php\nwp-links-opml.php\nwp-load.php\nwp-login.php\nwp-mail.php\nwp-settings.php\nwp-signup.php\nwp-trackback.php\nxmlrpc.php\nconfig/\nwp-content/plugins/\nwp-content/mu-plugins/\nwp-content/languages/\nwp-content/uploads/\nwp-content/upgrade/\nwp-content/themes/*\n\n# don't ignore the theme you're using\n!wp-content/themes/yourthemename\n</code></pre>\n\n<p>This makes the most sense when used together with composer for installing wordpress and plugins.</p>\n"
},
{
"answer_id": 384874,
"author": "sbddesign",
"author_id": 196922,
"author_profile": "https://wordpress.stackexchange.com/users/196922",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on the situation. However, in my view, Git versioning a WordPress site is often more hassle than it's worth. The reason is because tracking the state of the site can not be distilled down to merely the code that sits on your server; it also depends on the contents of the database. Unless you have a scheme to include some kind of database export in with your version control, it's not really a true way of tracking the site's state.</p>\n<p>For most of my WordPress installs, I might have one custom developed theme/child theme and one custom developed plugin. These each get version controlled in their own Git repo. I make git commits from my local development environment and push changes to production via SSH, SFTP, or whatever makes sense for this specific server.</p>\n<p>For production environment, I setup automated off-site backups of the <code>/wp-content</code> folder and the MySQL database.</p>\n<p>This might not be exactly the answer you were looking for. However, in my experience, this has worked best for me in managing countless WordPress sites. I would love it if WordPress sites supported composer packages in a more native way, but ultimately, it's a different kind of animal.</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
] |
I am configuring Git along with my WP development environment, and I was wondering what should be tracked and what should be ignored. If it makes sense to track plugins and for WP core. Create one repo for both theme & plugins?
Common sense would suggest that tracking WP as a whole, is overkill and unuseful, as I am not involved in core development and updates; of course, I want to track my theme/child-theme folder where my work is. Plugins?
So I wonder what is the suggested setup, how many repositories and what to track/ignore
References:
[How should I structure a WP website project using git and updating from WP dashboard?](https://wordpress.stackexchange.com/questions/128164/how-should-i-structure-a-wp-website-project-using-git-and-updating-from-wp-dashb)
[What is the best way to setup wordpress development environment for freelancers with version control?](https://wordpress.stackexchange.com/questions/205999/what-is-the-best-way-to-setup-wordpress-development-environment-for-freelancers)
|
Basically ignore everything except your theme folder and custom plugins. sample .gitignore:
```
wp-admin/
wp-includes/
.htaccess
index.php
license.txt
liesmich.html
readme.html
wp-activate.php
wp-blog-header.php
wp-comments-post.php
wp-config.php
wp-config-sample.php
wp-config-stage.php
wp-config-live.php
wp-config-dev.php
wp-config-production.php
wp-cron.php
wp-links-opml.php
wp-load.php
wp-login.php
wp-mail.php
wp-settings.php
wp-signup.php
wp-trackback.php
xmlrpc.php
config/
wp-content/plugins/
wp-content/mu-plugins/
wp-content/languages/
wp-content/uploads/
wp-content/upgrade/
wp-content/themes/*
# don't ignore the theme you're using
!wp-content/themes/yourthemename
```
This makes the most sense when used together with composer for installing wordpress and plugins.
|
238,589 |
<p>I have several categories post:</p>
<pre><code>General
News
Comedy
Competitions
Culture
Gaming
Food
etc
</code></pre>
<p>The posts url are in the following format:</p>
<pre><code>www.mydomain.com/category-name/post-title
</code></pre>
<p>Example:</p>
<pre><code>www.mydomain.com/food/how-to-make-paella
www.mydomain.com/gaming/game-of-theday
</code></pre>
<p>But I would like to hide from the URL the category name 'general' so for example.</p>
<p>instead of </p>
<pre><code>www.mydomain.com/general/how-to-learn-spanish
</code></pre>
<p>have</p>
<pre><code>www.mydomain.com/how-to-learn-spanish
</code></pre>
<p>I have tried some wiring a rewrite rule in the .htaccess but doesn't work.</p>
<p>Any idea how can I do it?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 238592,
"author": "Kenya Sullivan",
"author_id": 92563,
"author_profile": "https://wordpress.stackexchange.com/users/92563",
"pm_score": 2,
"selected": false,
"text": "<p>This is subjective and depends on what you are trying to achieve. A theme developer may have a different requirement than a plugin developer. Here is a good gist of a <a href=\"https://gist.github.com/salcode/9940509\" rel=\"nofollow noreferrer\">bare minimum .gitignore file for a WordPress install</a>.</p>\n\n<pre><code># -----------------------------------------------------------------\n# .gitignore for WordPress @salcode\n# ver 20160309\n#\n# From the root of your project run\n# curl -Ohttps://gist.githubusercontent.com/salcode/b515f520d3f8207ecd04/raw/.gitignore\n# to download this file\n#\n# By default all files are ignored. You'll need to whitelist\n# any mu-plugins, plugins, or themes you want to include in the repo.\n#\n# ignore everything in the root except the \"wp-content\" directory.\n/*\n!wp-content/\n\n# ignore everything in the \"wp-content\" directory, except:\n# mu-plugins, plugins, and themes directories\nwp-content/*\n!wp-content/mu-plugins/\n!wp-content/plugins/\n!wp-content/themes/\n\n# ignore all mu-plugins, plugins, and themes\n# unless explicitly whitelisted at the end of this file\nwp-content/mu-plugins/*\nwp-content/plugins/*\nwp-content/themes/*\n\n# ignore all files starting with . or ~\n.*\n~*\n\n# ignore node dependency directories (used by grunt)\nnode_modules/\n\n# ignore OS generated files\nehthumbs.db\nThumbs.db\n\n# ignore Editor files\n*.sublime-project\n*.sublime-workspace\n*.komodoproject\n\n# ignore log files and databases\n*.log\n*.sql\n*.sqlite\n\n# ignore compiled files\n*.com\n*.class\n*.dll\n*.exe\n*.o\n*.so\n\n# ignore packaged files\n*.7z\n*.dmg\n*.gz\n*.iso\n*.jar\n*.rar\n*.tar\n*.zip\n\n# -------------------------\n# BEGIN Whitelisted Files\n# -------------------------\n\n# track these files, if they exist\n!.gitignore\n!.editorconfig\n!README.md\n!CHANGELOG.md\n!composer.json\n\n# track these mu-plugins, plugins, and themes\n# add your own entries here\n!wp-content/mu-plugins/example-mu-plugin/\n!wp-content/plugins/example-plugin/\n!wp-content/themes/example-theme/\n</code></pre>\n"
},
{
"answer_id": 238593,
"author": "skndstry",
"author_id": 87327,
"author_profile": "https://wordpress.stackexchange.com/users/87327",
"pm_score": 3,
"selected": false,
"text": "<p>Basically ignore everything except your theme folder and custom plugins. sample .gitignore: </p>\n\n<pre><code>wp-admin/\nwp-includes/\n.htaccess\nindex.php\nlicense.txt\nliesmich.html\nreadme.html\nwp-activate.php\nwp-blog-header.php\nwp-comments-post.php\nwp-config.php\nwp-config-sample.php\nwp-config-stage.php\nwp-config-live.php\nwp-config-dev.php\nwp-config-production.php\nwp-cron.php\nwp-links-opml.php\nwp-load.php\nwp-login.php\nwp-mail.php\nwp-settings.php\nwp-signup.php\nwp-trackback.php\nxmlrpc.php\nconfig/\nwp-content/plugins/\nwp-content/mu-plugins/\nwp-content/languages/\nwp-content/uploads/\nwp-content/upgrade/\nwp-content/themes/*\n\n# don't ignore the theme you're using\n!wp-content/themes/yourthemename\n</code></pre>\n\n<p>This makes the most sense when used together with composer for installing wordpress and plugins.</p>\n"
},
{
"answer_id": 384874,
"author": "sbddesign",
"author_id": 196922,
"author_profile": "https://wordpress.stackexchange.com/users/196922",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on the situation. However, in my view, Git versioning a WordPress site is often more hassle than it's worth. The reason is because tracking the state of the site can not be distilled down to merely the code that sits on your server; it also depends on the contents of the database. Unless you have a scheme to include some kind of database export in with your version control, it's not really a true way of tracking the site's state.</p>\n<p>For most of my WordPress installs, I might have one custom developed theme/child theme and one custom developed plugin. These each get version controlled in their own Git repo. I make git commits from my local development environment and push changes to production via SSH, SFTP, or whatever makes sense for this specific server.</p>\n<p>For production environment, I setup automated off-site backups of the <code>/wp-content</code> folder and the MySQL database.</p>\n<p>This might not be exactly the answer you were looking for. However, in my experience, this has worked best for me in managing countless WordPress sites. I would love it if WordPress sites supported composer packages in a more native way, but ultimately, it's a different kind of animal.</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65640/"
] |
I have several categories post:
```
General
News
Comedy
Competitions
Culture
Gaming
Food
etc
```
The posts url are in the following format:
```
www.mydomain.com/category-name/post-title
```
Example:
```
www.mydomain.com/food/how-to-make-paella
www.mydomain.com/gaming/game-of-theday
```
But I would like to hide from the URL the category name 'general' so for example.
instead of
```
www.mydomain.com/general/how-to-learn-spanish
```
have
```
www.mydomain.com/how-to-learn-spanish
```
I have tried some wiring a rewrite rule in the .htaccess but doesn't work.
Any idea how can I do it?
Thanks!
|
Basically ignore everything except your theme folder and custom plugins. sample .gitignore:
```
wp-admin/
wp-includes/
.htaccess
index.php
license.txt
liesmich.html
readme.html
wp-activate.php
wp-blog-header.php
wp-comments-post.php
wp-config.php
wp-config-sample.php
wp-config-stage.php
wp-config-live.php
wp-config-dev.php
wp-config-production.php
wp-cron.php
wp-links-opml.php
wp-load.php
wp-login.php
wp-mail.php
wp-settings.php
wp-signup.php
wp-trackback.php
xmlrpc.php
config/
wp-content/plugins/
wp-content/mu-plugins/
wp-content/languages/
wp-content/uploads/
wp-content/upgrade/
wp-content/themes/*
# don't ignore the theme you're using
!wp-content/themes/yourthemename
```
This makes the most sense when used together with composer for installing wordpress and plugins.
|
238,600 |
<p>I have comments enabled on my site but the form isn't appearing. It worked at one point as there are comments on some of my posts with links to them but they don't appear on the page.</p>
<p>Take this post: <a href="https://arcath.net/2016/03/react/" rel="noreferrer">https://arcath.net/2016/03/react/</a> The theme is clearly showing 1 comment at the top of the page.</p>
<p>Comments are enabled in <code>Settings -> Discussion</code></p>
<p><a href="https://i.stack.imgur.com/YjNpc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YjNpc.png" alt="Discussion Settings"></a></p>
<p><a href="https://i.stack.imgur.com/xrxb3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xrxb3.png" alt="Post Options"></a></p>
<p>I've read a lot of forum posts on the subject that lead me to these settings but I can't see anything wrong with them.</p>
|
[
{
"answer_id": 238602,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Stupid question :</strong> \nIs it possible that your theme doesn't include the comments on display?</p>\n\n<p>In addition to settings, your theme must display comments.</p>\n\n<p>The default function provided by WP is <a href=\"https://developer.wordpress.org/reference/functions/comments_template/\" rel=\"nofollow\">comments_template</a> (to use on single.php and/or page.php) :</p>\n\n<pre><code>\n comments_template( '', true );\n</code></pre>\n\n<p><strong>UPDATE ---------------------------------------------------</strong></p>\n\n<p>I believe there is something wrong with the theme \"hueman\".</p>\n\n<p>I installed it on a local WP containing sample contents.</p>\n\n<p>When I go to an article containing comments, I have the exact same result as you get.</p>\n\n<p>If I display the exact same article using a different theme (one of the defaults provided), the comments are displayed.</p>\n\n<p>So I checked the single.php template file of the hueman theme and it use a custom function ( hu_is_checked('post-comments') ).\nUsed in: </p>\n\n<pre><code>if ( hu_is_checked('post-comments') ) { comments_template('/comments.php',true); }</code></pre>\n\n<p>The problem is: it return null (so the comments can't be displayed).</p>\n\n<p>According to the theme documentation, we should be able to customize the theme options through the customizer\n<a href=\"http://docs.presscustomizr.com/article/113-customizr-theme-options-comments\" rel=\"nofollow\">http://docs.presscustomizr.com/article/113-customizr-theme-options-comments</a>\nThis option is located in : Customizer > Content Panel > Comments</p>\n\n<p>Unfortunatly I wasn't able to found it : \nI tried on front page, single post, page, never saw it.</p>\n\n<p>So, since the option is not defined, the custom function will always return null.</p>\n\n<p>A quick fix would be to create a child theme of hueman, overwrite single.php template and change the line for:</p>\n\n<pre><code>comments_template('/comments.php',true);</code></pre>\n\n<p>I tested it, it works.</p>\n\n<p>A better solution would be to contact the theme author to see if we missed something or if it's a bug.</p>\n"
},
{
"answer_id": 238604,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 2,
"selected": false,
"text": "<p>Follow three steps : </p>\n\n<ol>\n<li><p>Can you check in your post edit page. Many themes have an Meta Box with an option to enable and disable Comments in post's edit page.</p></li>\n<li><p>If you have checked there and still is is not coming then please check your theme's file if comments_template is there or not. </p></li>\n<li><p>If it is there, then are you using any comments related plugin such as Disqus or Facebook Comments. Please try deactivating those.</p></li>\n</ol>\n\n<p>Hope with the above option you will get your solution.</p>\n"
},
{
"answer_id": 324097,
"author": "Susan",
"author_id": 157894,
"author_profile": "https://wordpress.stackexchange.com/users/157894",
"pm_score": 2,
"selected": false,
"text": "<p>I just had to post this as I was going thru the same thing. I'd edited the post that \"came with\" the initial set up. Seeing as the post was from a year ago, I thought I'd 'post date' it (pun intended). But the comments box wouldn't show up. So, I created a brand-new post, and left the publish date as of right now, actual time. The comments box showed up. I created another post, left it at the immediate time, and hey presto, it worked. I even switched themes to see and yes, the comments box(es) were there on the two posts. So, don't back date something and see if that works for you!</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85357/"
] |
I have comments enabled on my site but the form isn't appearing. It worked at one point as there are comments on some of my posts with links to them but they don't appear on the page.
Take this post: <https://arcath.net/2016/03/react/> The theme is clearly showing 1 comment at the top of the page.
Comments are enabled in `Settings -> Discussion`
[](https://i.stack.imgur.com/YjNpc.png)
[](https://i.stack.imgur.com/xrxb3.png)
I've read a lot of forum posts on the subject that lead me to these settings but I can't see anything wrong with them.
|
**Stupid question :**
Is it possible that your theme doesn't include the comments on display?
In addition to settings, your theme must display comments.
The default function provided by WP is [comments\_template](https://developer.wordpress.org/reference/functions/comments_template/) (to use on single.php and/or page.php) :
```
comments_template( '', true );
```
**UPDATE ---------------------------------------------------**
I believe there is something wrong with the theme "hueman".
I installed it on a local WP containing sample contents.
When I go to an article containing comments, I have the exact same result as you get.
If I display the exact same article using a different theme (one of the defaults provided), the comments are displayed.
So I checked the single.php template file of the hueman theme and it use a custom function ( hu\_is\_checked('post-comments') ).
Used in:
```
if ( hu_is_checked('post-comments') ) { comments_template('/comments.php',true); }
```
The problem is: it return null (so the comments can't be displayed).
According to the theme documentation, we should be able to customize the theme options through the customizer
<http://docs.presscustomizr.com/article/113-customizr-theme-options-comments>
This option is located in : Customizer > Content Panel > Comments
Unfortunatly I wasn't able to found it :
I tried on front page, single post, page, never saw it.
So, since the option is not defined, the custom function will always return null.
A quick fix would be to create a child theme of hueman, overwrite single.php template and change the line for:
```
comments_template('/comments.php',true);
```
I tested it, it works.
A better solution would be to contact the theme author to see if we missed something or if it's a bug.
|
238,606 |
<p>I created a custom table 'products' with the following field:title,description,url.The items stored into the table are imported.</p>
<p>I would like to extends the wordpress search to this table.
Is it possible to do this?</p>
|
[
{
"answer_id": 238602,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Stupid question :</strong> \nIs it possible that your theme doesn't include the comments on display?</p>\n\n<p>In addition to settings, your theme must display comments.</p>\n\n<p>The default function provided by WP is <a href=\"https://developer.wordpress.org/reference/functions/comments_template/\" rel=\"nofollow\">comments_template</a> (to use on single.php and/or page.php) :</p>\n\n<pre><code>\n comments_template( '', true );\n</code></pre>\n\n<p><strong>UPDATE ---------------------------------------------------</strong></p>\n\n<p>I believe there is something wrong with the theme \"hueman\".</p>\n\n<p>I installed it on a local WP containing sample contents.</p>\n\n<p>When I go to an article containing comments, I have the exact same result as you get.</p>\n\n<p>If I display the exact same article using a different theme (one of the defaults provided), the comments are displayed.</p>\n\n<p>So I checked the single.php template file of the hueman theme and it use a custom function ( hu_is_checked('post-comments') ).\nUsed in: </p>\n\n<pre><code>if ( hu_is_checked('post-comments') ) { comments_template('/comments.php',true); }</code></pre>\n\n<p>The problem is: it return null (so the comments can't be displayed).</p>\n\n<p>According to the theme documentation, we should be able to customize the theme options through the customizer\n<a href=\"http://docs.presscustomizr.com/article/113-customizr-theme-options-comments\" rel=\"nofollow\">http://docs.presscustomizr.com/article/113-customizr-theme-options-comments</a>\nThis option is located in : Customizer > Content Panel > Comments</p>\n\n<p>Unfortunatly I wasn't able to found it : \nI tried on front page, single post, page, never saw it.</p>\n\n<p>So, since the option is not defined, the custom function will always return null.</p>\n\n<p>A quick fix would be to create a child theme of hueman, overwrite single.php template and change the line for:</p>\n\n<pre><code>comments_template('/comments.php',true);</code></pre>\n\n<p>I tested it, it works.</p>\n\n<p>A better solution would be to contact the theme author to see if we missed something or if it's a bug.</p>\n"
},
{
"answer_id": 238604,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 2,
"selected": false,
"text": "<p>Follow three steps : </p>\n\n<ol>\n<li><p>Can you check in your post edit page. Many themes have an Meta Box with an option to enable and disable Comments in post's edit page.</p></li>\n<li><p>If you have checked there and still is is not coming then please check your theme's file if comments_template is there or not. </p></li>\n<li><p>If it is there, then are you using any comments related plugin such as Disqus or Facebook Comments. Please try deactivating those.</p></li>\n</ol>\n\n<p>Hope with the above option you will get your solution.</p>\n"
},
{
"answer_id": 324097,
"author": "Susan",
"author_id": 157894,
"author_profile": "https://wordpress.stackexchange.com/users/157894",
"pm_score": 2,
"selected": false,
"text": "<p>I just had to post this as I was going thru the same thing. I'd edited the post that \"came with\" the initial set up. Seeing as the post was from a year ago, I thought I'd 'post date' it (pun intended). But the comments box wouldn't show up. So, I created a brand-new post, and left the publish date as of right now, actual time. The comments box showed up. I created another post, left it at the immediate time, and hey presto, it worked. I even switched themes to see and yes, the comments box(es) were there on the two posts. So, don't back date something and see if that works for you!</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238606",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102441/"
] |
I created a custom table 'products' with the following field:title,description,url.The items stored into the table are imported.
I would like to extends the wordpress search to this table.
Is it possible to do this?
|
**Stupid question :**
Is it possible that your theme doesn't include the comments on display?
In addition to settings, your theme must display comments.
The default function provided by WP is [comments\_template](https://developer.wordpress.org/reference/functions/comments_template/) (to use on single.php and/or page.php) :
```
comments_template( '', true );
```
**UPDATE ---------------------------------------------------**
I believe there is something wrong with the theme "hueman".
I installed it on a local WP containing sample contents.
When I go to an article containing comments, I have the exact same result as you get.
If I display the exact same article using a different theme (one of the defaults provided), the comments are displayed.
So I checked the single.php template file of the hueman theme and it use a custom function ( hu\_is\_checked('post-comments') ).
Used in:
```
if ( hu_is_checked('post-comments') ) { comments_template('/comments.php',true); }
```
The problem is: it return null (so the comments can't be displayed).
According to the theme documentation, we should be able to customize the theme options through the customizer
<http://docs.presscustomizr.com/article/113-customizr-theme-options-comments>
This option is located in : Customizer > Content Panel > Comments
Unfortunatly I wasn't able to found it :
I tried on front page, single post, page, never saw it.
So, since the option is not defined, the custom function will always return null.
A quick fix would be to create a child theme of hueman, overwrite single.php template and change the line for:
```
comments_template('/comments.php',true);
```
I tested it, it works.
A better solution would be to contact the theme author to see if we missed something or if it's a bug.
|
238,640 |
<p>Looking through the <a href="https://developer.wordpress.org/reference/functions/is_page_template/" rel="noreferrer">Wordpress documentation</a>, it says that <code>is_page_template()</code> compares against a "template name", if one is provided.</p>
<p>I have a template stored in <code>page-homepage.php</code> called <code>Homepage</code>:</p>
<pre><code>/*
* Template Name: Homepage
* Description: The template for displaying the homepage
*/
</code></pre>
<p>And I have some code I wish to run in my functions.php when I'm using that template:</p>
<pre><code>if (is_page_template('Homepage')) {
...
</code></pre>
<p>But it isn't being triggered when I'm on a page which uses that template.</p>
<p>When I look at the code that Wordpress executes for <code>is_page_template()</code>, it looks like it actually checks for the document name, not the template name...?</p>
<pre><code>function is_page_template( $template = '' ) {
$page_template = get_page_template_slug( get_queried_object_id() );
if ( $template == $page_template )
return true;
</code></pre>
<p>In my instance it seems that <code>$page_template</code> is <code>page-homepage.php</code> -- not the template name, like the documentation suggests...?</p>
<p>Am I doing something wrong?</p>
|
[
{
"answer_id": 238642,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 5,
"selected": true,
"text": "<p>Your condition should be written like this:</p>\n<pre><code>if (is_page_template('path/file.php')) { \n // Do stuff\n}\n</code></pre>\n<p>I believe the confusion is a result of two things:</p>\n<ol>\n<li>The docs refer to "name" ambiguously. Specifying "file name" would make the documentation much more clear.</li>\n<li>The code behind <code>is_page_template()</code> shows the <code>get_page_template_slug()</code> function at its core. This function actually returns a file name, not the template slug. <a href=\"https://codex.wordpress.org/Function_Reference/get_page_template_slug\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_page_template_slug</a></li>\n</ol>\n<p>When specifying an argument for the <code>is_page_template()</code> function (as in the example above), the file path is relative to the theme root.</p>\n<p>This function will not work inside the loop.</p>\n<p>EDIT: an important issue to note here as well. The <code>is_page_template()</code> function will return empty/false if the page is using the default template from the hierarchy. If a custom template is not assigned, you must use another method, such as <code>basename(get_page_template())</code>. See Jacob's answer here for more details: <a href=\"https://wordpress.stackexchange.com/a/328427/45202\">https://wordpress.stackexchange.com/a/328427/45202</a></p>\n"
},
{
"answer_id": 238643,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 3,
"selected": false,
"text": "<p>I think the best thing to say is, it checks on the FILE name and in your case it would be page-homepage.php. so:</p>\n<pre><code>if (is_page_template('page-homepage.php')) { \n ...\n</code></pre>\n<p>Other things to think of is if the template file is actually stored within another folder inside the theme. <a href=\"https://developer.wordpress.org/reference/functions/is_page_template/#more-information\" rel=\"noreferrer\">read more</a></p>\n<p>One more thing, the <code>Template Name: Homepage</code> is genrally whats used to identify the template when creating a page or post.</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4109/"
] |
Looking through the [Wordpress documentation](https://developer.wordpress.org/reference/functions/is_page_template/), it says that `is_page_template()` compares against a "template name", if one is provided.
I have a template stored in `page-homepage.php` called `Homepage`:
```
/*
* Template Name: Homepage
* Description: The template for displaying the homepage
*/
```
And I have some code I wish to run in my functions.php when I'm using that template:
```
if (is_page_template('Homepage')) {
...
```
But it isn't being triggered when I'm on a page which uses that template.
When I look at the code that Wordpress executes for `is_page_template()`, it looks like it actually checks for the document name, not the template name...?
```
function is_page_template( $template = '' ) {
$page_template = get_page_template_slug( get_queried_object_id() );
if ( $template == $page_template )
return true;
```
In my instance it seems that `$page_template` is `page-homepage.php` -- not the template name, like the documentation suggests...?
Am I doing something wrong?
|
Your condition should be written like this:
```
if (is_page_template('path/file.php')) {
// Do stuff
}
```
I believe the confusion is a result of two things:
1. The docs refer to "name" ambiguously. Specifying "file name" would make the documentation much more clear.
2. The code behind `is_page_template()` shows the `get_page_template_slug()` function at its core. This function actually returns a file name, not the template slug. <https://codex.wordpress.org/Function_Reference/get_page_template_slug>
When specifying an argument for the `is_page_template()` function (as in the example above), the file path is relative to the theme root.
This function will not work inside the loop.
EDIT: an important issue to note here as well. The `is_page_template()` function will return empty/false if the page is using the default template from the hierarchy. If a custom template is not assigned, you must use another method, such as `basename(get_page_template())`. See Jacob's answer here for more details: <https://wordpress.stackexchange.com/a/328427/45202>
|
238,645 |
<p>I'm using the catch-base theme as a parent theme and have the following code in functions.php </p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'catch-base';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-theme',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p>I for-the-life-of-me cannot figure out how to overwrite any of the template files through the child theme. I have tried the suggestion on the catchthemes website, <a href="https://catchthemes.com/blog/create-child-theme-wordpress/" rel="nofollow">https://catchthemes.com/blog/create-child-theme-wordpress/</a> but just using the same directory structure isn't working.</p>
<p>I've also tried adding this code after the "add_action" function, but it breaks the site and gives an "access denied" error.</p>
<pre><code>require_once( get_stylesheet_directory() . '/inc/catchbase-structure.php' );
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 238649,
"author": "Brandon",
"author_id": 102030,
"author_profile": "https://wordpress.stackexchange.com/users/102030",
"pm_score": 2,
"selected": false,
"text": "<p>The catch-base theme wraps every function in an if statement to make it easy to modify if necessary.</p>\n\n<p>Example....</p>\n\n<pre><code>if (! function_exists('function_name')) { \n /* some code */\n}\n</code></pre>\n\n<p>So what I ended up doing was adding this to my functions.php file in the child theme and it overwrote the function and the extra divs that I added showed up!</p>\n\n<pre><code>function function_name() {\n /* some modified code */\n}\n</code></pre>\n"
},
{
"answer_id": 386130,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>Child themes let you override template files that are loaded via the template hierarchy or <code>get_template_part</code> such as <code>index.php</code> or <code>archive.php</code>.</p>\n<p>Child themes cannot be used this way to replace arbitrary files such as CSS files, <code>functions.php</code>, files included ussing <code>require</code> or <code>include</code>, etc</p>\n<p>If the parent theme contains functions you want to remove or replace, these are your options:</p>\n<ul>\n<li>unhook the filter or action if it's added in the parent theme ( be mindful that the order things happen in is important, you can't unhook something if it hasn't been added yet! )</li>\n<li>redefine it if the parent theme has wrapped the function in conditional checks ( not always possible, inspect parent theme code to check )</li>\n<li>turn the functionality off if the parent theme provides a setting</li>\n<li>dequeue any enqueued scripts or styles you do not want ( be mindful of order/priority, you can't dequeue something that hasn't been enqueued yet! Order matters! )</li>\n<li>contact parent theme author</li>\n<li>fork parent theme</li>\n</ul>\n<p>Sadly there is no generic PHP/WP method to remove and replace an arbitrary PHP function. If there is no mechanism provided for doing it then it can't be done.</p>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102030/"
] |
I'm using the catch-base theme as a parent theme and have the following code in functions.php
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'catch-base';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-theme',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
I for-the-life-of-me cannot figure out how to overwrite any of the template files through the child theme. I have tried the suggestion on the catchthemes website, <https://catchthemes.com/blog/create-child-theme-wordpress/> but just using the same directory structure isn't working.
I've also tried adding this code after the "add\_action" function, but it breaks the site and gives an "access denied" error.
```
require_once( get_stylesheet_directory() . '/inc/catchbase-structure.php' );
```
What am I missing?
|
The catch-base theme wraps every function in an if statement to make it easy to modify if necessary.
Example....
```
if (! function_exists('function_name')) {
/* some code */
}
```
So what I ended up doing was adding this to my functions.php file in the child theme and it overwrote the function and the extra divs that I added showed up!
```
function function_name() {
/* some modified code */
}
```
|
238,647 |
<p>I have an anchor link on my product pages to a div further down the page. The div only shows if there is content in it.</p>
<p>Is it possible to write an if statement for the link based on the div ID? If #ID exists? </p>
<p>This is the div:</p>
<pre><code><div class="upsells products" id="tab-accessories">
<!--Change related products text-->
<?php
global $post;
//If Product Page is a Model page, display "Reccomended Accessories"
if ( has_term( 'Models', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Reccomended Accessories' . '</h2>';
}
//If Product Page is an Accessories page, display "Customers Also Bought"
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Customers Also Bought' . '</h2>';
}
?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
</div>
</code></pre>
<p>This is the link:</p>
<pre><code> <li><a href="#tab-accessories">Accessories</a></li>
</code></pre>
|
[
{
"answer_id": 238694,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>You're approach this the wrong way, I think. Even before you are outputting the link and the div in your template you should have a condition that tests whether there is anything to show in the loop. You are now running that test inside the div: <code>$products->have_posts()</code>. Unfortunately, since that loop is specific to WooCommerce I don't know which test to use.</p>\n\n<p>If there is nothing to show, your template should not include link and div. That is better than trying to repair it afterwards with css and/or javascript.</p>\n"
},
{
"answer_id": 238740,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>This can be done but we need to see the if statement that is around your div. Right now you that code above will still present the div, just not the content IN the div. You need to wrap that link code in the same if statement that your div is in.</p>\n\n<p>example: if your div if statement is:</p>\n\n<pre><code>if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {\necho '<div class=\"upsells products\" id=\"tab-accessories\">CONTENT OF DIV</div>';\n}\n</code></pre>\n\n<p>wrap your link earlier in the code with the same if statement:</p>\n\n<pre><code>if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {\necho '<li><a href=\"#tab-accessories\">Accessories</a></li>';\n}\n</code></pre>\n\n<p>whatever happens to one will be the same as the other.</p>\n"
},
{
"answer_id": 238776,
"author": "Roshan Deshapriya",
"author_id": 97402,
"author_profile": "https://wordpress.stackexchange.com/users/97402",
"pm_score": 0,
"selected": false,
"text": "<p>use the jquery method.</p>\n\n<pre>\n \n $(window).load(function(){\n if ($('your_div').is(\":empty\")){\n $('your_div').hide();\n } });\n \n</pre>\n"
}
] |
2016/09/08
|
[
"https://wordpress.stackexchange.com/questions/238647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85805/"
] |
I have an anchor link on my product pages to a div further down the page. The div only shows if there is content in it.
Is it possible to write an if statement for the link based on the div ID? If #ID exists?
This is the div:
```
<div class="upsells products" id="tab-accessories">
<!--Change related products text-->
<?php
global $post;
//If Product Page is a Model page, display "Reccomended Accessories"
if ( has_term( 'Models', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Reccomended Accessories' . '</h2>';
}
//If Product Page is an Accessories page, display "Customers Also Bought"
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Customers Also Bought' . '</h2>';
}
?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
</div>
```
This is the link:
```
<li><a href="#tab-accessories">Accessories</a></li>
```
|
This can be done but we need to see the if statement that is around your div. Right now you that code above will still present the div, just not the content IN the div. You need to wrap that link code in the same if statement that your div is in.
example: if your div if statement is:
```
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<div class="upsells products" id="tab-accessories">CONTENT OF DIV</div>';
}
```
wrap your link earlier in the code with the same if statement:
```
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<li><a href="#tab-accessories">Accessories</a></li>';
}
```
whatever happens to one will be the same as the other.
|
238,672 |
<p>I've noticed plugins using a singleton pattern that will use WordPress's <code>_doing_it_wrong()</code> function in their <code>clone()</code> methods, like so:</p>
<pre><code><?php
public function __clone() {
_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'divlibrary' ), $this->version );
}
?>
</code></pre>
<p>But I also noticed this warning/notice on WordPress's official documentation:
<a href="https://i.stack.imgur.com/JViCx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JViCx.png" alt="enter image description here"></a></p>
<p>It really doesn't matter when, how a developer is using it, WordPress is advocating that it shouldn't be used, so I'm wondering what is the correct way to do this within custom plugins? The method is used for deprecating code but in this instance the developer is just wanting to send a warning/alert out.</p>
<p><strong>Reference:</strong> <a href="https://developer.wordpress.org/reference/functions/_doing_it_wrong/" rel="noreferrer">https://developer.wordpress.org/reference/functions/_doing_it_wrong/</a></p>
|
[
{
"answer_id": 263996,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>What is an alternative method to the WordPress private _doing_it_wrong() function?</p>\n</blockquote>\n\n<p>There's no way that WordPress is ever going to get rid of the <code>_doing_it_wrong()</code> function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called <code>doing_it_wrong()</code> that is copy and pasted from <code>_doing_it_wrong()</code>.</p>\n\n<p>Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as <code>_doing_it_wrong()</code>.</p>\n\n<pre><code>class deprecated {\n protected $method;\n protected $message;\n protected $version;\n\n public function method( $method ) {\n $this->method = $method;\n return $this;\n }\n\n public function message( $message ) {\n $this->message = $message;\n return $this;\n }\n\n public function version( $version ) {\n $this->version = sprintf( \n __( 'This message was added in version %1$s.' ), \n $version\n );\n return $this;\n }\n\n public function trigger_error() {\n do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );\n if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {\n trigger_error( sprintf( \n __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),\n isset( $this->method ) ? $this->method : '', \n isset( $this->message ) ? $this->message : '', \n isset( $this->version ) ? $this->version : ''\n ) );\n }\n }\n}\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>class wpse_238672 {\n public function some_deprecated_method() {\n ( new deprecated() )\n ->method( __METHOD__ )\n ->message( __( \n 'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'\n ) )\n ->version( '2.3.4' )\n ->trigger_error();\n\n $this->non_deprecated_method();\n }\n\n public function non_deprecated_method() {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 370071,
"author": "John B",
"author_id": 67684,
"author_profile": "https://wordpress.stackexchange.com/users/67684",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/_doing_it_wrong/#changelog\" rel=\"nofollow noreferrer\">As of WordPress 5.4</a> <code>_doing_it_wrong()</code> is no longer marked private, so it looks like we can just use it.</p>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12691/"
] |
I've noticed plugins using a singleton pattern that will use WordPress's `_doing_it_wrong()` function in their `clone()` methods, like so:
```
<?php
public function __clone() {
_doing_it_wrong( __FUNCTION__, __( 'Cheatin’ huh?', 'divlibrary' ), $this->version );
}
?>
```
But I also noticed this warning/notice on WordPress's official documentation:
[](https://i.stack.imgur.com/JViCx.png)
It really doesn't matter when, how a developer is using it, WordPress is advocating that it shouldn't be used, so I'm wondering what is the correct way to do this within custom plugins? The method is used for deprecating code but in this instance the developer is just wanting to send a warning/alert out.
**Reference:** <https://developer.wordpress.org/reference/functions/_doing_it_wrong/>
|
>
> What is an alternative method to the WordPress private \_doing\_it\_wrong() function?
>
>
>
There's no way that WordPress is ever going to get rid of the `_doing_it_wrong()` function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called `doing_it_wrong()` that is copy and pasted from `_doing_it_wrong()`.
Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as `_doing_it_wrong()`.
```
class deprecated {
protected $method;
protected $message;
protected $version;
public function method( $method ) {
$this->method = $method;
return $this;
}
public function message( $message ) {
$this->message = $message;
return $this;
}
public function version( $version ) {
$this->version = sprintf(
__( 'This message was added in version %1$s.' ),
$version
);
return $this;
}
public function trigger_error() {
do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );
if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
trigger_error( sprintf(
__( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
isset( $this->method ) ? $this->method : '',
isset( $this->message ) ? $this->message : '',
isset( $this->version ) ? $this->version : ''
) );
}
}
}
```
### Usage
```
class wpse_238672 {
public function some_deprecated_method() {
( new deprecated() )
->method( __METHOD__ )
->message( __(
'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'
) )
->version( '2.3.4' )
->trigger_error();
$this->non_deprecated_method();
}
public function non_deprecated_method() {
}
}
```
|
238,679 |
<p>I've been working with the <code>wp_list_categories( $args );</code> to display categories from a taxonomy and I feel that this might be the wrong method to use. Now I'm wondering if it is possible to instead of having the categories outputted into an unordered list, they are outputted as individual div elements for each category. Is there a better alternative to doing this?</p>
<pre><code><?php
$args = array(
'show_option_none' => __( 'No treatment categories' ),
'taxonomy' => 'treatment-categories',
'title_li' => __( 'Treatment Categories' )
);
wp_list_categories( $args );
?>
</code></pre>
<p>My original prototype of the site is using a grid system with individual columns for each category.</p>
<p><a href="https://i.stack.imgur.com/DNI6T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNI6T.png" alt="Original site prototype demonstrating what I need to accomplish"></a></p>
<p>I have worked with <code>get_categories( $args );</code> and I was able to accommplish what was expected, however I had an issue of trying to link to each category when a user would click on the 'View Treatment' button, it would take the user to the 404 page. Here was the template I was building when I was working with <code>get_categories( $args );</code>.</p>
<pre><code><?php get_header(); ?>
<section class="hero hero-sml hero-default no-marg-bottom">
<div class="container clearfix">
<h1>Treatments</h1>
</div><!-- .container -->
</section><!-- .hero -->
<section class="margin-top container clearfix">
<div class="row">
<?php
$args = array(
'taxonomy' => 'treatment-categories',
);
$categories = get_categories( $args );
foreach( $categories as $category ) {
?>
<div class="col-4 treatment-category">
<h3>
<?php echo $category->name; ?>
</h3>
<p>
<?php echo $category->description; ?>
</p>
<p>
<a class="btn btn-sml btn-clr btn-primary" href="<?php echo esc_url( $category_link ); ?>">
View treatments
</a>
</p>
</div><!-- .col-4 -->
<?php
}
?>
</div><!-- .row -->
</section><!-- .container -->
<?php get_footer(); ?>
</code></pre>
<p>Any help on how I can achieve this will be greatly appreciated as I've been stuck on this for a couple of weeks.</p>
|
[
{
"answer_id": 263996,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>What is an alternative method to the WordPress private _doing_it_wrong() function?</p>\n</blockquote>\n\n<p>There's no way that WordPress is ever going to get rid of the <code>_doing_it_wrong()</code> function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called <code>doing_it_wrong()</code> that is copy and pasted from <code>_doing_it_wrong()</code>.</p>\n\n<p>Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as <code>_doing_it_wrong()</code>.</p>\n\n<pre><code>class deprecated {\n protected $method;\n protected $message;\n protected $version;\n\n public function method( $method ) {\n $this->method = $method;\n return $this;\n }\n\n public function message( $message ) {\n $this->message = $message;\n return $this;\n }\n\n public function version( $version ) {\n $this->version = sprintf( \n __( 'This message was added in version %1$s.' ), \n $version\n );\n return $this;\n }\n\n public function trigger_error() {\n do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );\n if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {\n trigger_error( sprintf( \n __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),\n isset( $this->method ) ? $this->method : '', \n isset( $this->message ) ? $this->message : '', \n isset( $this->version ) ? $this->version : ''\n ) );\n }\n }\n}\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>class wpse_238672 {\n public function some_deprecated_method() {\n ( new deprecated() )\n ->method( __METHOD__ )\n ->message( __( \n 'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'\n ) )\n ->version( '2.3.4' )\n ->trigger_error();\n\n $this->non_deprecated_method();\n }\n\n public function non_deprecated_method() {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 370071,
"author": "John B",
"author_id": 67684,
"author_profile": "https://wordpress.stackexchange.com/users/67684",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/_doing_it_wrong/#changelog\" rel=\"nofollow noreferrer\">As of WordPress 5.4</a> <code>_doing_it_wrong()</code> is no longer marked private, so it looks like we can just use it.</p>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238679",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93077/"
] |
I've been working with the `wp_list_categories( $args );` to display categories from a taxonomy and I feel that this might be the wrong method to use. Now I'm wondering if it is possible to instead of having the categories outputted into an unordered list, they are outputted as individual div elements for each category. Is there a better alternative to doing this?
```
<?php
$args = array(
'show_option_none' => __( 'No treatment categories' ),
'taxonomy' => 'treatment-categories',
'title_li' => __( 'Treatment Categories' )
);
wp_list_categories( $args );
?>
```
My original prototype of the site is using a grid system with individual columns for each category.
[](https://i.stack.imgur.com/DNI6T.png)
I have worked with `get_categories( $args );` and I was able to accommplish what was expected, however I had an issue of trying to link to each category when a user would click on the 'View Treatment' button, it would take the user to the 404 page. Here was the template I was building when I was working with `get_categories( $args );`.
```
<?php get_header(); ?>
<section class="hero hero-sml hero-default no-marg-bottom">
<div class="container clearfix">
<h1>Treatments</h1>
</div><!-- .container -->
</section><!-- .hero -->
<section class="margin-top container clearfix">
<div class="row">
<?php
$args = array(
'taxonomy' => 'treatment-categories',
);
$categories = get_categories( $args );
foreach( $categories as $category ) {
?>
<div class="col-4 treatment-category">
<h3>
<?php echo $category->name; ?>
</h3>
<p>
<?php echo $category->description; ?>
</p>
<p>
<a class="btn btn-sml btn-clr btn-primary" href="<?php echo esc_url( $category_link ); ?>">
View treatments
</a>
</p>
</div><!-- .col-4 -->
<?php
}
?>
</div><!-- .row -->
</section><!-- .container -->
<?php get_footer(); ?>
```
Any help on how I can achieve this will be greatly appreciated as I've been stuck on this for a couple of weeks.
|
>
> What is an alternative method to the WordPress private \_doing\_it\_wrong() function?
>
>
>
There's no way that WordPress is ever going to get rid of the `_doing_it_wrong()` function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called `doing_it_wrong()` that is copy and pasted from `_doing_it_wrong()`.
Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as `_doing_it_wrong()`.
```
class deprecated {
protected $method;
protected $message;
protected $version;
public function method( $method ) {
$this->method = $method;
return $this;
}
public function message( $message ) {
$this->message = $message;
return $this;
}
public function version( $version ) {
$this->version = sprintf(
__( 'This message was added in version %1$s.' ),
$version
);
return $this;
}
public function trigger_error() {
do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );
if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
trigger_error( sprintf(
__( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
isset( $this->method ) ? $this->method : '',
isset( $this->message ) ? $this->message : '',
isset( $this->version ) ? $this->version : ''
) );
}
}
}
```
### Usage
```
class wpse_238672 {
public function some_deprecated_method() {
( new deprecated() )
->method( __METHOD__ )
->message( __(
'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'
) )
->version( '2.3.4' )
->trigger_error();
$this->non_deprecated_method();
}
public function non_deprecated_method() {
}
}
```
|
238,680 |
<p>I am using following codes to show title of a post in another post.But it shows only post id.How to solve this?</p>
<pre><code><?php $home_team_name = rwmb_meta( 'pb_select_home_team', 'type=select_advanced', get_the_ID() ); ?>
<?php echo esc_html( $home_team_name ); ?>
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 238681,
"author": "user3114253",
"author_id": 76325,
"author_profile": "https://wordpress.stackexchange.com/users/76325",
"pm_score": 0,
"selected": false,
"text": "<p>Generally we use <code>the_title()</code> or <code>echo get_the_title()</code> to print title</p>\n\n<p>try </p>\n\n<pre><code>echo get_the_title();\n</code></pre>\n\n<p>or </p>\n\n<pre><code>echo get_the_title( get_the_ID() );\n</code></pre>\n"
},
{
"answer_id": 238682,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 4,
"selected": true,
"text": "<p>Because you're outside the loop, you'll need to either know the post id of the title you want and specify it in the function parameter, or call the global $post variable if you're on the page (just not in the loop yet).</p>\n\n<pre><code>global $post\n\necho get_the_title($post->ID);\n\nor\n\necho get_the_title(2);\n</code></pre>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83330/"
] |
I am using following codes to show title of a post in another post.But it shows only post id.How to solve this?
```
<?php $home_team_name = rwmb_meta( 'pb_select_home_team', 'type=select_advanced', get_the_ID() ); ?>
<?php echo esc_html( $home_team_name ); ?>
```
Thanks
|
Because you're outside the loop, you'll need to either know the post id of the title you want and specify it in the function parameter, or call the global $post variable if you're on the page (just not in the loop yet).
```
global $post
echo get_the_title($post->ID);
or
echo get_the_title(2);
```
|
238,693 |
<p>I want to display the content of all pages on a single page, with links to each page.</p>
<p>This might sound like a daft request, but it's useful for quickly reviewing what's available on a smallish site.</p>
<p>Using the code below, I can get most of the info I want, but don't know how to add the permalink.</p>
<pre><code><?php $pages = get_pages();
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
echo $title;
echo $slug;
echo $content;}
?>
</code></pre>
|
[
{
"answer_id": 238698,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": -1,
"selected": false,
"text": "<p>There is probably better ways to achieve what you are wanting, but to answer your question with what you have:</p>\n\n<pre><code>$permalink = get_the_permalink($page_data->ID);\n</code></pre>\n"
},
{
"answer_id": 238701,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 0,
"selected": false,
"text": "<p>Try this code to show list of page content. Page title will be the link of that page.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'page', //specifying post type\n 'posts_per_page' => 10, //No. of Pages to show\n);\n\n$loop = new WP_Query( $args );\n\nwhile ( $loop->have_posts() ) : $loop->the_post();?>\n<h3><a href=\"<?php the_permalink() ?>\" title=\"<?php the_title(); ?>\"><font style=\"color:#666666;\"><?php the_title();?></a></h3>\n<?php the_content(__('Continue Reading')); \nendwhile;\n</code></pre>\n"
},
{
"answer_id": 238718,
"author": "bdtheme",
"author_id": 83330,
"author_profile": "https://wordpress.stackexchange.com/users/83330",
"pm_score": 0,
"selected": false,
"text": "<p>Try This:</p>\n\n<pre><code><?php\n global $paged; \n if( get_query_var( 'paged' ) ) {\n $paged = get_query_var( 'paged' );\n } elseif( get_query_var( 'page' ) ) {\n $paged = get_query_var( 'page' );\n } else {\n $paged = 1;\n }\n\n $args = array(\n 'post_type' => 'page',\n 'paged' => $paged,\n );\n\n $blog_query = new WP_Query($args);\n ?>\n\n <section>\n <?php if ( $blog_query->have_posts() ) : ?>\n <?php while ( $blog_query->have_posts() ) : $blog_query->the_post(); ?>\n <?php get_template_part( 'content-parts/content', get_post_format() ); ?>\n <?php endwhile; ?>\n <?php endif; ?>\n </section><!-- End #content -->\n?>\n</code></pre>\n"
},
{
"answer_id": 238720,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 0,
"selected": false,
"text": "<p>As you have all the Page data stored in <code>$page_data</code>, you can pass the Page <code>ID</code> to the <code>get_permalink();</code> to get the permalink of each page inside foreach loop.</p>\n\n<pre><code>$pages = get_pages();\nif ( !empty( $pages ) ) :\n foreach ($pages as $page_data) {\n $content = apply_filters('the_content', $page_data->post_content);\n $title = $page_data->post_title;\n $slug = $page_data->post_name;\n echo '<a href=\"' . get_permalink( $page_data->ID ) . '\">' . $title . '</a>';\n echo $slug;\n echo $content;\n }\nendif;\n</code></pre>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] |
I want to display the content of all pages on a single page, with links to each page.
This might sound like a daft request, but it's useful for quickly reviewing what's available on a smallish site.
Using the code below, I can get most of the info I want, but don't know how to add the permalink.
```
<?php $pages = get_pages();
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
echo $title;
echo $slug;
echo $content;}
?>
```
|
Try this code to show list of page content. Page title will be the link of that page.
```
$args = array(
'post_type' => 'page', //specifying post type
'posts_per_page' => 10, //No. of Pages to show
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();?>
<h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><font style="color:#666666;"><?php the_title();?></a></h3>
<?php the_content(__('Continue Reading'));
endwhile;
```
|
238,697 |
<p>I have a standard WordPress page category with tag_ID=92 which I want to noindex all posts in this category entirely. Is there a way to do it with actions/hooks in functions.php?</p>
|
[
{
"answer_id": 238699,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 2,
"selected": false,
"text": "<p>By noindex, I'm assuming you mean meta robots noindex, if so you could manually do this by utilizing the <a href=\"https://developer.wordpress.org/reference/functions/in_category/\" rel=\"nofollow\">in_category</a> function adding the following to your theme's header between the <code><head></head></code> tags, like so::</p>\n\n<pre><code> <?php if(in_category( '92' ))\n echo \"\\t<meta name='robots' content='noindex, nofollow' />\\r\\n\" ?>\n</code></pre>\n\n<p>Or, If you don't care to alter your theme directly, you could attach it to the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\">wp_head</a> action hook, place the following in your functions.php file usually located within your main theme or child themes folder.:</p>\n\n<pre><code>add_action('wp_head', 'noRobots');\nfunction noRobots() {\n if(in_category( '92' )) echo \"\\t<meta name='robots' content='noindex, nofollow' />\\r\\n\";\n}\n</code></pre>\n\n<p>Both the above will return true if the current post is in the category with ID '92', can also be used with category name or slug, or an array of either. </p>\n"
},
{
"answer_id": 238703,
"author": "Amine Faiz",
"author_id": 66813,
"author_profile": "https://wordpress.stackexchange.com/users/66813",
"pm_score": -1,
"selected": false,
"text": "<p>in your html header add the following code : </p>\n\n<pre><code><?php if (is_category('92')): ?>\n<meta name=\"robots\" content=\"noindex,nofollow\">\n<?php endif ?>\n</code></pre>\n"
},
{
"answer_id": 238735,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 3,
"selected": false,
"text": "<p>As the previous code I posted didnt work for the OP, clutching at straws, we can try to obtain the same outcome using <a href=\"https://developer.wordpress.org/reference/functions/get_the_category/\" rel=\"noreferrer\"><code>get_the_category</code></a>\nAs the OP stated he was using YOAST, i'll wrap this function into the YOAST hook for robots.</p>\n\n<pre><code>add_filter('wpseo_robots', 'yoast_no_home_noindex', 999); \nfunction yoast_no_home_noindex($string= \"\") {\n $term_id = get_the_category( $post->ID );\n if($term_id[0]->term_id == 92) {\n $string= \"noindex, nofollow\";\n }\n return $string; \n}\n</code></pre>\n\n<p>Same again, just drop this into your themes functions file.</p>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101087/"
] |
I have a standard WordPress page category with tag\_ID=92 which I want to noindex all posts in this category entirely. Is there a way to do it with actions/hooks in functions.php?
|
As the previous code I posted didnt work for the OP, clutching at straws, we can try to obtain the same outcome using [`get_the_category`](https://developer.wordpress.org/reference/functions/get_the_category/)
As the OP stated he was using YOAST, i'll wrap this function into the YOAST hook for robots.
```
add_filter('wpseo_robots', 'yoast_no_home_noindex', 999);
function yoast_no_home_noindex($string= "") {
$term_id = get_the_category( $post->ID );
if($term_id[0]->term_id == 92) {
$string= "noindex, nofollow";
}
return $string;
}
```
Same again, just drop this into your themes functions file.
|
238,709 |
<p>I've been away from Wordpress for a few months, and now I'm struggling to remember how to create a Page of Posts. It's most infuriating!</p>
<p><strong>The Current Site</strong></p>
<p>I have <code>home.php</code> set up to display the latest Posts of a Custom Post Type as the main page. It works fine. A simple <code>pre_get_posts</code> function in <code>functions.php</code> sets the CPT to be displayed:</p>
<pre><code>$query->set('post_type', 'campaign');
$query->set('posts_per_page', 11);
</code></pre>
<p>...when <code>is_home() && $query->is_main_query()</code>. <strong>This is correct, and does not need to be changed.</strong> It works great, but now the client wants a normal news blog <strong>elsewhere</strong> on the site.</p>
<p><strong>The New Version</strong></p>
<p>So... I need to add a news blog, that's not on the homepage, leaving the homepage as it is. It makes sense to me to use the default Post post type for this, and it makes sense for me to create a Page for this. But I can't seem to get a Page of Posts to work.</p>
<p>At first I created a <code>page-blog.php</code> template for a "News" Page, but it didn't pull in Posts with <code>while ( have_posts() ) : the_post();</code>. Instead it only listed <em>itself</em>...?</p>
<p>I then added a new line to my <code>pre_get_posts</code> function:</p>
<pre><code>if(is_page_template('page-news.php')) {
$query->set('post_type', 'post');
}
</code></pre>
<p>But now the page returns 404.</p>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 238712,
"author": "Harshita",
"author_id": 102498,
"author_profile": "https://wordpress.stackexchange.com/users/102498",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Changing the post type on the home page</strong></p>\n\n<p>By default, WordPress shows the post post type on your home page\nTo add pages, open your theme’s <strong>functions.php</strong> file and paste this PHP code into it:</p>\n\n<pre><code>add_filter( 'pre_get_posts', 'my_get_posts' );\n\nfunction my_get_posts( $query ) {\n\n if ( is_home() && $query->is_main_query() )\n $query->set( 'post_type', array( 'post', 'page', 'album', 'movie' ) );\n\n return $query;\n}\n</code></pre>\n\n<p>Showing the post types in your feed\nRealizing that many of you might want to also add these post types to your feed to match your blog, a small change in the code is required. All you need to do is change this line:</p>\n\n<pre><code>if ( is_home() && $query->is_main_query() )\n</code></pre>\n\n<p>We’ll use the <code>is_feed()</code> conditional tag:</p>\n\n<pre><code>if ( ( is_home() && $query->is_main_query() ) || is_feed() )\n</code></pre>\n\n<p>Now, you can have custom post types in your regular blog post rotation and your feed.</p>\n"
},
{
"answer_id": 238714,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 2,
"selected": true,
"text": "<p>Try this code in your <code>page-blog.php</code> to display list of posts</p>\n\n<pre><code>$paged = get_query_var('paged') ? get_query_var('paged') : 1;\n $args = array(\n 'post_type' => 'post', //Change this with your post type\n 'posts_per_page' => 10, //No. of Pages to show \n 'offset' => 0, //excluding the latest post if any\n 'paged' => $paged //For Pagination\n );\n\n$loop = new WP_Query( $args );\n\nwhile ( $loop->have_posts() ) : $loop->the_post();?>\n<h3><a href=\"<?php the_permalink() ?>\" title=\"<?php the_title(); ?>\"><?php the_title();?></a></h3>\n<?php the_content(__('Continue Reading')); \nendwhile;\n\nwp_reset_postdata();\n</code></pre>\n"
},
{
"answer_id": 238717,
"author": "bdtheme",
"author_id": 83330,
"author_profile": "https://wordpress.stackexchange.com/users/83330",
"pm_score": 0,
"selected": false,
"text": "<p>Try This:post_type=custom_post type slug</p>\n\n<pre><code><?php\n global $paged; \n if( get_query_var( 'paged' ) ) {\n $paged = get_query_var( 'paged' );\n } elseif( get_query_var( 'page' ) ) {\n $paged = get_query_var( 'page' );\n } else {\n $paged = 1;\n }\n\n $args = array(\n 'post_type' => 'your_post_type',\n 'paged' => $paged,\n );\n\n $blog_query = new WP_Query($args);\n ?>\n\n <section>\n <?php if ( $blog_query->have_posts() ) : ?>\n <?php while ( $blog_query->have_posts() ) : $blog_query->the_post(); ?>\n <?php get_template_part( 'content-parts/content', get_post_format() ); ?>\n <?php endwhile; ?>\n <?php endif; ?>\n </section><!-- End #content -->\n?>\n</code></pre>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4109/"
] |
I've been away from Wordpress for a few months, and now I'm struggling to remember how to create a Page of Posts. It's most infuriating!
**The Current Site**
I have `home.php` set up to display the latest Posts of a Custom Post Type as the main page. It works fine. A simple `pre_get_posts` function in `functions.php` sets the CPT to be displayed:
```
$query->set('post_type', 'campaign');
$query->set('posts_per_page', 11);
```
...when `is_home() && $query->is_main_query()`. **This is correct, and does not need to be changed.** It works great, but now the client wants a normal news blog **elsewhere** on the site.
**The New Version**
So... I need to add a news blog, that's not on the homepage, leaving the homepage as it is. It makes sense to me to use the default Post post type for this, and it makes sense for me to create a Page for this. But I can't seem to get a Page of Posts to work.
At first I created a `page-blog.php` template for a "News" Page, but it didn't pull in Posts with `while ( have_posts() ) : the_post();`. Instead it only listed *itself*...?
I then added a new line to my `pre_get_posts` function:
```
if(is_page_template('page-news.php')) {
$query->set('post_type', 'post');
}
```
But now the page returns 404.
What am I doing wrong?
|
Try this code in your `page-blog.php` to display list of posts
```
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post', //Change this with your post type
'posts_per_page' => 10, //No. of Pages to show
'offset' => 0, //excluding the latest post if any
'paged' => $paged //For Pagination
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();?>
<h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title();?></a></h3>
<?php the_content(__('Continue Reading'));
endwhile;
wp_reset_postdata();
```
|
238,741 |
<p>I have custom post type name "resources" and taxonomy called "type" with lot of terms in it. I do not want to create custom template for each term like taxonomy-type-{term}.php every time I add new term.</p>
<p>What I am trying to achieve here is a single page where it handle to check each terms. If the current term is "24622", show content and so on, but I want it dynamic so I don't want to input term ID each time a new term created. </p>
<p>The code that I use that works so far for single term is this:</p>
<pre><code><?php
$args = array (
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => 24622 //I WANT IT DYNAMIC
)
)
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
}
?>
</code></pre>
<p>Please help. Thanks!</p>
<p><strong>UPDATE</strong></p>
<p>Here is the code that works for now but it fetches posts wrong order.</p>
<pre><code>// get all terms used by current post for specific category
$terms = get_the_terms(get_the_ID() , 'type');
// if $terms is array convert array of term objects to array of term IDs
if(is_array($terms)){
$term_ids = wp_list_pluck($terms, 'term_id');
foreach($terms as $term) {
$post_ids[] = $term->term_id;
}
// proceed with tax query
$args = array(
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => $term->term_id
)
)
);
$loop = new WP_Query($args);
if ($loop->have_posts()) {
$term = $wp_query->queried_object;
while ($loop->have_posts()):
$loop->the_post();
// Output what you want
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
}
wp_reset_postdata();
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Rs8Hv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rs8Hv.jpg" alt="enter image description here"></a></p>
<p>If I click the "Case studies (2)" it supposed to show 2 posts but show 1 post. In "Advocacy maps (1)", it shows 2 posts.</p>
<p>Post 1 is related to "Case studies" and "Advocacy maps" terms<br>
Post 2 is related to "Case studies" and "Land monitoring reports"</p>
|
[
{
"answer_id": 238771,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could try the following code: </p>\n\n<pre><code>// get all terms used by current post for specific category\n$terms = get_the_terms(get_the_ID() , 'type');\n// if $terms is array convert array of term objects to array of term IDs\nif(is_array($terms)){\n$term_ids = wp_list_pluck($terms, 'term_id');\n// proceed with tax query\n$args = array(\n 'post_type' => 'resources',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'type',\n 'field' => 'id',\n 'terms' => $term_ids\n )\n )\n);\n$loop = new WP_Query($args);\n\nif ($loop->have_posts()) {\n $term = $wp_query->queried_object;\n while ($loop->have_posts()):\n $loop->the_post();\n\n // Output what you want\n\n echo '<li><a href=\"' . get_permalink() . '\">' . get_the_title() . '</a></li>';\n endwhile;\n}\nwp_reset_postdata();\n}\n</code></pre>\n\n<p>This will return all posts having the same term OR terms as current post.\nCan try and let me know if OK</p>\n"
},
{
"answer_id": 238833,
"author": "MightyGas",
"author_id": 35253,
"author_profile": "https://wordpress.stackexchange.com/users/35253",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you for your time answering my unclear question. The code I found is the one that Im looking for. Thank you again :)</p>\n\n<pre><code><?php \n//http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters\n$term_slug = get_queried_object()->slug;\n if ( !$term_slug )\n return;\n else\n$args = array(\n 'tax_query' => array(\n array(\n 'taxonomy' => 'gallery_category',\n 'field' => 'slug',\n 'terms' => $term_slug,\n 'posts_per_page' => 10\n )\n )\n);\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post(); ?>\n <div class=\"entry-content\">\n <?php the_excerpt(); ?>\n </div><!-- .entry-content -->\n<?php endwhile; // End the loop. ?>\n</code></pre>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35253/"
] |
I have custom post type name "resources" and taxonomy called "type" with lot of terms in it. I do not want to create custom template for each term like taxonomy-type-{term}.php every time I add new term.
What I am trying to achieve here is a single page where it handle to check each terms. If the current term is "24622", show content and so on, but I want it dynamic so I don't want to input term ID each time a new term created.
The code that I use that works so far for single term is this:
```
<?php
$args = array (
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => 24622 //I WANT IT DYNAMIC
)
)
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
}
?>
```
Please help. Thanks!
**UPDATE**
Here is the code that works for now but it fetches posts wrong order.
```
// get all terms used by current post for specific category
$terms = get_the_terms(get_the_ID() , 'type');
// if $terms is array convert array of term objects to array of term IDs
if(is_array($terms)){
$term_ids = wp_list_pluck($terms, 'term_id');
foreach($terms as $term) {
$post_ids[] = $term->term_id;
}
// proceed with tax query
$args = array(
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => $term->term_id
)
)
);
$loop = new WP_Query($args);
if ($loop->have_posts()) {
$term = $wp_query->queried_object;
while ($loop->have_posts()):
$loop->the_post();
// Output what you want
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
}
wp_reset_postdata();
}
```
[](https://i.stack.imgur.com/Rs8Hv.jpg)
If I click the "Case studies (2)" it supposed to show 2 posts but show 1 post. In "Advocacy maps (1)", it shows 2 posts.
Post 1 is related to "Case studies" and "Advocacy maps" terms
Post 2 is related to "Case studies" and "Land monitoring reports"
|
Thank you for your time answering my unclear question. The code I found is the one that Im looking for. Thank you again :)
```
<?php
//http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters
$term_slug = get_queried_object()->slug;
if ( !$term_slug )
return;
else
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'gallery_category',
'field' => 'slug',
'terms' => $term_slug,
'posts_per_page' => 10
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="entry-content">
<?php the_excerpt(); ?>
</div><!-- .entry-content -->
<?php endwhile; // End the loop. ?>
```
|
238,749 |
<p>Trying to conditionally hide the "private" prefix in front of the page title on one specific page named 'members' only.</p>
<p>I used this code in functions.php to hide the prefix on all pages.</p>
<pre><code>function title_format($content) {
return '%s';
}
add_filter('private_title_format', 'title_format');
add_filter('protected_title_format', 'title_format');
</code></pre>
<p>Tried to hook into this with the if is_page ( 'members' ) in various ways, but so far the only result i managed to get is fatal errors.</p>
|
[
{
"answer_id": 238771,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could try the following code: </p>\n\n<pre><code>// get all terms used by current post for specific category\n$terms = get_the_terms(get_the_ID() , 'type');\n// if $terms is array convert array of term objects to array of term IDs\nif(is_array($terms)){\n$term_ids = wp_list_pluck($terms, 'term_id');\n// proceed with tax query\n$args = array(\n 'post_type' => 'resources',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'type',\n 'field' => 'id',\n 'terms' => $term_ids\n )\n )\n);\n$loop = new WP_Query($args);\n\nif ($loop->have_posts()) {\n $term = $wp_query->queried_object;\n while ($loop->have_posts()):\n $loop->the_post();\n\n // Output what you want\n\n echo '<li><a href=\"' . get_permalink() . '\">' . get_the_title() . '</a></li>';\n endwhile;\n}\nwp_reset_postdata();\n}\n</code></pre>\n\n<p>This will return all posts having the same term OR terms as current post.\nCan try and let me know if OK</p>\n"
},
{
"answer_id": 238833,
"author": "MightyGas",
"author_id": 35253,
"author_profile": "https://wordpress.stackexchange.com/users/35253",
"pm_score": 1,
"selected": false,
"text": "<p>Thank you for your time answering my unclear question. The code I found is the one that Im looking for. Thank you again :)</p>\n\n<pre><code><?php \n//http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters\n$term_slug = get_queried_object()->slug;\n if ( !$term_slug )\n return;\n else\n$args = array(\n 'tax_query' => array(\n array(\n 'taxonomy' => 'gallery_category',\n 'field' => 'slug',\n 'terms' => $term_slug,\n 'posts_per_page' => 10\n )\n )\n);\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post(); ?>\n <div class=\"entry-content\">\n <?php the_excerpt(); ?>\n </div><!-- .entry-content -->\n<?php endwhile; // End the loop. ?>\n</code></pre>\n"
}
] |
2016/09/09
|
[
"https://wordpress.stackexchange.com/questions/238749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94259/"
] |
Trying to conditionally hide the "private" prefix in front of the page title on one specific page named 'members' only.
I used this code in functions.php to hide the prefix on all pages.
```
function title_format($content) {
return '%s';
}
add_filter('private_title_format', 'title_format');
add_filter('protected_title_format', 'title_format');
```
Tried to hook into this with the if is\_page ( 'members' ) in various ways, but so far the only result i managed to get is fatal errors.
|
Thank you for your time answering my unclear question. The code I found is the one that Im looking for. Thank you again :)
```
<?php
//http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters
$term_slug = get_queried_object()->slug;
if ( !$term_slug )
return;
else
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'gallery_category',
'field' => 'slug',
'terms' => $term_slug,
'posts_per_page' => 10
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="entry-content">
<?php the_excerpt(); ?>
</div><!-- .entry-content -->
<?php endwhile; // End the loop. ?>
```
|
238,807 |
<p>I have used a theme that includes the word "courses" throughout the theme by default as it is an online education platform. I am however creating a website with a similar design, but for projects so i would like to replace the word "courses" throughout the theme with the word "projects"
I have minimum experience with coding and even html so please dumb it down for me :)
Thank You in advance</p>
|
[
{
"answer_id": 238810,
"author": "Zeeshan",
"author_id": 102553,
"author_profile": "https://wordpress.stackexchange.com/users/102553",
"pm_score": -1,
"selected": false,
"text": "<p>The simplest thing you can do is export the database and find/replace <code>courses</code> with <code>projects</code>, save it and import the updated file to your server.</p>\n\n<p>Or else\nYou can try this plugin which replaces words(though i haven't got chance to try it)\n<a href=\"https://wordpress.org/plugins/word-replacer/\" rel=\"nofollow\">https://wordpress.org/plugins/word-replacer/</a></p>\n\n<p>Let me know if you need any help further</p>\n"
},
{
"answer_id": 238829,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": false,
"text": "<p>I would try one of two options depending on your preference</p>\n<h3>1. <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Search & Replace Script</a></h3>\n<ul>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search & Replace Script here</a></li>\n<li>Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://web.site/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>Enter the in word "<em>courses</em>" the <strong><code>search for…</code></strong> field and "projects" in the <strong><code>replace with…</code></strong> field</li>\n</ul>\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n<h3>2. <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Search & Replace Plugin</a></h3>\n<p>For a similar process, but within WordPress, is to use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Search & Replace</a> plugin to easily update your database that contain the word "<em>courses</em>" and change it to "<em>projects</em>". The process is easy to use and you can also perform a dry run to preview what tables and rows will be affected before applying those changes.</p>\n"
},
{
"answer_id": 238844,
"author": "WhereDidMyBrainGo",
"author_id": 102575,
"author_profile": "https://wordpress.stackexchange.com/users/102575",
"pm_score": 1,
"selected": false,
"text": "<p>If you have <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> you can do a \"dry run\" to see what would change.</p>\n\n<p><code>wp search-replace courses projects --dry-run</code></p>\n\n<p>Example output:</p>\n\n<blockquote>\n <p>| wp_posts | post_content | 6 | SQL |</p>\n</blockquote>\n\n<p>In example, 6 occurrences of <code>courses</code> in wp_posts table would be replaced with <code>projects</code></p>\n\n<p>See <a href=\"https://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">Search/replace strings in the database</a> for more info.</p>\n"
},
{
"answer_id": 238848,
"author": "Leon Francis Shelhamer",
"author_id": 25927,
"author_profile": "https://wordpress.stackexchange.com/users/25927",
"pm_score": 3,
"selected": false,
"text": "<p>I see some great answers for how to do a search and replace on a given string found in the database. However as I understand the OP's question, they are looking to replace text found in the theme files, as the question says \"I have used a theme that includes the word \"courses\" throughout the theme by default...\".</p>\n\n<p>If this was a case where the theme anticipated this need, or was already changing the text of a plugin, like some themes change the WooCommerce cart text from \"add to cart\" to \"purchase course\". Then there would be filter hooks available but you would need well written documentation, or the ability to look through the code to determine this. (<a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/add_filter/</a>)</p>\n\n<p>A fast simple clever way would be to add this to a child theme's <code>functions.php</code> file. (<a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"noreferrer\">https://codex.wordpress.org/Child_Themes</a>)</p>\n\n<pre><code>function start_modify_html() {\n\n ob_start();\n}\n\nfunction end_modify_html() {\n\n $html = ob_get_clean();\n $html = str_replace( 'Course', 'Project', $html );\n $html = str_replace( 'course', 'project', $html );\n echo $html;\n}\n\nadd_action( 'wp_head', 'start_modify_html' );\nadd_action( 'wp_footer', 'end_modify_html' );\n</code></pre>\n\n<p>The last way would be to edit the theme files, if the theme were ever updated all of your changes would be lost. To do this you could download the theme and use any decent text editor to do a search and replace, then upload. I do this with Atom editor all the time and it is open source and free to download. (<a href=\"http://flight-manual.atom.io/using-atom/sections/find-and-replace/\" rel=\"noreferrer\">http://flight-manual.atom.io/using-atom/sections/find-and-replace/</a>)</p>\n"
}
] |
2016/09/10
|
[
"https://wordpress.stackexchange.com/questions/238807",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102552/"
] |
I have used a theme that includes the word "courses" throughout the theme by default as it is an online education platform. I am however creating a website with a similar design, but for projects so i would like to replace the word "courses" throughout the theme with the word "projects"
I have minimum experience with coding and even html so please dumb it down for me :)
Thank You in advance
|
I see some great answers for how to do a search and replace on a given string found in the database. However as I understand the OP's question, they are looking to replace text found in the theme files, as the question says "I have used a theme that includes the word "courses" throughout the theme by default...".
If this was a case where the theme anticipated this need, or was already changing the text of a plugin, like some themes change the WooCommerce cart text from "add to cart" to "purchase course". Then there would be filter hooks available but you would need well written documentation, or the ability to look through the code to determine this. (<https://developer.wordpress.org/reference/functions/add_filter/>)
A fast simple clever way would be to add this to a child theme's `functions.php` file. (<https://codex.wordpress.org/Child_Themes>)
```
function start_modify_html() {
ob_start();
}
function end_modify_html() {
$html = ob_get_clean();
$html = str_replace( 'Course', 'Project', $html );
$html = str_replace( 'course', 'project', $html );
echo $html;
}
add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );
```
The last way would be to edit the theme files, if the theme were ever updated all of your changes would be lost. To do this you could download the theme and use any decent text editor to do a search and replace, then upload. I do this with Atom editor all the time and it is open source and free to download. (<http://flight-manual.atom.io/using-atom/sections/find-and-replace/>)
|
238,850 |
<p>I don't know why <code>get_term()</code> works on other pages but won't work in <code>functions.php</code>. Using <code>get_term()</code> in <code>functions.php</code> causes WordPress to report the error <em>Invalid taxonomy</em>.</p>
<p>my <code>function.php</code> which is ajax handler and already registered for ajax</p>
<pre><code> public function load_destination()
{
global $wpdb;
$termId = $_POST['termid'];
$term = get_term($termid,'package_state');
$args = array(
'post_type' => 'package',
'tax_query' => array(
array(
'taxonomy' => 'package_state',
'field' => 'id',
'terms' => $termId
)
)
);
$query = new WP_Query( $args );
$collection=[];
$count =1;
while($query->have_posts()) : $query->the_post();
$collection['data'][] = // i need to set term data here $term;
$count++;
endwhile;
wp_send_json($collection);
}
</code></pre>
|
[
{
"answer_id": 238851,
"author": "bbruman",
"author_id": 102212,
"author_profile": "https://wordpress.stackexchange.com/users/102212",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_term\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_term</a></p>\n\n<pre><code>Uses global: (object) $wpdb\n</code></pre>\n\n<p>try declaring</p>\n\n<pre><code>global $wpdb;\n</code></pre>\n\n<p>before your get_term() query?</p>\n\n<p>It may work, depending on the code you're trying to use.</p>\n"
},
{
"answer_id": 238854,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you are are using <code>get_term()</code> for a custom taxonomy. If you're using <code>get_term()</code> inside <code>functions.php</code> and outside of a hooked function, that code is going to be run immediately when <code>functions.php</code> is loaded. Your custom taxonomy will not have been registered at this point, because that happens on the <code>init</code> hook.</p>\n\n<p>Your code is working inside of your page template because WordPress has loaded the custom taxonomies at that point.</p>\n\n<p>If you were to try something like <code>$term = get_term( '2', 'category' );</code> (where <code>2</code> is a valid term ID) in <code>functions.php</code>, it would actually work, because WordPress loads built-in taxonomies in <code>wp-settings.php</code> (which is very early in the loading process) for backwards compatibility reasons. WordPress also registers default taxonomies on <code>init</code>, by the way. This is explained in the documentation block for <code>create_initial_taxonomies()</code> in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/taxonomy.php#L13\" rel=\"nofollow\"><code>/wp-includes/taxonomy.php</code></a>.</p>\n\n<p>Anyway, running <code>get_term()</code> outside of a hooked function in <code>functions.php</code> is not the right way to do it, and more code would be needed to help you further.</p>\n"
}
] |
2016/09/11
|
[
"https://wordpress.stackexchange.com/questions/238850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66294/"
] |
I don't know why `get_term()` works on other pages but won't work in `functions.php`. Using `get_term()` in `functions.php` causes WordPress to report the error *Invalid taxonomy*.
my `function.php` which is ajax handler and already registered for ajax
```
public function load_destination()
{
global $wpdb;
$termId = $_POST['termid'];
$term = get_term($termid,'package_state');
$args = array(
'post_type' => 'package',
'tax_query' => array(
array(
'taxonomy' => 'package_state',
'field' => 'id',
'terms' => $termId
)
)
);
$query = new WP_Query( $args );
$collection=[];
$count =1;
while($query->have_posts()) : $query->the_post();
$collection['data'][] = // i need to set term data here $term;
$count++;
endwhile;
wp_send_json($collection);
}
```
|
It sounds like you are are using `get_term()` for a custom taxonomy. If you're using `get_term()` inside `functions.php` and outside of a hooked function, that code is going to be run immediately when `functions.php` is loaded. Your custom taxonomy will not have been registered at this point, because that happens on the `init` hook.
Your code is working inside of your page template because WordPress has loaded the custom taxonomies at that point.
If you were to try something like `$term = get_term( '2', 'category' );` (where `2` is a valid term ID) in `functions.php`, it would actually work, because WordPress loads built-in taxonomies in `wp-settings.php` (which is very early in the loading process) for backwards compatibility reasons. WordPress also registers default taxonomies on `init`, by the way. This is explained in the documentation block for `create_initial_taxonomies()` in [`/wp-includes/taxonomy.php`](https://github.com/WordPress/WordPress/blob/master/wp-includes/taxonomy.php#L13).
Anyway, running `get_term()` outside of a hooked function in `functions.php` is not the right way to do it, and more code would be needed to help you further.
|
238,863 |
<p>I am beginner of wordpress. </p>
<pre><code> <?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
</code></pre>
<p>I use this post loop once, But now this doesn't work. Where am I doing mistake. I search but I can't understand very well. Thank you.</p>
<p>----------------------------- EDİT -----------------------------</p>
<p>I create topic like that.</p>
<p><a href="https://i.stack.imgur.com/v9WCv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9WCv.png" alt="enter image description here"></a></p>
<p>And result is like this: (just lile page title).</p>
<p><a href="https://i.stack.imgur.com/MCgor.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCgor.png" alt="enter image description here"></a></p>
<p>Also if you want my page.php code :</p>
<pre><code> <?php if(is_page(albumlerimiz)): ?>
<div id="albumlerimiz">
<div class="baslik">
<h1> Albümlerimiz </h1>
</div>
<div class="content">
<div class="container">
<div class="center-align">
<div class="portfolio_filter">
<ul>
<li data-filter="*"> TÜM ALBÜMLER </li>
<li data-filter=".dugun"> DÜGÜN ALBÜMLERİ </li>
<li data-filter=".cocuk"> ÇOCUK ALBÜMLERİ </li>
<li data-filter=".okul"> OKUL ALBÜMLERİ </li>
<li data-filter=".sunnet"> SÜNNET ALBÜMLERİ </li>
</ul>
</div>
<div class="portfolio_items">
<?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
</div>
</div>
</div>
</div>
<?php endif ?>
</code></pre>
|
[
{
"answer_id": 238879,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 2,
"selected": true,
"text": "<p>Go to admin (Wordpress Portal) > Settings > Reading, look to \"Front page displays\" and make sure \"Your latest posts\" is checked</p>\n\n<p><a href=\"https://codex.wordpress.org/Settings_Reading_Screen\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Settings_Reading_Screen</a></p>\n"
},
{
"answer_id": 239088,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 0,
"selected": false,
"text": "<p>As per my understandings of your issue:</p>\n\n<p>You are not querying posts you need to show.\nUse <code>wp_query()</code> to query your posts before loop.</p>\n\n<pre><code>$wp_query = new WP_Query(array('posts_per_page'=>-1));\nwhile ($wp_query->have_posts()) : $wp_query->the_post();\n //your code here\nendwhile;\n</code></pre>\n"
},
{
"answer_id": 276609,
"author": "Arindam",
"author_id": 125709,
"author_profile": "https://wordpress.stackexchange.com/users/125709",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php \n $wp_query = new WP_Query(array('posts_per_page'=>-1));\nwhile ($wp_query->have_posts()) : $wp_query->the_post();?>\n <h3><?php the_title();?></h3>\n <p><?php the_content(); ?></p> \n<?php endwhile;\n?>\n</code></pre>\n\n<p>this is the right answer.....</p>\n"
},
{
"answer_id": 306015,
"author": "Mohamed Abbas",
"author_id": 145267,
"author_profile": "https://wordpress.stackexchange.com/users/145267",
"pm_score": 0,
"selected": false,
"text": "<p>Answer go to setting -> reading -> make sure your latest posts checked as image below</p>\n\n<p><a href=\"https://i.stack.imgur.com/BXms1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BXms1.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2016/09/11
|
[
"https://wordpress.stackexchange.com/questions/238863",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96869/"
] |
I am beginner of wordpress.
```
<?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
```
I use this post loop once, But now this doesn't work. Where am I doing mistake. I search but I can't understand very well. Thank you.
----------------------------- EDİT -----------------------------
I create topic like that.
[](https://i.stack.imgur.com/v9WCv.png)
And result is like this: (just lile page title).
[](https://i.stack.imgur.com/MCgor.png)
Also if you want my page.php code :
```
<?php if(is_page(albumlerimiz)): ?>
<div id="albumlerimiz">
<div class="baslik">
<h1> Albümlerimiz </h1>
</div>
<div class="content">
<div class="container">
<div class="center-align">
<div class="portfolio_filter">
<ul>
<li data-filter="*"> TÜM ALBÜMLER </li>
<li data-filter=".dugun"> DÜGÜN ALBÜMLERİ </li>
<li data-filter=".cocuk"> ÇOCUK ALBÜMLERİ </li>
<li data-filter=".okul"> OKUL ALBÜMLERİ </li>
<li data-filter=".sunnet"> SÜNNET ALBÜMLERİ </li>
</ul>
</div>
<div class="portfolio_items">
<?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
</div>
</div>
</div>
</div>
<?php endif ?>
```
|
Go to admin (Wordpress Portal) > Settings > Reading, look to "Front page displays" and make sure "Your latest posts" is checked
<https://codex.wordpress.org/Settings_Reading_Screen>
|
238,882 |
<p>I'm not experienced with the WordPress. My goal is to display all the posts on the page.</p>
<p>I was trying to display posts on a page like so:</p>
<pre><code><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
...
<?php endwhile; else: ?>
<p><?php _e( 'Sorry, no pages found.' ); ?></p>
<?php endif; ?>
</code></pre>
<p>I've faced a problem that there is a limit of 5 posts to be displayed by default. I tried to use custom <code>WP_Query</code>:</p>
<pre><code><?php
$all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'posts_per_page'=>-1,
));
if ($all_query->have_posts()) : while ($all_query->have_posts()) : $all_query->the_post();
?>
</code></pre>
<p>It shows all the posts, but it also shows all the posts even on category archive pages (i.e. posts from another category).</p>
<p>As I understand, I can create <code>archive.php</code> page for categories and authors.</p>
<p>Is there any solution to use loop to show all the posts only of the current category or author?</p>
|
[
{
"answer_id": 238893,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The number of posts displayed in any loop by default is controlled by <em>Settings > Blog pages show at most</em>. To show all posts, you can enter a huge number, but <code>-1</code> (which is the value to use for the <code>posts_per_page</code> paramerter in <code>WP_Query</code>) does not work here.</p>\n\n<p>It is possible to show all posts on the category and author archives while still showing a limited number of posts within your main blog area. To do this, use the <em>Blog pages to show at most</em> setting to configure the number of posts to show within the main blog, then use the <code>pre_get_posts</code> hook to modify the other archives to suit your preferences. Add the following code to your theme's <code>functions.php</code> file:</p>\n\n<pre><code>/**\n * Modify the query to show all posts on category and author archives.\n * \n */\nfunction wpse238882_pre_get_posts( $query ) {\n if ( ( $query->is_author() || $query->is_category() ) && $query->is_main_query() ) {\n $query->set( 'posts_per_page', -1 );\n }\n}\nadd_action( 'pre_get_posts', 'wpse238882_pre_get_posts' );\n</code></pre>\n\n<p>You can still use the <code>author.php</code> and <code>category.php</code> templates to customize the output of your author and category archives, but this is not necessary to simply modify the number of posts displayed, which has been demonstrated above. Check out the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template hierarchy</a> Codex entry for more information on customizing templates.</p>\n"
},
{
"answer_id": 310673,
"author": "Maria Teresa",
"author_id": 145335,
"author_profile": "https://wordpress.stackexchange.com/users/145335",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n\n//for each category, show all posts\n$cat_args = array(\n 'orderby' => 'name',\n 'order' => 'ASC'\n);\n$categories = get_categories( $cat_args );\n\nforeach( $categories as $category ) {\n\n $args = array(\n 'showposts' => -1,\n 'post_per_page' => -1,\n 'category__in' => array($category->term_id),\n 'caller_get_posts' =>1\n );\n $posts = get_posts( $args );\n\n if( $posts ) {\n echo '<p>Category: <a href=\"' . get_category_link( $category->term_id ) . '\" title=\"' . sprintf( __( \"View all posts in %s\" ), $category->name ) . '\" ' . '>' . $category->name . '</a></p>';\n\n foreach( $posts as $post ) {\n setup_postdata( $post );\n\n while ( have_posts() ) : the_post(); \n\n the_title( '<div>', '</div>' );\n\n endwhile;hp\n } // foreach($posts\n } // if ($posts\n} // foreach($categories\n</code></pre>\n"
}
] |
2016/09/11
|
[
"https://wordpress.stackexchange.com/questions/238882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82592/"
] |
I'm not experienced with the WordPress. My goal is to display all the posts on the page.
I was trying to display posts on a page like so:
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
...
<?php endwhile; else: ?>
<p><?php _e( 'Sorry, no pages found.' ); ?></p>
<?php endif; ?>
```
I've faced a problem that there is a limit of 5 posts to be displayed by default. I tried to use custom `WP_Query`:
```
<?php
$all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'posts_per_page'=>-1,
));
if ($all_query->have_posts()) : while ($all_query->have_posts()) : $all_query->the_post();
?>
```
It shows all the posts, but it also shows all the posts even on category archive pages (i.e. posts from another category).
As I understand, I can create `archive.php` page for categories and authors.
Is there any solution to use loop to show all the posts only of the current category or author?
|
The number of posts displayed in any loop by default is controlled by *Settings > Blog pages show at most*. To show all posts, you can enter a huge number, but `-1` (which is the value to use for the `posts_per_page` paramerter in `WP_Query`) does not work here.
It is possible to show all posts on the category and author archives while still showing a limited number of posts within your main blog area. To do this, use the *Blog pages to show at most* setting to configure the number of posts to show within the main blog, then use the `pre_get_posts` hook to modify the other archives to suit your preferences. Add the following code to your theme's `functions.php` file:
```
/**
* Modify the query to show all posts on category and author archives.
*
*/
function wpse238882_pre_get_posts( $query ) {
if ( ( $query->is_author() || $query->is_category() ) && $query->is_main_query() ) {
$query->set( 'posts_per_page', -1 );
}
}
add_action( 'pre_get_posts', 'wpse238882_pre_get_posts' );
```
You can still use the `author.php` and `category.php` templates to customize the output of your author and category archives, but this is not necessary to simply modify the number of posts displayed, which has been demonstrated above. Check out the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) Codex entry for more information on customizing templates.
|
238,889 |
<p>I'm trying to make a social links menu for the footer in my theme. I want a menu to be customisable in Dashboard, I want the links to be relative to what's put in there.</p>
<p>Originally to get that, I did this: </p>
<pre><code><a href="http://www.facebook.com/" target="_blank"><i class="fa fa-facebook circle"></i></a>
<a href="http://www.google.com/" target="_blank"><i class="fa fa-google-plus circle"></i></a>
<a href="http://www.twitter.com/" target="_blank"><i class="fa fa-twitter circle"></i></a>
<a href="http://www.linkedin.com/" target="_blank"><i class="fa fa-linkedin circle"></i></a>
</code></pre>
<p>For hard-coded menu items.</p>
<p>Now, I want to use</p>
<pre><code><?php wp_nav_menu( array( 'theme_location' => 'social' ) ); ?>
</code></pre>
<p>To generate the <code><li></code> but realise that doing so puts the link label, i.e. <code>Facebook</code> inside the <code><li><a></code> tags.</p>
<p>i.e. <code><li class="fa fa-facebook circle"><a href="fb.com">Facebook</a></li></code></p>
<p>Which isn't that great because 1. Facebook label gets in the way and 2. is the only thing that is clickable.</p>
<p>I want to get the link tag on the outside of my classes (being set automatically by Wordpress too through Menu customisation)</p>
<p>I realise I could write the <code><i></code> class inside the label for each menu item, but that defeats the purpose I'm going after here.</p>
<p>Edit: I'd love a solution that doesn't exclude hacking in some way.</p>
|
[
{
"answer_id": 238902,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 2,
"selected": true,
"text": "<p>This is a tough one. Normally I'd say use <code>text-indent:-99999px;</code> as part of the markup for <code><a></code> -- to get that link text off the screen. But you have that <code>fa</code> italic tag which is really text as well - so it gets shifted off the screen, too.</p>\n\n<p>This solution is pretty ugly but you can probably tweak it for your use.</p>\n\n<p>Wrap the social links inside a div:</p>\n\n<pre><code><div id=\"social-wrapper\">\n <a href=\"http://www.facebook.com/\" target=\"_blank\"><i class=\"fa fa-facebook circle\"></i>Facebook</a>\n <a href=\"http://www.google.com/\" target=\"_blank\"><i class=\"fa fa-google-plus circle\"></i>Google</a>\n <a href=\"http://www.twitter.com/\" target=\"_blank\"><i class=\"fa fa-twitter circle\"></i>Twitter</a>\n <a href=\"http://www.linkedin.com/\" target=\"_blank\"><i class=\"fa fa-linkedin circle\"></i>LinkedIn</a>\n</div>\n</code></pre>\n\n<p>Then, .css like this:</p>\n\n<pre><code>#social-wrapper .fa {\n color: #000;\n}\n#social-wrapper a {\n color: transparent;\n display: inline-block;\n margin: 0 8px;\n overflow: hidden;\n width: 15px;\n}\n</code></pre>\n\n<p>Set that width to accommodate your .fa icon width. Here is a <a href=\"https://jsfiddle.net/t1zk4u5n/\" rel=\"nofollow\">jsfiddle</a> that shows how it works.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>ok, didn't realize you couldn't get the above solution to work. Here's a less ugly version, still just using CSS. Anything beyond this and you will need to write your own implementation of <code>wp_nav_menu</code> to get the content the way you want it and not rely on a css solution.</p>\n\n<p>Same HTML as above, with a wrapper div.</p>\n\n<p>This CSS:</p>\n\n<pre><code>#social-wrapper {\n text-indent: -99999px;\n}\n#social-wrapper a {\n width: 30px;\n float: left;\n}\n#social-wrapper .fa {\n display: inline-block;\n vertical-align: middle;\n width: 0;\n text-indent: 99999px;\n}\n</code></pre>\n\n<p>And here's <a href=\"https://jsfiddle.net/r21fooqh/\" rel=\"nofollow\">another fiddle</a> showing how it works.</p>\n"
},
{
"answer_id": 239125,
"author": "insidesin",
"author_id": 102600,
"author_profile": "https://wordpress.stackexchange.com/users/102600",
"pm_score": 0,
"selected": false,
"text": "<p>My solution was strange. A little hacky, and going with CC's solution worked, but I think it was being bugged by something else in my footer. (I'm silly)</p>\n\n<pre><code>#social_area {\n li a {\n display: block;\n color: transparent;\n overflow: hidden;\n margin-top: -45px;\n width: 100%;\n }\n}\n</code></pre>\n\n<p>Where HTML looked a little like this.</p>\n\n<pre><code><ul id=\"menu-social-media\">\n <li class=\"fa fa-facebook circle\"><a title=\"Facebook\" target=\"_blank\" href=\"http://www.facebook.com/\">Facebook</a></li>\n <li class=\"fa fa-instagram circle\"><a title=\"Instagram\" target=\"_blank\" href=\"http://www.instagram.com/\">Instagram</a></li>\n <li class=\"fa fa-pinterest circle\"><a title=\"Pinterest\" target=\"_blank\" href=\"http://au.pinterest.com/\">Pinterest</a></li>\n <li class=\"fa fa-yelp circle\"><a title=\"Yelp\" target=\"_blank\" href=\"http://www.yelp.com/\">Yelp</a></li>\n</ul>\n</code></pre>\n\n<p>Surrounded by the #social_area div.</p>\n\n<p>I think I spent an hour trying to get this to work but it was another element's style that was ruining it. (Why won't this shit work!?)</p>\n\n<p>Thanks CC!</p>\n"
}
] |
2016/09/11
|
[
"https://wordpress.stackexchange.com/questions/238889",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102600/"
] |
I'm trying to make a social links menu for the footer in my theme. I want a menu to be customisable in Dashboard, I want the links to be relative to what's put in there.
Originally to get that, I did this:
```
<a href="http://www.facebook.com/" target="_blank"><i class="fa fa-facebook circle"></i></a>
<a href="http://www.google.com/" target="_blank"><i class="fa fa-google-plus circle"></i></a>
<a href="http://www.twitter.com/" target="_blank"><i class="fa fa-twitter circle"></i></a>
<a href="http://www.linkedin.com/" target="_blank"><i class="fa fa-linkedin circle"></i></a>
```
For hard-coded menu items.
Now, I want to use
```
<?php wp_nav_menu( array( 'theme_location' => 'social' ) ); ?>
```
To generate the `<li>` but realise that doing so puts the link label, i.e. `Facebook` inside the `<li><a>` tags.
i.e. `<li class="fa fa-facebook circle"><a href="fb.com">Facebook</a></li>`
Which isn't that great because 1. Facebook label gets in the way and 2. is the only thing that is clickable.
I want to get the link tag on the outside of my classes (being set automatically by Wordpress too through Menu customisation)
I realise I could write the `<i>` class inside the label for each menu item, but that defeats the purpose I'm going after here.
Edit: I'd love a solution that doesn't exclude hacking in some way.
|
This is a tough one. Normally I'd say use `text-indent:-99999px;` as part of the markup for `<a>` -- to get that link text off the screen. But you have that `fa` italic tag which is really text as well - so it gets shifted off the screen, too.
This solution is pretty ugly but you can probably tweak it for your use.
Wrap the social links inside a div:
```
<div id="social-wrapper">
<a href="http://www.facebook.com/" target="_blank"><i class="fa fa-facebook circle"></i>Facebook</a>
<a href="http://www.google.com/" target="_blank"><i class="fa fa-google-plus circle"></i>Google</a>
<a href="http://www.twitter.com/" target="_blank"><i class="fa fa-twitter circle"></i>Twitter</a>
<a href="http://www.linkedin.com/" target="_blank"><i class="fa fa-linkedin circle"></i>LinkedIn</a>
</div>
```
Then, .css like this:
```
#social-wrapper .fa {
color: #000;
}
#social-wrapper a {
color: transparent;
display: inline-block;
margin: 0 8px;
overflow: hidden;
width: 15px;
}
```
Set that width to accommodate your .fa icon width. Here is a [jsfiddle](https://jsfiddle.net/t1zk4u5n/) that shows how it works.
**EDIT:**
ok, didn't realize you couldn't get the above solution to work. Here's a less ugly version, still just using CSS. Anything beyond this and you will need to write your own implementation of `wp_nav_menu` to get the content the way you want it and not rely on a css solution.
Same HTML as above, with a wrapper div.
This CSS:
```
#social-wrapper {
text-indent: -99999px;
}
#social-wrapper a {
width: 30px;
float: left;
}
#social-wrapper .fa {
display: inline-block;
vertical-align: middle;
width: 0;
text-indent: 99999px;
}
```
And here's [another fiddle](https://jsfiddle.net/r21fooqh/) showing how it works.
|
238,905 |
<p>I need to add revision support to WooCommerce Products (at least for the main content). The developers are unwilling to do this until there is some support on Wordpress for the extra product fields: <a href="https://github.com/woothemes/woocommerce/issues/2178" rel="nofollow">https://github.com/woothemes/woocommerce/issues/2178</a></p>
<p>As I prefer partial revision support than nothing, I took a look around and found the following.</p>
<p>As of WooCommerce 2.6.4, we have this on woocommerce/includes/class-wc-post-types.php:</p>
<pre><code> register_post_type( 'product',
apply_filters( 'woocommerce_register_post_type_product',
array(
'labels' => array(
'name' => __( 'Products', 'woocommerce' ),
'singular_name' => __( 'Product', 'woocommerce' ),
'menu_name' => _x( 'Products', 'Admin menu name', 'woocommerce' ),
'add_new' => __( 'Add Product', 'woocommerce' ),
'add_new_item' => __( 'Add New Product', 'woocommerce' ),
'edit' => __( 'Edit', 'woocommerce' ),
'edit_item' => __( 'Edit Product', 'woocommerce' ),
'new_item' => __( 'New Product', 'woocommerce' ),
'view' => __( 'View Product', 'woocommerce' ),
'view_item' => __( 'View Product', 'woocommerce' ),
'search_items' => __( 'Search Products', 'woocommerce' ),
'not_found' => __( 'No Products found', 'woocommerce' ),
'not_found_in_trash' => __( 'No Products found in trash', 'woocommerce' ),
'parent' => __( 'Parent Product', 'woocommerce' ),
'featured_image' => __( 'Product Image', 'woocommerce' ),
'set_featured_image' => __( 'Set product image', 'woocommerce' ),
'remove_featured_image' => __( 'Remove product image', 'woocommerce' ),
'use_featured_image' => __( 'Use as product image', 'woocommerce' ),
'insert_into_item' => __( 'Insert into product', 'woocommerce' ),
'uploaded_to_this_item' => __( 'Uploaded to this product', 'woocommerce' ),
'filter_items_list' => __( 'Filter products', 'woocommerce' ),
'items_list_navigation' => __( 'Products navigation', 'woocommerce' ),
'items_list' => __( 'Products list', 'woocommerce' ),
),
'description' => __( 'This is where you can add new products to your store.', 'woocommerce' ),
'public' => true,
'show_ui' => true,
'capability_type' => 'product',
'map_meta_cap' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'hierarchical' => false, // Hierarchical causes memory issues - WP loads all records!
'rewrite' => $product_permalink ? array( 'slug' => untrailingslashit( $product_permalink ), 'with_front' => false, 'feeds' => true ) : false,
'query_var' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'comments', 'custom-fields', 'page-attributes', 'publicize', 'wpcom-markdown' ),
'has_archive' => ( $shop_page_id = wc_get_page_id( 'shop' ) ) && get_post( $shop_page_id ) ? get_page_uri( $shop_page_id ) : 'shop',
'show_in_nav_menus' => true
)
)
);
</code></pre>
<p>I can make it work adding a <code>'revisions'</code> to <code>'supports'</code> array.</p>
<p>But every upgrade will revert this change.</p>
<p>Now the question is: how to make this change as a child theme/plugin/whatever that can keep working even after WooCommerce upgrades?</p>
|
[
{
"answer_id": 238906,
"author": "Roy Ho",
"author_id": 67572,
"author_profile": "https://wordpress.stackexchange.com/users/67572",
"pm_score": 5,
"selected": true,
"text": "<p>As you pointed out already there is a filter.</p>\n\n<pre><code>add_filter( 'woocommerce_register_post_type_product', 'wpse_modify_product_post_type' );\n\nfunction wpse_modify_product_post_type( $args ) {\n $args['supports'][] = 'revisions';\n\n return $args;\n}\n</code></pre>\n\n<p>Put that in your child theme's functions.php file.</p>\n"
},
{
"answer_id": 291635,
"author": "Rohit Savaj",
"author_id": 93150,
"author_profile": "https://wordpress.stackexchange.com/users/93150",
"pm_score": 1,
"selected": false,
"text": "<p>Enables the revisions meta box in Page edit screen.</p>\n\n<pre><code>function wpcodex_add_excerpt_support_for_pages() {\n add_post_type_support( 'product', 'revisions' );\n}\nadd_action( 'init', 'wpcodex_add_excerpt_support_for_pages' );\n</code></pre>\n\n<p>this may help</p>\n"
}
] |
2016/09/11
|
[
"https://wordpress.stackexchange.com/questions/238905",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102609/"
] |
I need to add revision support to WooCommerce Products (at least for the main content). The developers are unwilling to do this until there is some support on Wordpress for the extra product fields: <https://github.com/woothemes/woocommerce/issues/2178>
As I prefer partial revision support than nothing, I took a look around and found the following.
As of WooCommerce 2.6.4, we have this on woocommerce/includes/class-wc-post-types.php:
```
register_post_type( 'product',
apply_filters( 'woocommerce_register_post_type_product',
array(
'labels' => array(
'name' => __( 'Products', 'woocommerce' ),
'singular_name' => __( 'Product', 'woocommerce' ),
'menu_name' => _x( 'Products', 'Admin menu name', 'woocommerce' ),
'add_new' => __( 'Add Product', 'woocommerce' ),
'add_new_item' => __( 'Add New Product', 'woocommerce' ),
'edit' => __( 'Edit', 'woocommerce' ),
'edit_item' => __( 'Edit Product', 'woocommerce' ),
'new_item' => __( 'New Product', 'woocommerce' ),
'view' => __( 'View Product', 'woocommerce' ),
'view_item' => __( 'View Product', 'woocommerce' ),
'search_items' => __( 'Search Products', 'woocommerce' ),
'not_found' => __( 'No Products found', 'woocommerce' ),
'not_found_in_trash' => __( 'No Products found in trash', 'woocommerce' ),
'parent' => __( 'Parent Product', 'woocommerce' ),
'featured_image' => __( 'Product Image', 'woocommerce' ),
'set_featured_image' => __( 'Set product image', 'woocommerce' ),
'remove_featured_image' => __( 'Remove product image', 'woocommerce' ),
'use_featured_image' => __( 'Use as product image', 'woocommerce' ),
'insert_into_item' => __( 'Insert into product', 'woocommerce' ),
'uploaded_to_this_item' => __( 'Uploaded to this product', 'woocommerce' ),
'filter_items_list' => __( 'Filter products', 'woocommerce' ),
'items_list_navigation' => __( 'Products navigation', 'woocommerce' ),
'items_list' => __( 'Products list', 'woocommerce' ),
),
'description' => __( 'This is where you can add new products to your store.', 'woocommerce' ),
'public' => true,
'show_ui' => true,
'capability_type' => 'product',
'map_meta_cap' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'hierarchical' => false, // Hierarchical causes memory issues - WP loads all records!
'rewrite' => $product_permalink ? array( 'slug' => untrailingslashit( $product_permalink ), 'with_front' => false, 'feeds' => true ) : false,
'query_var' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'comments', 'custom-fields', 'page-attributes', 'publicize', 'wpcom-markdown' ),
'has_archive' => ( $shop_page_id = wc_get_page_id( 'shop' ) ) && get_post( $shop_page_id ) ? get_page_uri( $shop_page_id ) : 'shop',
'show_in_nav_menus' => true
)
)
);
```
I can make it work adding a `'revisions'` to `'supports'` array.
But every upgrade will revert this change.
Now the question is: how to make this change as a child theme/plugin/whatever that can keep working even after WooCommerce upgrades?
|
As you pointed out already there is a filter.
```
add_filter( 'woocommerce_register_post_type_product', 'wpse_modify_product_post_type' );
function wpse_modify_product_post_type( $args ) {
$args['supports'][] = 'revisions';
return $args;
}
```
Put that in your child theme's functions.php file.
|
238,911 |
<p>I have this code I want to implement onto my website. I have successfully set up a child theme. This code is suppose to change the background every day of the week. I am not all too familiar with Wordpress, and I am wondering where I should place it and how. Can someone please give me step by step instruction what I need to do?</p>
<p>The code is below. Thank you very much.</p>
<hr>
<pre><code>function chgDailyImg()
{
var imagearray = new Array();
imagearray[0] = "sundaypic.jpg";
imagearray[1] = "mondaypic.jpg";
imagearray[2] = "tuesdaypic.jpg";
imagearray[3] = "wednesdaypic.jpg";
imagearray[4] = "thursdaypic.jpg";
imagearray[5] = "fridaypic.jpg";
imagearray[6] = "saturdaypic.jpg";
var d = new Date(); /*** create a date object for use ***/
var i = d.getDay(); /*** use the date object to get the day of the week - this will be a number from 0 to 6 - sunday=0, saturday=6 -it's the way counting works in javascript it starts at 0 like in the arrays ***/
document.getElementById("dailyImg").src = imagearray;
}/* CSS Document *//* CSS Document */
</code></pre>
|
[
{
"answer_id": 238916,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The code you've posted is JavaScript, and it should be placed within a JavaScript file inside of your child theme, e.g.:</p>\n\n<p><code>/your-child-theme/js/background-changer.js</code></p>\n\n<p>Your child theme should then enqueue your JS file from within its <code>functions.php</code> file, like so: </p>\n\n<pre><code>function wpse238911_load_js() {\n wp_enqueue_script( 'wpse238911_load_js', get_stylesheet_directory_uri() . '/js/background-changer.js', array(), false, false );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse238911_load_js' );\n</code></pre>\n\n<p>This is really the only WordPress specific part of your issue. </p>\n\n<p>It looks like there may be a some problems with your JS too. You are assigning the entire <code>imagearray</code> to the <code>src</code> attribute of the <code>#dailyImg</code> element. It looks like you should be using <code>imagearray[i]</code>. Also <code>chgDailyImg()</code> is never executed. Here's a possibly helpful fixed version:</p>\n\n<pre><code>function chgDailyImg() {\n\n var imagearray = new Array();\n imagearray[0] = \"sundaypic.jpg\";\n imagearray[1] = \"mondaypic.jpg\";\n imagearray[2] = \"tuesdaypic.jpg\";\n imagearray[3] = \"wednesdaypic.jpg\";\n imagearray[4] = \"thursdaypic.jpg\";\n imagearray[5] = \"fridaypic.jpg\";\n imagearray[6] = \"saturdaypic.jpg\";\n\n var d = new Date(); /*** create a date object for use ***/\n var i = d.getDay(); /*** use the date object to get the day of the week - this will be a number from 0 to 6 - sunday=0, saturday=6 -it's the way counting works in javascript it starts at 0 like in the arrays ***/\n\n document.getElementById(\"dailyImg\").src = imagearray[i];\n}\nchgDailyImg();\n</code></pre>\n\n<p>At this point we're talking about vanilla JavaScript, and that's off topic for this site. You might have better luck over on Stack Overflow for JavaScript questions.</p>\n"
},
{
"answer_id": 238917,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 3,
"selected": true,
"text": "<p>In this scenario, the tag that you want to call to execute your function is the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\"><code>wp_head()</code></a>.</p>\n\n<p>Looking at the code you provides, you have the idea down, but I decided to rewrite it differently. In your child theme's <a href=\"https://codex.wordpress.org/Child_Themes#Using_functions.php\" rel=\"nofollow\"><code>functions.php</code></a> file, add the following:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_238911_weekly_background' );\n function wpse_238911_weekly_background() {\n $day = date( \"l\" );\n\n switch( $day ) {\n case 'Monday':\n $background_image = 'mon-img.jpg';\n break;\n case 'Tuesday':\n $background_image = 'tue-img.jpg';\n break;\n case 'Wednesday':\n $background_image = 'wed-img.jpg';\n break;\n case 'Thursday':\n $background_image = 'thu-img.jpg';\n break;\n case 'Friday':\n $background_image = 'fri-img.jpg';\n break;\n case 'Saturday':\n $background_image = 'sat-img.jpg';\n break;\n case 'Sunday':\n default:\n $background_image = 'sun-img.jpg';\n break;\n }\n\n ?>\n <style type=\"text/css\">\n body {\n background-image: url( 'http://web.site/img/<?php echo $background_image; ?>' );\n }\n </style>\n <?php\n}\n</code></pre>\n\n<p>Just switch out the <code>mon-img.jpg</code> to your actual image names and change the <code>http://web.site/img/</code> path to wherever you will be having your day-of-the-week images stored.</p>\n"
}
] |
2016/09/12
|
[
"https://wordpress.stackexchange.com/questions/238911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102602/"
] |
I have this code I want to implement onto my website. I have successfully set up a child theme. This code is suppose to change the background every day of the week. I am not all too familiar with Wordpress, and I am wondering where I should place it and how. Can someone please give me step by step instruction what I need to do?
The code is below. Thank you very much.
---
```
function chgDailyImg()
{
var imagearray = new Array();
imagearray[0] = "sundaypic.jpg";
imagearray[1] = "mondaypic.jpg";
imagearray[2] = "tuesdaypic.jpg";
imagearray[3] = "wednesdaypic.jpg";
imagearray[4] = "thursdaypic.jpg";
imagearray[5] = "fridaypic.jpg";
imagearray[6] = "saturdaypic.jpg";
var d = new Date(); /*** create a date object for use ***/
var i = d.getDay(); /*** use the date object to get the day of the week - this will be a number from 0 to 6 - sunday=0, saturday=6 -it's the way counting works in javascript it starts at 0 like in the arrays ***/
document.getElementById("dailyImg").src = imagearray;
}/* CSS Document *//* CSS Document */
```
|
In this scenario, the tag that you want to call to execute your function is the [`wp_head()`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head).
Looking at the code you provides, you have the idea down, but I decided to rewrite it differently. In your child theme's [`functions.php`](https://codex.wordpress.org/Child_Themes#Using_functions.php) file, add the following:
```
add_action( 'wp_head', 'wpse_238911_weekly_background' );
function wpse_238911_weekly_background() {
$day = date( "l" );
switch( $day ) {
case 'Monday':
$background_image = 'mon-img.jpg';
break;
case 'Tuesday':
$background_image = 'tue-img.jpg';
break;
case 'Wednesday':
$background_image = 'wed-img.jpg';
break;
case 'Thursday':
$background_image = 'thu-img.jpg';
break;
case 'Friday':
$background_image = 'fri-img.jpg';
break;
case 'Saturday':
$background_image = 'sat-img.jpg';
break;
case 'Sunday':
default:
$background_image = 'sun-img.jpg';
break;
}
?>
<style type="text/css">
body {
background-image: url( 'http://web.site/img/<?php echo $background_image; ?>' );
}
</style>
<?php
}
```
Just switch out the `mon-img.jpg` to your actual image names and change the `http://web.site/img/` path to wherever you will be having your day-of-the-week images stored.
|
238,915 |
<p>How can a <strong>category</strong> be assigned to a <em>new front-end post</em> submission?<br><br>
<em>Posting works</em>, Category is not assigned.
Would like to be able to add more than one, if possible.<br>
Both are CPT and custom taxonomies.<br><br></p>
<pre><code>if ( isset( $_POST['submitted'] ) && isset( $_POST['new_post_nonce_field'] ) && wp_verify_nonce( $_POST['new_post_nonce_field'], 'new_post_nonce_action' ) ) {
$new_post = array(
'post_content' => $_POST['post-content'],
'post_title' => wp_strip_all_tags( $_POST['post-title'] ),
'post_type' => 'custom_pt',
'post_category' => array(
'custom_tax' => $_POST['custom_tax']
),
);
if ( !$hasError == true ) {
$post_id = wp_insert_post( $new_post );
if ( post_id ) {
wp_redirect( home_url() );
}
}
}
</code></pre>
<p>.</p>
<pre><code> <form id="new_post" method="POST" action="" enctype="multipart/form-data">
<label for="post-title">The Title</label>
<input id="post-title" name="post-title" type="text" />
<label for="post-content">The Content</label>
<textarea id="post-content" name="post-content"></textarea>
<label for="custom_tax">The Categories</label>
<?php wp_dropdown_categories( 'tab_index=10&taxonomy=custom_tax&name=custom_tax&class=custom_tax&show_option_all=Select a category' ); ?>
<?php wp_nonce_field( 'new_post_nonce_action', 'new_post_nonce_field' ); ?>
<button type="submit">Publish</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</code></pre>
<p>Thank You.</p>
|
[
{
"answer_id": 238923,
"author": "Navin Bhudiya",
"author_id": 98536,
"author_profile": "https://wordpress.stackexchange.com/users/98536",
"pm_score": -1,
"selected": false,
"text": "<p>By using <strong>wp_set_object_terms</strong> you can set post category , for more details please follow this link \n<a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_set_object_terms</a></p>\n"
},
{
"answer_id": 238932,
"author": "10Y01",
"author_id": 101510,
"author_profile": "https://wordpress.stackexchange.com/users/101510",
"pm_score": 2,
"selected": false,
"text": "<p>I checked and it works with this:<br></p>\n\n<pre><code>$new_post = array(\n 'post_content' => $_POST['post-content'],\n 'post_title' => wp_strip_all_tags( $_POST['post-title'] ),\n 'post_type' => 'custom_pt'\n);\n</code></pre>\n\n<p><em>note: I used a text input for the single category</em></p>\n\n<pre><code><input id=\"input-name-value\" name=\"input-name-value\" type=\"text\" />\n</code></pre>\n\n<p>I havent tried it with a select - option dropdown. or more than 1 category.</p>\n\n<pre><code>$post_id = wp_insert_post( $new_post );\n\nwp_set_object_terms( $post_id, $_POST['input-name-value'], 'yourCategory' );\n</code></pre>\n\n<p>It would be nice if someone could pimp this out in order to get full functionallity.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 239474,
"author": "10Y01",
"author_id": 101510,
"author_profile": "https://wordpress.stackexchange.com/users/101510",
"pm_score": 0,
"selected": false,
"text": "<p>Found this:</p>\n\n<pre><code>$postCats = trim( $_POST['post-cats']; )\n$postCats = explode( ',', $postCats );\n\nwp_set_object_terms( $post_id, array( $postCats[0], $postCats[1], $postCats[2], $postCats[3], $postCats[4] ), 'category' );\n</code></pre>\n\n<p>Works the same for tags</p>\n\n<p>I'm still wondering if there is a way to add unlimited categories without declaring a limited number in an array (like above).</p>\n\n<p>'d be great if someone helped me out with that.</p>\n"
}
] |
2016/09/12
|
[
"https://wordpress.stackexchange.com/questions/238915",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101510/"
] |
How can a **category** be assigned to a *new front-end post* submission?
*Posting works*, Category is not assigned.
Would like to be able to add more than one, if possible.
Both are CPT and custom taxonomies.
```
if ( isset( $_POST['submitted'] ) && isset( $_POST['new_post_nonce_field'] ) && wp_verify_nonce( $_POST['new_post_nonce_field'], 'new_post_nonce_action' ) ) {
$new_post = array(
'post_content' => $_POST['post-content'],
'post_title' => wp_strip_all_tags( $_POST['post-title'] ),
'post_type' => 'custom_pt',
'post_category' => array(
'custom_tax' => $_POST['custom_tax']
),
);
if ( !$hasError == true ) {
$post_id = wp_insert_post( $new_post );
if ( post_id ) {
wp_redirect( home_url() );
}
}
}
```
.
```
<form id="new_post" method="POST" action="" enctype="multipart/form-data">
<label for="post-title">The Title</label>
<input id="post-title" name="post-title" type="text" />
<label for="post-content">The Content</label>
<textarea id="post-content" name="post-content"></textarea>
<label for="custom_tax">The Categories</label>
<?php wp_dropdown_categories( 'tab_index=10&taxonomy=custom_tax&name=custom_tax&class=custom_tax&show_option_all=Select a category' ); ?>
<?php wp_nonce_field( 'new_post_nonce_action', 'new_post_nonce_field' ); ?>
<button type="submit">Publish</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
```
Thank You.
|
I checked and it works with this:
```
$new_post = array(
'post_content' => $_POST['post-content'],
'post_title' => wp_strip_all_tags( $_POST['post-title'] ),
'post_type' => 'custom_pt'
);
```
*note: I used a text input for the single category*
```
<input id="input-name-value" name="input-name-value" type="text" />
```
I havent tried it with a select - option dropdown. or more than 1 category.
```
$post_id = wp_insert_post( $new_post );
wp_set_object_terms( $post_id, $_POST['input-name-value'], 'yourCategory' );
```
It would be nice if someone could pimp this out in order to get full functionallity.
Thanks.
|
238,941 |
<p>I'm trying to add some javascript to my theme customizer. My JS file is loaded no problem and my document ready event works but <code>wp.customize.bind()</code> isn't calling my callback.</p>
<pre><code>jQuery(document).on('ready', function(){
console.log('binding')
wp.customize.bind('ready', function(){
console.log('ready')
})
})
</code></pre>
<p><code>binding</code> gets outputed to the console but <code>ready</code> does not.</p>
<p>What am I missing? there seems to be little to no documentation on using the javascript here.</p>
|
[
{
"answer_id": 284297,
"author": "Digvijayad",
"author_id": 118765,
"author_profile": "https://wordpress.stackexchange.com/users/118765",
"pm_score": 0,
"selected": false,
"text": "<p>I had same problem. \nThe reason it was not binding for me was because I had this error <code>\"Uncaught TypeError: Cannot read property 'unsync' of undefined\"</code> on my console.</p>\n\n<p>It was caused because I removed the <code>header_textcolor</code> settings from the theme template by using <code>$wp_customize->remove_setting( 'header_textcolor' );</code> but it was still being referenced in the js.</p>\n\n<p>After fixing this, bind worked as intended. </p>\n"
},
{
"answer_id": 286508,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "<p>Do not put the Customizer <code>ready</code> event handler inside of the jQuery <code>event</code> handler. The Customizer <code>ready</code> will trigger at jQuery <code>ready</code>, so you are adding the event handler too late. Just do:</p>\n\n<pre><code>wp.customize.bind('ready', function(){\n console.log('ready');\n});\n</code></pre>\n\n<p>Your JS needs to be enqueued with <code>customize-controls</code> script as its dependency. Enqueue at the <code>customize_controls_enqueue_scripts</code> action.</p>\n"
}
] |
2016/09/12
|
[
"https://wordpress.stackexchange.com/questions/238941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85357/"
] |
I'm trying to add some javascript to my theme customizer. My JS file is loaded no problem and my document ready event works but `wp.customize.bind()` isn't calling my callback.
```
jQuery(document).on('ready', function(){
console.log('binding')
wp.customize.bind('ready', function(){
console.log('ready')
})
})
```
`binding` gets outputed to the console but `ready` does not.
What am I missing? there seems to be little to no documentation on using the javascript here.
|
Do not put the Customizer `ready` event handler inside of the jQuery `event` handler. The Customizer `ready` will trigger at jQuery `ready`, so you are adding the event handler too late. Just do:
```
wp.customize.bind('ready', function(){
console.log('ready');
});
```
Your JS needs to be enqueued with `customize-controls` script as its dependency. Enqueue at the `customize_controls_enqueue_scripts` action.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.