Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jmcausing/15cc506170438bed139eafdf62445ddb to your computer and use it in GitHub Desktop.
Save jmcausing/15cc506170438bed139eafdf62445ddb to your computer and use it in GitHub Desktop.
Dynamic WP shortcodes from each post - custom post type
// Load causing_forms_query() function after WP loads.
add_action( 'init', 'causing_forms_query' );
function causing_forms_query() {
add_shortcode('cforms', 'cforms_scode');
}
function cforms_scode( $attr, $content="") {
// connect to database with post type 'causing_forms' to get the ID of each post. You can use post_title if you want.
global $wpdb;
$post_type = 'causing_forms';
$my_query = $wpdb->get_results("SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'causing_forms' AND post_status IN ('draft', 'publish') ");
if ( !is_null($my_query) ) { // check if query is not empty
// Loop start
foreach( $my_query as $cforms_query) {
$cforms_id = $cforms_query->ID; // post_id variable
$args = shortcode_atts( array(
'the_post_id' => $cforms_id // pass arguments post_id to shortcodes so that shortcodes can have parameters like id. ex: [cforms ID=12]
), $attr ); // ID is dynamic so it will detect which post ID and content to look for.
// get the html source from the custom field
$html_field = get_field( 'cforms-example_html_form', $args['the_post_id'] );
// content of shortcodes
// displays the ID and content of html_field from ACF (html codes)
$output = '
<div class="your_class">
<h1 style="color:red";>This is the Post ID of this Shortcode: ' . $args['the_post_id'] .'</h1>
<p> '. $html_field .' </p>
</div>
';
// return the conent of shortcodes according to post ID.
return $output;
}
// Loop end
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment